@tuturuuu/ai 0.0.11 → 0.1.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.
@@ -0,0 +1,507 @@
1
+ import {
2
+ type Adapter,
3
+ type AdapterPostableMessage,
4
+ type ChatInstance,
5
+ type FetchOptions,
6
+ type FetchResult,
7
+ type FormattedContent,
8
+ Message,
9
+ parseMarkdown,
10
+ type RawMessage,
11
+ type StreamChunk,
12
+ type StreamOptions,
13
+ stringifyMarkdown,
14
+ type ThreadInfo,
15
+ type UserInfo,
16
+ } from 'chat';
17
+ import {
18
+ type API,
19
+ type Credentials,
20
+ ThreadType,
21
+ Zalo,
22
+ type Message as ZcaMessage,
23
+ } from 'zca-js';
24
+
25
+ export interface ZaloPersonalAdapterConfig {
26
+ channelId: string;
27
+ cookieJson: string;
28
+ displayName: string;
29
+ imei: string;
30
+ language?: string;
31
+ ownId?: string | null;
32
+ userAgent: string;
33
+ }
34
+
35
+ export interface ZaloPersonalStatus {
36
+ connected: boolean;
37
+ lastError: string | null;
38
+ lastEventAt: string | null;
39
+ ownId: string | null;
40
+ running: boolean;
41
+ startedAt: string | null;
42
+ }
43
+
44
+ export interface ZaloPersonalThreadRef {
45
+ externalThreadId: string;
46
+ threadType: ThreadType;
47
+ }
48
+
49
+ export interface ZaloPersonalSentRaw {
50
+ externalThreadId: string;
51
+ id: string;
52
+ isSelf: true;
53
+ response: unknown;
54
+ text: string;
55
+ threadId: string;
56
+ threadType: ThreadType;
57
+ ts: number;
58
+ }
59
+
60
+ export type ZaloPersonalRawMessage = ZcaMessage | ZaloPersonalSentRaw;
61
+
62
+ export type ZaloPersonalAdapter = Adapter<
63
+ ZaloPersonalThreadRef,
64
+ ZaloPersonalRawMessage
65
+ > & {
66
+ getPersonalStatus(): ZaloPersonalStatus;
67
+ startPersonalListener(): Promise<ZaloPersonalStatus>;
68
+ stopPersonalListener(): Promise<ZaloPersonalStatus>;
69
+ validateLogin(): Promise<ZaloPersonalStatus>;
70
+ };
71
+
72
+ const THREAD_ID_PREFIX = 'zalo-personal';
73
+
74
+ export function parseZaloPersonalCookieJson(
75
+ cookieJson: string
76
+ ): Credentials['cookie'] {
77
+ const parsed = JSON.parse(cookieJson) as unknown;
78
+
79
+ if (Array.isArray(parsed)) {
80
+ return parsed as Credentials['cookie'];
81
+ }
82
+
83
+ if (isRecord(parsed) && Array.isArray(parsed.cookies)) {
84
+ return parsed as Credentials['cookie'];
85
+ }
86
+
87
+ throw new Error('zalo_personal_cookie_json_invalid');
88
+ }
89
+
90
+ export function createZaloPersonalAdapter(
91
+ config: ZaloPersonalAdapterConfig
92
+ ): ZaloPersonalAdapter {
93
+ let api: API | null = null;
94
+ let chat: ChatInstance | null = null;
95
+ let listenersAttached = false;
96
+ let status: ZaloPersonalStatus = {
97
+ connected: false,
98
+ lastError: null,
99
+ lastEventAt: null,
100
+ ownId: config.ownId?.trim() || null,
101
+ running: false,
102
+ startedAt: null,
103
+ };
104
+
105
+ function setStatus(update: Partial<ZaloPersonalStatus>) {
106
+ status = { ...status, ...update };
107
+ return status;
108
+ }
109
+
110
+ function encodeThreadId(ref: ZaloPersonalThreadRef) {
111
+ return [
112
+ THREAD_ID_PREFIX,
113
+ config.channelId,
114
+ ref.threadType === ThreadType.Group ? 'group' : 'user',
115
+ ref.externalThreadId,
116
+ ].join(':');
117
+ }
118
+
119
+ function decodeThreadId(threadId: string): ZaloPersonalThreadRef {
120
+ const [prefix, channelId, rawType, ...idParts] = threadId.split(':');
121
+
122
+ if (
123
+ prefix !== THREAD_ID_PREFIX ||
124
+ channelId !== config.channelId ||
125
+ !rawType ||
126
+ idParts.length === 0
127
+ ) {
128
+ return {
129
+ externalThreadId: threadId,
130
+ threadType: ThreadType.User,
131
+ };
132
+ }
133
+
134
+ return {
135
+ externalThreadId: idParts.join(':'),
136
+ threadType: rawType === 'group' ? ThreadType.Group : ThreadType.User,
137
+ };
138
+ }
139
+
140
+ function messageThreadId(raw: ZcaMessage) {
141
+ return encodeThreadId({
142
+ externalThreadId: raw.threadId,
143
+ threadType: raw.type,
144
+ });
145
+ }
146
+
147
+ async function connect() {
148
+ if (api) return api;
149
+
150
+ try {
151
+ if (!config.cookieJson.trim() || !config.imei.trim()) {
152
+ throw new Error('zalo_personal_credentials_missing');
153
+ }
154
+
155
+ const zalo = new Zalo();
156
+ api = await zalo.login({
157
+ cookie: parseZaloPersonalCookieJson(config.cookieJson),
158
+ imei: config.imei,
159
+ language: config.language,
160
+ userAgent: config.userAgent,
161
+ });
162
+
163
+ const ownId = api.getOwnId();
164
+ setStatus({
165
+ connected: true,
166
+ lastError: null,
167
+ ownId: ownId || status.ownId,
168
+ });
169
+
170
+ return api;
171
+ } catch (error) {
172
+ setStatus({
173
+ connected: false,
174
+ lastError: error instanceof Error ? error.message : String(error),
175
+ running: false,
176
+ });
177
+ throw error;
178
+ }
179
+ }
180
+
181
+ function attachListeners(apiInstance: API) {
182
+ if (listenersAttached) return;
183
+
184
+ apiInstance.listener.on('connected', () => {
185
+ setStatus({
186
+ connected: true,
187
+ lastError: null,
188
+ running: true,
189
+ });
190
+ });
191
+ apiInstance.listener.on('disconnected', (_code, reason) => {
192
+ setStatus({
193
+ connected: false,
194
+ lastError: reason || null,
195
+ running: false,
196
+ });
197
+ });
198
+ apiInstance.listener.on('closed', (_code, reason) => {
199
+ setStatus({
200
+ connected: false,
201
+ lastError: reason || null,
202
+ running: false,
203
+ });
204
+ });
205
+ apiInstance.listener.on('error', (error) => {
206
+ setStatus({
207
+ lastError: error instanceof Error ? error.message : String(error),
208
+ });
209
+ });
210
+ apiInstance.listener.on('message', (message) => {
211
+ void handleIncomingMessage(message);
212
+ });
213
+
214
+ listenersAttached = true;
215
+ }
216
+
217
+ async function handleIncomingMessage(raw: ZcaMessage) {
218
+ if (raw.isSelf || typeof raw.data.content !== 'string') {
219
+ return;
220
+ }
221
+
222
+ const sdkMessage = adapter.parseMessage(raw);
223
+ setStatus({ lastEventAt: new Date().toISOString() });
224
+
225
+ await chat?.processMessage(adapter, sdkMessage.threadId, sdkMessage, {
226
+ waitUntil: (task) => {
227
+ void task.catch((error) => {
228
+ setStatus({
229
+ lastError: error instanceof Error ? error.message : String(error),
230
+ });
231
+ });
232
+ },
233
+ });
234
+ }
235
+
236
+ function unsupported(feature: string) {
237
+ return new Error(`zalo_personal_${feature}_unsupported`);
238
+ }
239
+
240
+ const adapter: ZaloPersonalAdapter = {
241
+ addReaction: async () => {
242
+ throw unsupported('reaction');
243
+ },
244
+ channelIdFromThreadId: (_threadId) => config.channelId,
245
+ decodeThreadId,
246
+ deleteMessage: async () => {
247
+ throw unsupported('delete');
248
+ },
249
+ disconnect: async () => {
250
+ api?.listener.stop();
251
+ api = null;
252
+ listenersAttached = false;
253
+ setStatus({
254
+ connected: false,
255
+ running: false,
256
+ });
257
+ },
258
+ editMessage: async () => {
259
+ throw unsupported('edit');
260
+ },
261
+ encodeThreadId,
262
+ fetchMessages: async (
263
+ threadId,
264
+ options?: FetchOptions
265
+ ): Promise<FetchResult<ZaloPersonalRawMessage>> => {
266
+ const apiInstance = await connect();
267
+ const thread = decodeThreadId(threadId);
268
+
269
+ if (thread.threadType !== ThreadType.Group) {
270
+ return { messages: [] };
271
+ }
272
+
273
+ const result = await apiInstance.getGroupChatHistory(
274
+ thread.externalThreadId,
275
+ options?.limit ?? 50
276
+ );
277
+
278
+ const messages = result.groupMsgs
279
+ .map((message) => adapter.parseMessage(message))
280
+ .sort(
281
+ (a, b) =>
282
+ a.metadata.dateSent.getTime() - b.metadata.dateSent.getTime()
283
+ );
284
+
285
+ return { messages };
286
+ },
287
+ fetchThread: async (threadId): Promise<ThreadInfo> => {
288
+ const thread = decodeThreadId(threadId);
289
+
290
+ return {
291
+ channelId: config.channelId,
292
+ channelName: config.displayName,
293
+ id: threadId,
294
+ isDM: thread.threadType === ThreadType.User,
295
+ metadata: {
296
+ accountMode: 'personal',
297
+ externalThreadId: thread.externalThreadId,
298
+ threadType: thread.threadType === ThreadType.Group ? 'group' : 'user',
299
+ },
300
+ };
301
+ },
302
+ getPersonalStatus: () => status,
303
+ getUser: async (userId): Promise<UserInfo | null> => ({
304
+ fullName: userId,
305
+ isBot: false,
306
+ userId,
307
+ userName: userId,
308
+ }),
309
+ handleWebhook: async () =>
310
+ Response.json(
311
+ { error: 'Personal Zalo channels use a listener, not webhooks.' },
312
+ { status: 404 }
313
+ ),
314
+ initialize: async (instance) => {
315
+ chat = instance;
316
+ },
317
+ isDM: (threadId) => decodeThreadId(threadId).threadType === ThreadType.User,
318
+ lockScope: 'thread',
319
+ name: 'zalo',
320
+ openDM: async (userId) =>
321
+ encodeThreadId({
322
+ externalThreadId: userId,
323
+ threadType: ThreadType.User,
324
+ }),
325
+ parseMessage: (raw) => {
326
+ if (isSentRaw(raw)) {
327
+ return new Message<ZaloPersonalRawMessage>({
328
+ attachments: [],
329
+ author: {
330
+ fullName: config.displayName,
331
+ isBot: true,
332
+ isMe: true,
333
+ userId: status.ownId ?? 'zalo-personal-self',
334
+ userName: config.displayName,
335
+ },
336
+ formatted: parseMarkdown(raw.text),
337
+ id: raw.id,
338
+ metadata: {
339
+ dateSent: new Date(raw.ts),
340
+ edited: false,
341
+ },
342
+ raw,
343
+ text: raw.text,
344
+ threadId: raw.threadId,
345
+ });
346
+ }
347
+
348
+ const text =
349
+ typeof raw.data.content === 'string'
350
+ ? raw.data.content
351
+ : '[Unsupported Zalo message]';
352
+ const authorId =
353
+ raw.data.uidFrom || raw.data.userId || (raw.isSelf ? status.ownId : '');
354
+
355
+ return new Message<ZaloPersonalRawMessage>({
356
+ attachments: [],
357
+ author: {
358
+ fullName: raw.data.dName || authorId || 'Zalo user',
359
+ isBot: raw.isSelf,
360
+ isMe: raw.isSelf,
361
+ userId: authorId || raw.threadId,
362
+ userName: raw.data.dName || authorId || raw.threadId,
363
+ },
364
+ formatted: parseMarkdown(text),
365
+ id: raw.data.msgId || raw.data.cliMsgId || `${raw.data.ts}`,
366
+ metadata: {
367
+ dateSent: dateFromZaloTimestamp(raw.data.ts),
368
+ edited: false,
369
+ },
370
+ raw,
371
+ text,
372
+ threadId: messageThreadId(raw),
373
+ });
374
+ },
375
+ postMessage: async (threadId, message) => {
376
+ const apiInstance = await connect();
377
+ const thread = decodeThreadId(threadId);
378
+ const text = extractPostableText(message);
379
+ const response = await apiInstance.sendMessage(
380
+ { msg: text },
381
+ thread.externalThreadId,
382
+ thread.threadType
383
+ );
384
+ const id = String(
385
+ response.message?.msgId ??
386
+ response.attachment.at(0)?.msgId ??
387
+ Date.now()
388
+ );
389
+
390
+ return {
391
+ id,
392
+ raw: {
393
+ externalThreadId: thread.externalThreadId,
394
+ id,
395
+ isSelf: true,
396
+ response,
397
+ text,
398
+ threadId,
399
+ threadType: thread.threadType,
400
+ ts: Date.now(),
401
+ },
402
+ threadId,
403
+ };
404
+ },
405
+ removeReaction: async () => {
406
+ throw unsupported('reaction');
407
+ },
408
+ renderFormatted: (content: FormattedContent) => stringifyMarkdown(content),
409
+ startPersonalListener: async () => {
410
+ const apiInstance = await connect();
411
+ attachListeners(apiInstance);
412
+ apiInstance.listener.start({ retryOnClose: true });
413
+
414
+ return setStatus({
415
+ connected: true,
416
+ lastError: null,
417
+ running: true,
418
+ startedAt: status.startedAt ?? new Date().toISOString(),
419
+ });
420
+ },
421
+ startTyping: async (threadId) => {
422
+ const apiInstance = await connect();
423
+ const thread = decodeThreadId(threadId);
424
+ await apiInstance.sendTypingEvent(
425
+ thread.externalThreadId,
426
+ thread.threadType
427
+ );
428
+ },
429
+ stopPersonalListener: async () => {
430
+ api?.listener.stop();
431
+
432
+ return setStatus({
433
+ connected: false,
434
+ running: false,
435
+ });
436
+ },
437
+ stream: async (
438
+ threadId,
439
+ textStream: AsyncIterable<string | StreamChunk>,
440
+ _options?: StreamOptions
441
+ ): Promise<RawMessage<ZaloPersonalRawMessage> | null> => {
442
+ let text = '';
443
+
444
+ for await (const chunk of textStream) {
445
+ if (typeof chunk === 'string') {
446
+ text += chunk;
447
+ } else if (chunk.type === 'markdown_text') {
448
+ text += chunk.text;
449
+ }
450
+ }
451
+
452
+ return adapter.postMessage(threadId, text.trim() || 'Done.');
453
+ },
454
+ userName: config.displayName,
455
+ validateLogin: async () => {
456
+ const apiInstance = await connect();
457
+
458
+ return setStatus({
459
+ connected: true,
460
+ lastError: null,
461
+ ownId: apiInstance.getOwnId() || status.ownId,
462
+ });
463
+ },
464
+ };
465
+
466
+ return adapter;
467
+ }
468
+
469
+ function dateFromZaloTimestamp(value: string) {
470
+ const numeric = Number.parseInt(value, 10);
471
+
472
+ if (!Number.isFinite(numeric)) {
473
+ return new Date();
474
+ }
475
+
476
+ return new Date(numeric < 1_000_000_000_000 ? numeric * 1000 : numeric);
477
+ }
478
+
479
+ function extractPostableText(message: AdapterPostableMessage) {
480
+ if (typeof message === 'string') {
481
+ return message;
482
+ }
483
+
484
+ if (isRecord(message)) {
485
+ if (typeof message.markdown === 'string') {
486
+ return message.markdown;
487
+ }
488
+
489
+ if (typeof message.text === 'string') {
490
+ return message.text;
491
+ }
492
+
493
+ if (isRecord(message.ast)) {
494
+ return stringifyMarkdown(message.ast as unknown as FormattedContent);
495
+ }
496
+ }
497
+
498
+ return String(message);
499
+ }
500
+
501
+ function isRecord(value: unknown): value is Record<string, unknown> {
502
+ return typeof value === 'object' && value !== null;
503
+ }
504
+
505
+ function isSentRaw(value: unknown): value is ZaloPersonalSentRaw {
506
+ return isRecord(value) && value.isSelf === true && 'response' in value;
507
+ }
@@ -2,10 +2,7 @@ import type {
2
2
  AiFeature,
3
3
  CreditErrorCode,
4
4
  } from '@tuturuuu/ai/credits/constants';
