-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.ts
More file actions
524 lines (467 loc) · 15.7 KB
/
Copy pathmodels.ts
File metadata and controls
524 lines (467 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// Zod schemas define both runtime API validation and TypeScript types.
import { z } from "zod";
/**
* Token response from /token endpoint.
*
* Fields:
* - access_token: JWT access token (required)
* - refresh_token: JWT refresh token (nullable)
* - token_type: Token type (default "Bearer")
* - expires_in: Access token TTL in seconds (nullable)
* - refresh_expires_in: Refresh token TTL in seconds (nullable)
*
* Pattern: z.object() (lenient) — server may add fields (e.g. "plan").
*/
export const TokenResponseSchema = z.object({
access_token: z.string(),
refresh_token: z.string().nullable(),
token_type: z.string().default("Bearer"),
expires_in: z.number().nullable(),
refresh_expires_in: z.number().nullable().optional(),
plan: z.string().optional(),
});
/**
* Health check response from /health endpoint.
*
* Fields:
* - status: Overall health status string (e.g., "healthy" | "unhealthy")
* - database: Database connection status
* - redis: Redis connection/fallback status
* - services: External services status record
* - version: API version string
* - timestamp: Response timestamp ISO 8601
*
* Matches app/schemas/health.py in prompsit-api.
*/
export const ServiceHealthInfoSchema = z.object({
status: z.string(),
version: z.string().nullable().optional(),
missing_env: z.array(z.string()).nullable().optional(),
});
export const HealthResponseSchema = z.object({
status: z.string(),
database: z.string(),
redis: z.string(),
services: z.record(z.string(), ServiceHealthInfoSchema),
version: z.string(),
timestamp: z.string(),
});
// --- Translation schemas ---
/**
* Single translation item from API response.
*
* Fields:
* - translated_text: The translated text (required)
* - latency_ms: Translation latency in milliseconds (nullable)
* - quality_score: QE score 0-1 when enable_qe=true (nullable)
* - tag_alignment_method: Tag alignment method e.g. "neural" (nullable)
*
* Pattern: z.object() rejects unknown keys (strict schema contract).
*/
export const TranslationItemSchema = z.object({
translated_text: z.string(),
latency_ms: z.number().nullable(),
quality_score: z.number().nullable(),
tag_alignment_method: z.string().nullable(),
});
/**
* Translation response from POST /v1/translation.
*
* Fields:
* - translations: Array of TranslationItem results
* - source_lang: Confirmed source language code
* - target_lang: Confirmed target language code
* - engine: Engine used for translation (nullable)
* - total_latency_ms: Total request latency in milliseconds (nullable)
*
* Pattern: z.object() rejects unknown keys (strict schema contract).
*/
export const TranslationResponseSchema = z.object({
translations: z.array(TranslationItemSchema),
source_lang: z.string(),
target_lang: z.string(),
engine: z.string().nullable(),
total_latency_ms: z.number().nullable(),
});
// --- Evaluation schemas ---
/**
* A source/hypothesis/reference triplet for quality evaluation.
*
* Fields:
* - source: Original source text (required)
* - hypothesis: Machine-translated text (required)
* - reference: Human reference translation (required)
*
* Pattern: z.object() rejects unknown keys (strict schema contract).
*/
export const SegmentSchema = z.object({
source: z.string(),
hypothesis: z.string(),
reference: z.string(),
});
/**
* Evaluation response from POST /v1/quality/score.
*
* Fields:
* - corpus_scores: Aggregated scores per metric e.g. {"bleu": 0.42} (nullable)
* - segment_scores: Per-segment scores per metric e.g. {"bleu": [0.4, 0.5]} (nullable)
* - segment_count: Number of evaluated segments (default 0)
*
* Pattern: z.object() rejects unknown keys (strict schema contract).
*/
export const EvaluationResponseSchema = z.object({
corpus_scores: z.record(z.string(), z.number()).nullable(),
segment_scores: z.record(z.string(), z.array(z.number())).nullable(),
segment_count: z.number().default(0),
});
// --- Engine and format schemas ---
/** Per-engine metadata (APT package info). */
export const EngineDetailSchema = z.object({
package: z.string().nullish(),
package_version: z.string().nullish(),
});
/**
* Language pair detail from GET /v1/translation/languages.
*
* Fields:
* - source/target: BCP 47 language codes
* - source_name/target_name: Human-readable names
* - engines: Dict keyed by engine name → EngineDetail metadata
*/
export const LanguagePairDetailSchema = z.object({
source: z.string(),
source_name: z.string(),
target: z.string(),
target_name: z.string(),
engines: z.record(z.string(), EngineDetailSchema),
});
/** Unified format info for all discovery endpoints. */
export const FormatInfoSchema = z.object({
id: z.string(),
name: z.string(),
description: z.string(),
extensions: z.array(z.string()),
output_formats: z.array(z.string()),
});
/** Unified response wrapper for all format discovery endpoints. */
export const FormatsResponseSchema = z.object({
formats: z.array(FormatInfoSchema),
total: z.number(),
});
// --- Job schemas ---
/**
* Job status response from GET /v1/jobs/{job_id}.
*
* Fields:
* - job_id: Unique job identifier (required)
* - status: Job lifecycle status e.g. "pending", "completed" (required)
* - progress_percentage: Completion percentage 0-100 (default 0)
* - current_step: Current processing step e.g. "deformat", "translate" (nullable)
* - error_message: Error description when status=failed (nullable)
* - output_format: Output format e.g. "docx" for PDF input (nullable)
* - warnings: Array of warning messages (nullable)
* - chars_translated: Number of characters translated (nullable)
* - translation_requests_count: Number of translation API calls made (nullable)
* - created_at: Job creation timestamp ISO 8601 (nullable)
* - started_at: Job start timestamp ISO 8601 (nullable)
* - completed_at: Job completion timestamp ISO 8601 (nullable)
*
* Pattern: z.object() rejects unknown keys (strict schema contract).
*/
export const TMImportJobResultSchema = z.object({
tm_id: z.string(),
segment_count: z.number(),
source_lang: z.string(),
target_lang: z.string(),
});
export const JobStatusResponseSchema = z.object({
job_id: z.string(),
job_type: z.string(),
status: z.string(),
progress_percentage: z.number().default(0),
current_step: z.string().nullable(),
error_message: z.string().nullable(),
output_format: z.string().nullable(),
warnings: z.array(z.string()).nullable(),
chars_translated: z.number().nullable(),
translation_requests_count: z.number().nullable(),
created_at: z.string().nullable(),
started_at: z.string().nullable(),
completed_at: z.string().nullable(),
result_url: z.string().nullable().default(null),
error_code: z.string().nullable().default(null),
tm_import_result: TMImportJobResultSchema.nullable().default(null),
});
// --- Async Job Creation schema ---
/**
* Job creation response shared by document translation, data processing, and TMX import.
*
* Fields:
* - job_id: Unique job identifier (required)
* - status: Initial job status (default "pending")
* - job_type: Type of job e.g. "translation" (default "translation")
*
* Pattern: z.object() rejects unknown keys (strict schema contract).
*/
export const JobCreateResponseSchema = z.object({
job_id: z.string(),
status: z.string().default("pending"),
job_type: z.string().default("translation"),
status_url: z.string(),
result_url: z.string().nullable(),
});
/** Single language entry from GET /v1/data/score/languages. */
export const ScoreLanguageSchema = z.object({
id: z.string(),
name: z.string(),
});
/** Response from GET /v1/data/score/languages. */
export const DataScoreLanguagesResponseSchema = z.object({
languages: z.array(ScoreLanguageSchema),
total: z.number(),
default: z.string(),
});
export type DataScoreLanguagesResponse = z.infer<typeof DataScoreLanguagesResponseSchema>;
// --- User Usage schemas ---
/** Tier configuration from GET /v1/user/usage. */
export const TierInfoSchema = z.object({
name: z.string(),
chars_daily_limit: z.number(),
corpus_bytes_daily_limit: z.number(),
rpm_limit: z.number(),
segment_limit: z.number().nullable(),
});
/** Daily character usage (translation + QE pool) from GET /v1/user/usage. */
export const DailyUsageSchema = z.object({
chars_used: z.number(),
chars_limit: z.number(),
percentage: z.number(),
reset_at: z.string(),
});
/** Daily corpus byte usage (annotation pool) from GET /v1/user/usage. */
export const CorpusUsageSchema = z.object({
bytes_used: z.number(),
bytes_limit: z.number(),
percentage: z.number(),
reset_at: z.string(),
});
/** Subscription info from GET /v1/user/usage. */
export const SubscriptionInfoSchema = z.object({
active: z.boolean(),
start_date: z.string(),
end_date: z.string().nullable(),
});
/**
* User usage response from GET /v1/user/usage.
*
* Two usage pools:
* - daily_usage: character usage (translation + QE)
* - corpus_usage: byte usage (annotation)
*
* Matches app/schemas/user.py in prompsit-api.
*/
export const UserUsageResponseSchema = z.object({
tier: TierInfoSchema,
daily_usage: DailyUsageSchema,
corpus_usage: CorpusUsageSchema,
subscription: SubscriptionInfoSchema,
});
// --- Input DTOs for resource methods (camelCase, separate from wire-format Zod schemas) ---
/** Input for TranslationResource.translate() */
export interface TranslateParams {
texts: string[];
sourceLang: string;
targetLang: string;
enableQe?: boolean;
}
/** Input for TranslationResource.uploadDocument() */
export interface UploadDocumentParams {
filePath: string;
sourceLang: string;
targetLang: string;
outputFormat?: string;
}
/** Input for EvaluationResource.evaluate() */
export interface EvaluateParams {
segments: Segment[];
metrics: string[];
aggregation?: string;
}
/** Tag-quality segment (reference-free): source + hypothesis only. */
export interface TagSegment {
source: string;
hypothesis: string;
}
/** Input for EvaluationResource.scoreTags() */
export interface ScoreTagsParams {
segments: TagSegment[];
subScores?: string[];
aggregation?: string;
}
/** Input for EvaluationResource.evaluateFile() */
export interface EvaluateFileParams {
filePath: string;
metrics?: string[];
aggregation?: string;
outputFormat?: string;
}
/** Result from EvaluationResource.evaluateFile() — binary scored file + metadata */
export interface EvaluateFileResult {
data: Buffer;
filename: string;
corpusScores: Record<string, number>;
}
/** Input for DataResource.score() */
export interface ScoreParams {
sourceFile: string;
targetFile?: string;
outputFormat?: string;
sourceLang?: string;
}
/** Input for DataResource.annotate() */
export interface AnnotateParams {
filePath: string;
lang: string;
pipeline?: string[];
minLen?: number;
minAvgWords?: number;
lidModel: string;
}
// --- Device Flow schemas (RFC 8628) ---
/**
* Device authorization response from POST /v1/auth/device.
*
* Fields:
* - device_code: Opaque 32-byte base64 token for polling
* - user_code: Human-readable XXXX-XXXX format
* - verification_uri: Short URL (RFC 8628 §3.3)
* - verification_uri_complete: URL with embedded user_code for QR codes (§3.3.1)
* - expires_in: Device code TTL in seconds (default 600s)
* - interval: Minimum polling interval in seconds (default 5s)
*/
export const DeviceAuthorizationResponseSchema = z.object({
device_code: z.string(),
user_code: z.string(),
verification_uri: z.string(),
verification_uri_complete: z.string().optional(),
expires_in: z.number().default(600),
interval: z.number().default(5),
});
/**
* Device token success response from POST /v1/auth/device/token.
*
* `prompsit_secret` is present only on FIRST Google registration; on recurring
* logins the API omits it (returns null) and the CLI must keep its previously
* stored value. See ADR-037.
*/
export const DeviceTokenResponseSchema = z.object({
access_token: z.string(),
refresh_token: z.string(),
token_type: z.string().default("Bearer"),
expires_in: z.number(),
plan: z.string(),
email: z.string(),
account_id: z.string(),
prompsit_secret: z.string().nullish(),
});
/**
* Response from POST /v1/auth/secret (self-service rotate or set custom).
*
* Returns the new plaintext secret PLUS a fresh JWT pair so the calling CLI
* session can resume immediately on the new credentials.
*/
export const ChangeSecretResponseSchema = z.object({
prompsit_secret: z.string(),
access_token: z.string(),
refresh_token: z.string(),
expires_in: z.number(),
token_type: z.string().default("Bearer"),
});
/**
* Device token error response from POST /v1/auth/device/token (HTTP 400).
* RFC 8628 §3.5 error codes for polling.
*/
export const DeviceTokenErrorSchema = z.object({
error: z.enum(["authorization_pending", "slow_down", "expired_token", "access_denied"]),
error_description: z.string().optional(),
});
/**
* Inferred TypeScript types from Zod schemas.
* Single source of truth: types automatically match schema definitions.
*/
export type TokenResponse = z.infer<typeof TokenResponseSchema>;
export type HealthResponse = z.infer<typeof HealthResponseSchema>;
export type TranslationResponse = z.infer<typeof TranslationResponseSchema>;
export type Segment = z.infer<typeof SegmentSchema>;
export type EvaluationResponse = z.infer<typeof EvaluationResponseSchema>;
export type LanguagePairDetail = z.infer<typeof LanguagePairDetailSchema>;
export type FormatInfo = z.infer<typeof FormatInfoSchema>;
export type FormatsResponse = z.infer<typeof FormatsResponseSchema>;
export type JobStatusResponse = z.infer<typeof JobStatusResponseSchema>;
export type JobCreateResponse = z.infer<typeof JobCreateResponseSchema>;
export type UserUsageResponse = z.infer<typeof UserUsageResponseSchema>;
export type DeviceAuthorizationResponse = z.infer<typeof DeviceAuthorizationResponseSchema>;
export type DeviceTokenResponse = z.infer<typeof DeviceTokenResponseSchema>;
export type ChangeSecretResponse = z.infer<typeof ChangeSecretResponseSchema>;
// ---------------------------------------------------------------------------
// Translation Memory (TM) — API-535
// ---------------------------------------------------------------------------
export const TMResponseSchema = z.object({
id: z.string(),
profile_id: z.string(),
source_lang: z.string(),
target_lang: z.string(),
segment_count: z.number(),
created_at: z.string(),
});
export const TMListResponseSchema = z.object({
items: z.array(TMResponseSchema),
total: z.number(),
});
export const TMSegmentResponseSchema = z.object({
id: z.string(),
source_text: z.string(),
target_text: z.string(),
source_hash: z.string(),
created_at: z.string(),
});
export const TMSegmentListResponseSchema = z.object({
items: z.array(TMSegmentResponseSchema),
total: z.number(),
page: z.number(),
page_size: z.number(),
});
export const TMSearchHitResponseSchema = z.object({
source_text: z.string(),
target_text: z.string(),
similarity: z.number(),
match_type: z.string(),
});
export const TMSearchResponseSchema = z.object({
hits: z.array(TMSearchHitResponseSchema),
total_count: z.number(),
});
export type TMListResponse = z.infer<typeof TMListResponseSchema>;
export type TMSegmentListResponse = z.infer<typeof TMSegmentListResponseSchema>;
export type TMImportJobResult = z.infer<typeof TMImportJobResultSchema>;
export type TMSearchResponse = z.infer<typeof TMSearchResponseSchema>;
// TM param interfaces (camelCase at CLI boundary, mapped to snake_case in resource)
export interface TMListParams {
profileId?: string;
sourceLang?: string;
targetLang?: string;
}
export interface TMShowSegmentsParams {
sourceLang: string;
targetLang: string;
profileId?: string;
page?: number;
pageSize?: number;
}
export interface TMSearchParams {
query: string;
sourceLang: string;
targetLang: string;
limit?: number;
profileId?: string;
}