5
- import {
6
- matchesAllowedModel,
7
- resolveGatewayModelId,
8
- } from '@tuturuuu/ai/credits/model-mapping';
5
+ import { resolveGatewayModelId } from '@tuturuuu/ai/credits/model-mapping';
9
6
  import type {
10
7
  CreditCheckResult,
11
8
  CreditDeductionResult,
@@ -14,11 +11,8 @@ import type {
14
11
  import { createAdminClient } from '@tuturuuu/supabase/next/server';
15
12
  import {
16
13
  decrementAiCreditChargeInFlight,
17
- hasAiCreditChargeInFlight,
18
14
  incrementAiCreditChargeInFlight,
19
15
  invalidateAiCreditSnapshot,
20
- isAiCreditSnapshotUsable,
21
- readAiCreditSnapshot,
22
16
  } from '@tuturuuu/utils/ai-temp-auth';
23
17
 
24
18
  type DeductAiCreditsRpcRow = {
@@ -52,35 +46,8 @@ export async function checkAiCredits(
52
46
  }
53
47
 
54
48
  const gatewayModelId = resolveGatewayModelId(modelId);
55
-
56
- if (opts?.userId) {
57
- const snapshot = await readAiCreditSnapshot({
58
- wsId,
59
- userId: opts.userId,
60
- });
61
- const inFlight = await hasAiCreditChargeInFlight({
62
- wsId,
63
- userId: opts.userId,
64
- });
65
- if (
66
- isAiCreditSnapshotUsable(snapshot, { inFlight }) &&
67
- (snapshot.allowedFeatures.length === 0 ||
68
- snapshot.allowedFeatures.includes(feature)) &&
69
- matchesAllowedModel(gatewayModelId, snapshot.allowedModels)
70
- ) {
71
- return {
72
- allowed: snapshot.remainingCredits > 0,
73
- remainingCredits: snapshot.remainingCredits,
74
- tier: snapshot.tier,
75
- maxOutputTokens: snapshot.maxOutputTokens,
76
- errorCode: snapshot.remainingCredits > 0 ? null : 'CREDITS_EXHAUSTED',
77
- errorMessage:
78
- snapshot.remainingCredits > 0
79
- ? null
80
- : 'AI credits exhausted. Please upgrade your plan or purchase more credits.',
81
- };
82
- }
83
- }
49
+ // Status snapshots are UI hints only. The RPC is the authoritative gate for
50
+ // daily credit, daily request, and feature-specific request limits.
84
51
 
85
52
  const sbAdmin = await createAdminClient();
86
53
  const { data, error } = await sbAdmin.rpc('check_ai_credit_allowance', {
@@ -78,7 +78,7 @@ export function isGoogleModelId(modelId: string): boolean {
78
78
  if (slashIndex === -1) return true;
79
79
 
80
80
  const provider = modelId.slice(0, slashIndex);
81
- return provider === 'google' || provider === 'google-vertex';
81
+ return provider === 'google';
82
82
  }
83
83
 
84
84
  /**
@@ -307,81 +307,6 @@ export async function executeConvertFileToMarkdown(
307
307
  }
308
308
  }
309
309
 
310
- if (sourceUrl) {
311
- const markitdownTimeoutMs = resolveMarkitdownTimeoutMs();
312
- const abortController = new AbortController();
313
- const timeoutId = setTimeout(
314
- () => abortController.abort(),
315
- markitdownTimeoutMs
316
- );
317
-
318
- let metadataResponse: Response;
319
- try {
320
- metadataResponse = await fetch(markitdownUrl, {
321
- method: 'POST',
322
- headers: {
323
- Authorization: `Bearer ${markitdownSecret}`,
324
- 'Content-Type': 'application/json',
325
- },
326
- body: JSON.stringify({
327
- url: sourceUrl,
328
- filename: fileNameArg || 'youtube.md',
329
- enable_plugins: true,
330
- }),
331
- signal: abortController.signal,
332
- });
333
- } catch (error) {
334
- const message =
335
- error instanceof Error && error.name === 'AbortError'
336
- ? `YouTube metadata lookup timed out after ${markitdownTimeoutMs}ms.`
337
- : 'Failed to reach YouTube metadata service.';
338
- console.error('YouTube metadata request failed:', error);
339
- return { ok: false, error: message };
340
- } finally {
341
- clearTimeout(timeoutId);
342
- }
343
-
344
- if (!metadataResponse.ok) {
345
- const rawBody = await metadataResponse.text().catch(() => '');
346
- const safeMessage = rawBody.replace(/\s+/g, ' ').trim().slice(0, 300);
347
- console.error('YouTube metadata lookup failed:', {
348
- status: metadataResponse.status,
349
- body: safeMessage,
350
- });
351
- return {
352
- ok: false,
353
- error: `YouTube metadata lookup failed (status ${metadataResponse.status}).`,
354
- };
355
- }
356
-
357
- let payload: { title?: unknown };
358
- try {
359
- payload = (await metadataResponse.json()) as { title?: unknown };
360
- } catch (error) {
361
- console.error('YouTube metadata service returned invalid JSON:', error);
362
- return { ok: false, error: 'YouTube metadata lookup failed.' };
363
- }
364
-
365
- const title =
366
- typeof payload.title === 'string' && payload.title.trim()
367
- ? payload.title.trim()
368
- : null;
369
-
370
- return {
371
- ok: true,
372
- title,
373
- fileName: fileNameArg || null,
374
- storagePath: null,
375
- url: sourceUrl,
376
- metadataOnly: true,
377
- supportedCapabilities: ['youtube_title_metadata'],
378
- unsupportedCapabilities: ['youtube_transcription', 'youtube_summary'],
379
- message: title
380
- ? `Only YouTube metadata is supported. Title: ${title}. YouTube transcripts and summaries are not supported.`
381
- : 'Only YouTube metadata is supported. YouTube transcripts and summaries are not supported.',
382
- };
383
- }
384
-
385
310
  if (!sourceUrl && targetPath) {
386
311
  if (isUnsafeStoragePath(targetPath)) {
387
312
  return { ok: false, error: 'Invalid storagePath for current workspace.' };