dsh-connect-trae 1.0.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/lib/index.d.ts ADDED
@@ -0,0 +1,975 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
3
+ import { Context } from "@deepseek-ai/cordis";
4
+ import { AttachmentStore } from "@deepseek-ai/dsh-attachment";
5
+ //#region src/reasoning.d.ts
6
+ declare const TRAE_REASONING_EFFORTS: readonly ["minimal", "low", "medium", "high", "xhigh"];
7
+ type TraeReasoningEffort = typeof TRAE_REASONING_EFFORTS[number];
8
+ interface TraeReasoningCapability {
9
+ supported: readonly TraeReasoningEffort[];
10
+ defaultEffort?: TraeReasoningEffort;
11
+ }
12
+ declare function parseReasoningCapability(value: unknown): TraeReasoningCapability | undefined;
13
+ /** Add effort only when the selected model advertises that exact value. */
14
+ declare function applyReasoningEffort<T extends Record<string, unknown>>(body: T, effort: TraeReasoningEffort | undefined, capability: TraeReasoningCapability | undefined): T & {
15
+ reasoning_effort?: TraeReasoningEffort;
16
+ };
17
+ //#endregion
18
+ //#region src/model-metadata.d.ts
19
+ interface TraeDiscoveredReasoning {
20
+ supported: TraeReasoningEffort[];
21
+ defaultEffort?: TraeReasoningEffort;
22
+ }
23
+ interface TraeDiscoveredModel {
24
+ id: string;
25
+ name: string;
26
+ multimodal: boolean;
27
+ contextWindow?: number;
28
+ maxContextWindow?: number;
29
+ creditMultiplier?: number;
30
+ reasoningSupported: boolean;
31
+ reasoning?: TraeDiscoveredReasoning;
32
+ }
33
+ /** Parse only capabilities explicitly advertised by Trae's remote model API. */
34
+ declare function parseTraeRemoteModel(value: unknown): TraeDiscoveredModel | undefined;
35
+ //#endregion
36
+ //#region src/catalog.d.ts
37
+ interface TraeModelInfo {
38
+ id: string;
39
+ name: string;
40
+ contextWindow?: number;
41
+ maxTokens?: number;
42
+ input?: ('text' | 'image')[];
43
+ creditMultiplier?: number;
44
+ reasoningSupported?: boolean;
45
+ reasoning?: TraeDiscoveredReasoning;
46
+ reasoningEfforts?: Partial<Record<TraeReasoningEffort, string | null>>;
47
+ baseModelId?: string;
48
+ maxContext?: boolean;
49
+ maxContextWindow?: number;
50
+ }
51
+ /** Bootstrap catalog: identity only where current Trae metadata has not been fetched yet. */
52
+ declare const FALLBACK_TRAE_MODELS: readonly TraeModelInfo[];
53
+ /** Convert verified Trae API metadata into normal models and optional 1M variants. */
54
+ declare function discoveredCatalog(models: readonly TraeDiscoveredModel[], enabled1m?: ReadonlySet<string>): TraeModelInfo[];
55
+ declare class TraeCatalog {
56
+ private models;
57
+ current(): readonly TraeModelInfo[];
58
+ set(models: readonly TraeModelInfo[]): void;
59
+ }
60
+ //#endregion
61
+ //#region src/upstream.d.ts
62
+ type TraeUpstreamErrorKind = 'authentication' | 'hard_credit' | 'soft_rate' | 'not_found' | 'server' | 'client' | 'unconfigured';
63
+ type TraeChatResult = {
64
+ ok: true;
65
+ response: Response;
66
+ } | {
67
+ ok: false;
68
+ status: number;
69
+ kind: TraeUpstreamErrorKind;
70
+ message: string;
71
+ };
72
+ interface TraeUpstreamClient {
73
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
74
+ }
75
+ /**
76
+ * Safe first-stage upstream. Real Trae traffic stays disabled until one
77
+ * edition-specific endpoint and wire codec are verified with fixtures.
78
+ */
79
+ declare class UnconfiguredTraeUpstreamClient implements TraeUpstreamClient {
80
+ chatStream(_bodyJson: string, _signal?: AbortSignal): Promise<TraeChatResult>;
81
+ }
82
+ //#endregion
83
+ //#region src/shim.d.ts
84
+ interface ShimLogger {
85
+ warn(...args: unknown[]): void;
86
+ error(...args: unknown[]): void;
87
+ }
88
+ interface TraeShim {
89
+ ready: Promise<void>;
90
+ baseUrl(): string;
91
+ token(): string;
92
+ close(): Promise<void>;
93
+ }
94
+ interface TraeShimOptions {
95
+ catalog: TraeCatalog;
96
+ client: TraeUpstreamClient;
97
+ logger?: ShimLogger;
98
+ }
99
+ declare function createTraeShim(options: TraeShimOptions): TraeShim;
100
+ //#endregion
101
+ //#region src/adapter.d.ts
102
+ declare const TRAE_PROVIDER = "trae";
103
+ declare const TRAE_STREAM_IDLE_TIMEOUT_MS = 300000;
104
+ interface TraeAdapterOptions {
105
+ shim: TraeShim;
106
+ catalog: TraeCatalog;
107
+ resolveAttachments?: () => AttachmentStore | undefined;
108
+ }
109
+ interface TraeAdapter {
110
+ adapter: PiAiAdapter;
111
+ invalidate(): void;
112
+ }
113
+ declare function createTraeAdapter(options: TraeAdapterOptions): TraeAdapter;
114
+ //#endregion
115
+ //#region src/paths.d.ts
116
+ type TraeEdition = 'cn' | 'sg' | 'solo' | 'solo-sg';
117
+ interface TraeStorageCandidate {
118
+ edition: TraeEdition;
119
+ path: string;
120
+ }
121
+ declare function traeStorageCandidates(platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv): TraeStorageCandidate[];
122
+ //#endregion
123
+ //#region src/auth.d.ts
124
+ interface TraeCredential {
125
+ accessToken: string;
126
+ refreshToken?: string;
127
+ userId: string;
128
+ accountName?: string;
129
+ host: string;
130
+ expiresAtMs: number;
131
+ refreshExpiresAtMs?: number;
132
+ edition: TraeEdition;
133
+ source: 'desktop' | 'dsh';
134
+ }
135
+ interface TraeRefreshOutcome {
136
+ accessToken: string;
137
+ refreshToken?: string;
138
+ expiresAtMs: number;
139
+ refreshExpiresAtMs?: number;
140
+ host?: string;
141
+ }
142
+ interface TraeCredentialStoreOptions {
143
+ storagePath?: string;
144
+ edition?: TraeEdition | 'auto';
145
+ accountId?: string;
146
+ ownPath?: string;
147
+ refresh: (credential: TraeCredential) => Promise<TraeRefreshOutcome>;
148
+ refreshMarginMs?: number;
149
+ }
150
+ interface TraeAccountChoice {
151
+ id: string;
152
+ accountName: string;
153
+ edition: TraeEdition;
154
+ source: 'desktop' | 'dsh';
155
+ tokenExpiresAtMs: number;
156
+ selected: boolean;
157
+ }
158
+ declare function traeOwnAuthPath(): string;
159
+ declare function normalizeTraeCredential(raw: unknown, edition: TraeEdition, source: TraeCredential['source']): TraeCredential | undefined;
160
+ declare class TraeCredentialStore {
161
+ private storagePathOverride;
162
+ private edition;
163
+ private accountId;
164
+ private preferIds;
165
+ private readonly ownPath;
166
+ private readonly refresh;
167
+ private readonly refreshMarginMs;
168
+ private inflight;
169
+ constructor(options: TraeCredentialStoreOptions);
170
+ setSource(storagePath: string | undefined, edition?: TraeEdition | 'auto', accountId?: string): void;
171
+ selectAccount(accountId: string | undefined): void;
172
+ /**
173
+ * Preferred account ordering used when no account is explicitly selected.
174
+ * The connector can only bill the `llm_utils_chat` channel against general
175
+ * credits, so accounts with zero general credits should not become the
176
+ * default or they fail with 4008 / empty responses.
177
+ */
178
+ setPreferAccountIds(ids: readonly string[]): void;
179
+ candidates(): TraeStorageCandidate[];
180
+ /** First credential matching the preferred ordering, else the first live one. */
181
+ private preferred;
182
+ accounts(): Promise<TraeAccountChoice[]>;
183
+ current(): Promise<TraeCredential | undefined>;
184
+ resolve(): Promise<TraeCredential>;
185
+ status(): Promise<{
186
+ state: 'signed-in' | 'signed-out';
187
+ edition?: TraeEdition;
188
+ expiresAtMs?: number;
189
+ source?: 'desktop' | 'dsh';
190
+ }>;
191
+ desktopFilePresent(): Promise<boolean>;
192
+ logout(): Promise<void>;
193
+ private readAll;
194
+ private readDesktopAll;
195
+ private readOwn;
196
+ private refreshNow;
197
+ }
198
+ //#endregion
199
+ //#region src/decrypt.d.ts
200
+ declare function decryptTraeStorageValue(encoded: string): string;
201
+ declare function parseTraeAuthValue(value: string): unknown;
202
+ declare function parseTraeStorageDocument(text: string): unknown;
203
+ //#endregion
204
+ //#region src/identity.d.ts
205
+ interface TraeIdentity {
206
+ edition: TraeEdition;
207
+ machineId: string;
208
+ deviceId: string;
209
+ appVersion?: string;
210
+ buildVersion?: string;
211
+ deviceBrand?: string;
212
+ deviceCpu?: string;
213
+ osVersion?: string;
214
+ platform: NodeJS.Platform;
215
+ }
216
+ /** Read stable identity from Trae-owned files without generating impersonated IDs. */
217
+ declare function readTraeIdentity(candidate: TraeStorageCandidate): Promise<TraeIdentity>;
218
+ /** Headers derived from actual persisted identity, never a new random identity per request. */
219
+ declare function identityHeaders(identity: TraeIdentity): Record<string, string>;
220
+ //#endregion
221
+ //#region src/model-config.d.ts
222
+ interface TraeObservedModelConfig {
223
+ configName: string;
224
+ modelName: string;
225
+ promptSet?: string;
226
+ abVersion?: string;
227
+ rawChatFunction?: string;
228
+ }
229
+ /**
230
+ * Parse a secret-free CustomModel debug line emitted by Trae. Optional values
231
+ * remain absent when Trae prints None; we must not invent defaults for them.
232
+ */
233
+ declare function parseObservedModelConfig(line: string): TraeObservedModelConfig | undefined;
234
+ //#endregion
235
+ //#region src/model-cache.d.ts
236
+ interface TraeCachedModelConfig {
237
+ name: string;
238
+ customConfig?: Record<string, unknown>;
239
+ promptMaxTokens?: number;
240
+ maxTokens?: number;
241
+ maxTurn?: number;
242
+ multimodal?: boolean;
243
+ modelType?: string;
244
+ }
245
+ /** Parse a safe subset of one cached model entry; credentials and endpoints are intentionally omitted. */
246
+ declare function parseTraeCachedModel(value: unknown): TraeCachedModelConfig | undefined;
247
+ /** Read Trae's own current user's model map via sqlite3 without exposing secrets. */
248
+ declare function readTraeCachedModel(functionName: string, modelName: string, userId: string): Promise<TraeCachedModelConfig | undefined>;
249
+ //#endregion
250
+ //#region src/model-extra-config.d.ts
251
+ interface TraeRawChatBehaviorConfig {
252
+ passBackReasoning?: boolean;
253
+ nativeFunctionCall?: boolean;
254
+ useV2Process?: boolean;
255
+ maxModeEnabled?: boolean;
256
+ maxToolcallChars?: number;
257
+ streamThrottleEnabled?: boolean;
258
+ }
259
+ /** Parse only Raw Chat behavior switches observed in Trae's model_extra_config. */
260
+ declare function parseTraeRawChatBehaviorConfig(value: unknown): TraeRawChatBehaviorConfig;
261
+ /** Extract the JSON object from one native model_extra_config parse log line. */
262
+ declare function parseTraeModelExtraConfigLogLine(line: string): TraeRawChatBehaviorConfig | undefined;
263
+ //#endregion
264
+ //#region src/model-detail.d.ts
265
+ declare const TRAE_MODEL_DETAIL_PATH = "/api/ide/v1/batch_get_detail_param";
266
+ declare const TRAE_MODEL_DETAIL_FUNCTIONS: readonly ["ui_builder_v2", "solo_coder", "chat_v3", "solo_builder", "builder_v3", "builder", "chat", "inline_chat", "git_ai", "custom_agent_generation", "utils", "code_reviewer", "code_review_summary", "solo_agent", "solo_agent_remote", "solo_work_remote", "solo_agent_lite", "solo_work_lite", "solo_design_lite", "solo_design_remote", "multimodal", "system_diagnosis"];
267
+ interface TraeModelDetailRequest {
268
+ functions: string[];
269
+ agent_type: '' | 'solo_agent';
270
+ current_config_info: {
271
+ config_name: string;
272
+ is_custom_model: boolean;
273
+ };
274
+ mode_type: 0;
275
+ access_type: 0;
276
+ ab_force_vids: '';
277
+ ab_autotest_advanced_mode: 0;
278
+ }
279
+ /** Build the exact request shape observed in successful current Trae CN logs. */
280
+ declare function buildTraeModelDetailRequest(configName?: string, custom?: boolean): TraeModelDetailRequest;
281
+ //#endregion
282
+ //#region src/protocol.d.ts
283
+ declare const TRAE_CN_AGENT_TASK_PATH = "/api/agent/v3/create_agent_task";
284
+ declare const TRAE_CN_TITLE_PATH = "/api/agent/v3/llm_utils_chat";
285
+ interface OpenAITextMessage {
286
+ role: 'assistant' | 'system' | 'user';
287
+ content: string;
288
+ }
289
+ interface TraeAgentTaskBody {
290
+ messages: {
291
+ role: OpenAITextMessage['role'];
292
+ content: {
293
+ type: 'text';
294
+ text: string;
295
+ }[];
296
+ }[];
297
+ model: string;
298
+ function: string;
299
+ stream: true;
300
+ request_id: string;
301
+ session_id: string;
302
+ max_tokens?: number;
303
+ }
304
+ /**
305
+ * Evidence-bounded body draft. It is intentionally pure and offline; the
306
+ * network client remains disabled until a controlled request validates it.
307
+ */
308
+ declare function buildTraeAgentTaskBody(messages: readonly OpenAITextMessage[], model: string, options?: {
309
+ maxTokens?: number;
310
+ requestId?: string;
311
+ sessionId?: string;
312
+ }): TraeAgentTaskBody;
313
+ type TraeHeaderProfile = 'agent-task' | 'model-detail' | 'raw-chat' | 'native-curl';
314
+ /**
315
+ * Numeric version code sent when the persisted build version is not a plain
316
+ * integer. The upstream binds `x-app-version-code` / `x-ide-version-code` as a
317
+ * number: Trae stores `iCubeLastVersion` as a dotted build string (observed
318
+ * `2.3.76922` on TRAE SOLO CN 0.1.56), which the server rejects with
319
+ * `4001 ... expr_path=app_version_code, cause=parameter type does not match
320
+ * binding data`. Verified 2026-08-29: with a numeric code the same request
321
+ * returns HTTP 200 + `text/event-stream` on
322
+ * `/api/agent/v3/llm_utils_chat` (`solo_work_lite`).
323
+ *
324
+ * Only the *format* of this field is normalised. Machine, device and app
325
+ * version stay exactly as persisted — nothing here impersonates a device.
326
+ */
327
+ declare const TRAE_VERSION_CODE_FALLBACK = "20260716";
328
+ /** Keep a purely numeric build version; fall back when it cannot bind. */
329
+ declare function normalizeTraeVersionCode(buildVersion: string | undefined): string;
330
+ declare function buildTraeCnHeaders(credential: TraeCredential, identity: TraeIdentity, options?: {
331
+ appId?: string;
332
+ requestId?: string;
333
+ profile?: TraeHeaderProfile;
334
+ }): Record<string, string>;
335
+ declare function traeEndpoint(baseUrl: string, path: string): string;
336
+ //#endregion
337
+ //#region src/raw-chat.d.ts
338
+ declare const TRAE_RAW_CHAT_V2_PATH = "/api/ide/v2/llm_raw_chat";
339
+ declare const TRAE_RAW_CHAT_V1_PATH = "/api/ide/v1/llm_raw_chat";
340
+ type RawChatRole = 'assistant' | 'system' | 'tool' | 'user';
341
+ interface RawChatTextContent {
342
+ type: 'text';
343
+ text: string;
344
+ }
345
+ interface RawChatImageContent {
346
+ type: 'image_url';
347
+ image_url: {
348
+ url: string;
349
+ };
350
+ }
351
+ type RawChatContent = RawChatTextContent | RawChatImageContent;
352
+ interface RawChatToolCall {
353
+ id: string;
354
+ type: 'function';
355
+ function: {
356
+ name: string;
357
+ arguments: string;
358
+ };
359
+ }
360
+ interface RawChatMessage {
361
+ role: RawChatRole;
362
+ content: string | RawChatContent[];
363
+ tool_call_id?: string;
364
+ tool_calls?: RawChatToolCall[];
365
+ }
366
+ interface RawChatTool {
367
+ type: 'function';
368
+ function: {
369
+ name: string;
370
+ description?: string;
371
+ parameters: Record<string, unknown>;
372
+ };
373
+ }
374
+ interface TraeRawChatDraft {
375
+ model: string;
376
+ messages: RawChatMessage[];
377
+ stream: true;
378
+ tools?: RawChatTool[];
379
+ max_tokens?: number;
380
+ temperature?: number;
381
+ reasoning_effort?: string;
382
+ extra_info?: Record<string, unknown>;
383
+ }
384
+ /**
385
+ * Evidence-bounded OpenAI-like draft inferred from Trae's LLMRaw* DTO symbols.
386
+ * Pure/offline only: the upstream remains disabled until one controlled probe.
387
+ */
388
+ declare function buildTraeRawChatDraft(input: {
389
+ model: string;
390
+ messages: readonly RawChatMessage[];
391
+ tools?: readonly RawChatTool[];
392
+ maxTokens?: number;
393
+ temperature?: number;
394
+ reasoningEffort?: string;
395
+ extraInfo?: Record<string, unknown>;
396
+ }): TraeRawChatDraft;
397
+ type RawChatDelta = {
398
+ type: 'text';
399
+ text: string;
400
+ } | {
401
+ type: 'reasoning';
402
+ text: string;
403
+ } | {
404
+ type: 'tool-call';
405
+ index: number;
406
+ id?: string;
407
+ name?: string;
408
+ arguments?: string;
409
+ } | {
410
+ type: 'usage';
411
+ inputTokens?: number;
412
+ outputTokens?: number;
413
+ totalTokens?: number;
414
+ } | {
415
+ type: 'done';
416
+ finishReason: string;
417
+ } | {
418
+ type: 'unknown';
419
+ value: unknown;
420
+ };
421
+ /** Decode OpenAI-like raw-chat chunks while preserving unknown structures. */
422
+ declare function decodeRawChatChunk(value: unknown): RawChatDelta[];
423
+ //#endregion
424
+ //#region src/raw-envelope.d.ts
425
+ interface TraeFusionRawChatEnvelope {
426
+ arg: TraeRawChatDraft;
427
+ args_hash: string;
428
+ config_json: string;
429
+ }
430
+ /** Stable JSON hash candidate used by the native DTO's arg/args_hash fields. */
431
+ declare function hashTraeRawChatArg(arg: TraeRawChatDraft): string;
432
+ /**
433
+ * Evidence-bounded fusion envelope candidate. The native DTO exposes exactly
434
+ * arg/args_hash/config_json, but the hash algorithm and config_json contents
435
+ * remain candidates until a live response validates them.
436
+ */
437
+ declare function buildTraeFusionRawChatEnvelope(arg: TraeRawChatDraft, config: Record<string, unknown>): TraeFusionRawChatEnvelope;
438
+ //#endregion
439
+ //#region src/raw-runtime-config.d.ts
440
+ interface TraeRawChatRuntimeConfig {
441
+ configName: string;
442
+ modelName: string;
443
+ promptMaxTokens?: number;
444
+ maxTokens?: number;
445
+ maxTurn?: number;
446
+ multimodal?: boolean;
447
+ nativeFunctionCall?: boolean;
448
+ passBackReasoning?: boolean;
449
+ useV2Process?: boolean;
450
+ maxModeEnabled?: boolean;
451
+ maxToolcallChars?: number;
452
+ streamThrottleEnabled?: boolean;
453
+ customConfig?: Record<string, unknown>;
454
+ }
455
+ /** Merge safe current-cache facts with observed behavior flags; no network credentials enter this object. */
456
+ declare function traeRawChatExtraInfo(config: TraeRawChatRuntimeConfig): Record<string, unknown>;
457
+ declare function buildTraeRawChatRuntimeConfig(modelName: string, cached: TraeCachedModelConfig | undefined, behavior?: TraeRawChatBehaviorConfig): TraeRawChatRuntimeConfig;
458
+ //#endregion
459
+ //#region src/raw-resolver.d.ts
460
+ interface TraeRawResolverResult {
461
+ identity: TraeIdentity;
462
+ runtime: TraeRawChatRuntimeConfig;
463
+ }
464
+ /** Resolve current desktop identity and safe cached model config for capability probing. */
465
+ declare function resolveTraeRawRuntime(store: TraeCredentialStore, modelName: string): Promise<TraeRawResolverResult>;
466
+ //#endregion
467
+ //#region src/raw-fingerprint.d.ts
468
+ /** Stable non-secret fingerprint for capability-cache invalidation. */
469
+ declare function rawCapabilityFingerprint(input: {
470
+ endpoint: string;
471
+ edition: string;
472
+ identity: Pick<TraeIdentity, 'appVersion' | 'buildVersion'>;
473
+ runtime: TraeRawChatRuntimeConfig;
474
+ }): string;
475
+ //#endregion
476
+ //#region src/raw-capability.d.ts
477
+ type TraeRawChatCapability = {
478
+ available: true;
479
+ contentType: string | null;
480
+ } | {
481
+ available: false;
482
+ reason: 'authentication' | 'credit' | 'rate' | 'protocol' | 'transport' | 'server';
483
+ status: number;
484
+ };
485
+ /** One short non-tool request decides whether Raw Chat may become primary. */
486
+ declare function probeTraeRawChatCapability(client: TraeUpstreamClient, signal?: AbortSignal): Promise<TraeRawChatCapability>;
487
+ //#endregion
488
+ //#region src/raw-diagnostic.d.ts
489
+ type TraeRawDiagnosticState = 'disabled' | 'unchecked' | 'available' | 'protocol-gated' | 'authentication' | 'credit' | 'rate' | 'transport' | 'server';
490
+ interface TraeRawDiagnostic {
491
+ state: TraeRawDiagnosticState;
492
+ checkedAtMs?: number;
493
+ status?: number;
494
+ }
495
+ /** Project capability facts to a redacted, user-safe status. */
496
+ declare function rawCapabilityDiagnostic(enabled: boolean, capability?: TraeRawChatCapability, checkedAtMs?: number): TraeRawDiagnostic;
497
+ //#endregion
498
+ //#region src/raw-gateway.d.ts
499
+ interface TraeRawGatewayOptions {
500
+ raw: TraeUpstreamClient;
501
+ solo: TraeUpstreamClient;
502
+ endpoint: string;
503
+ edition: string;
504
+ identity: Pick<TraeIdentity, 'appVersion' | 'buildVersion'>;
505
+ runtime: TraeRawChatRuntimeConfig;
506
+ enabled?: boolean;
507
+ }
508
+ interface TraeRawGateway {
509
+ upstream: TraeUpstreamClient;
510
+ probe(signal?: AbortSignal): ReturnType<typeof probeTraeRawChatCapability>;
511
+ diagnostic(): TraeRawDiagnostic;
512
+ invalidate(): void;
513
+ }
514
+ /** Assemble the opt-in capability state and safe Raw→SOLO routing. */
515
+ declare function createTraeRawGateway(options: TraeRawGatewayOptions): TraeRawGateway;
516
+ //#endregion
517
+ //#region src/raw-upstream.d.ts
518
+ interface TraeRawChatConfig {
519
+ model: string;
520
+ configName: string;
521
+ promptSet?: string;
522
+ abVersion?: string;
523
+ passBackReasoning: boolean;
524
+ extraInfo?: Record<string, unknown>;
525
+ runtime?: TraeRawChatRuntimeConfig;
526
+ }
527
+ interface TraeRawChatClientOptions {
528
+ credential: () => Promise<TraeCredential>;
529
+ identity: () => Promise<TraeIdentity>;
530
+ config: TraeRawChatConfig;
531
+ baseUrl?: string;
532
+ fetchImpl?: typeof fetch;
533
+ }
534
+ type TraeRawChatFailureReason = 'empty' | 'json' | 'schema' | 'permission' | 'model' | 'generic-http' | 'other';
535
+ declare function classifyTraeRawChatFailure(message: string): TraeRawChatFailureReason;
536
+ /**
537
+ * Evidence-gated Raw Chat client. It is fully testable through injected fetch,
538
+ * but production callers must not construct it without verified config values.
539
+ */
540
+ declare class TraeRawChatUpstreamClient {
541
+ private readonly options;
542
+ private readonly fetchImpl;
543
+ constructor(options: TraeRawChatClientOptions);
544
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
545
+ }
546
+ //#endregion
547
+ //#region src/raw-capability-state.d.ts
548
+ interface TraeRawCapabilitySnapshot {
549
+ capability?: TraeRawChatCapability;
550
+ checkedAtMs?: number;
551
+ fingerprint?: string;
552
+ }
553
+ /** In-memory capability state; success/failure expires and config changes invalidate it. */
554
+ declare class TraeRawCapabilityState {
555
+ private readonly ttlMs;
556
+ private snapshot;
557
+ constructor(ttlMs?: number);
558
+ current(fingerprint: string, now?: number): TraeRawChatCapability | undefined;
559
+ record(fingerprint: string, capability: TraeRawChatCapability, now?: number): void;
560
+ inspect(): Readonly<TraeRawCapabilitySnapshot>;
561
+ invalidate(): void;
562
+ }
563
+ //#endregion
564
+ //#region src/raw-capability-controller.d.ts
565
+ interface TraeRawCapabilityControllerOptions {
566
+ client: TraeUpstreamClient;
567
+ state?: TraeRawCapabilityState;
568
+ enabled?: boolean;
569
+ }
570
+ /** Explicitly-triggered, single-flight Raw Chat capability checks. */
571
+ declare class TraeRawCapabilityController {
572
+ private readonly options;
573
+ private readonly state;
574
+ private enabled;
575
+ private inflight;
576
+ constructor(options: TraeRawCapabilityControllerOptions);
577
+ current(fingerprint: string): TraeRawChatCapability | undefined;
578
+ setEnabled(enabled: boolean): void;
579
+ inspect(): Readonly<TraeRawCapabilitySnapshot>;
580
+ isEnabled(): boolean;
581
+ invalidate(): void;
582
+ probe(fingerprint: string, signal?: AbortSignal): Promise<TraeRawChatCapability>;
583
+ }
584
+ //#endregion
585
+ //#region src/fallback-upstream.d.ts
586
+ interface TraeFallbackUpstreamOptions {
587
+ primary: TraeUpstreamClient;
588
+ fallback: TraeUpstreamClient;
589
+ onFallback?: (result: Extract<TraeChatResult, {
590
+ ok: false;
591
+ }>) => void;
592
+ }
593
+ /**
594
+ * Raw Chat first, SOLO Remote second. Fallback is intentionally narrow:
595
+ * only definitive pre-stream schema/route incompatibilities may retry the same
596
+ * user request. Authentication, credit, rate, cancellation, transport/server
597
+ * failures, and every successful Response are never replayed.
598
+ */
599
+ declare class TraeFallbackUpstreamClient implements TraeUpstreamClient {
600
+ private readonly options;
601
+ constructor(options: TraeFallbackUpstreamOptions);
602
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
603
+ private canFallback;
604
+ }
605
+ //#endregion
606
+ //#region src/gated-upstream.d.ts
607
+ interface TraeGatedUpstreamOptions {
608
+ raw: TraeUpstreamClient;
609
+ solo: TraeUpstreamClient;
610
+ capability(): TraeRawChatCapability | undefined;
611
+ onFallback?: (failure: Extract<TraeChatResult, {
612
+ ok: false;
613
+ }>) => void;
614
+ }
615
+ /** Select Raw Chat only after a successful capability probe; SOLO is the safe default. */
616
+ declare class TraeGatedUpstreamClient implements TraeUpstreamClient {
617
+ private readonly options;
618
+ constructor(options: TraeGatedUpstreamOptions);
619
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
620
+ }
621
+ //#endregion
622
+ //#region src/refresh.d.ts
623
+ /** Refresh only editions whose client contract is currently evidenced. */
624
+ declare function refreshTraeCredential(credential: TraeCredential, signal?: AbortSignal): Promise<TraeRefreshOutcome>;
625
+ //#endregion
626
+ //#region src/sse.d.ts
627
+ interface SseEvent {
628
+ event?: string;
629
+ data: string;
630
+ id?: string;
631
+ retry?: number;
632
+ }
633
+ /** Incremental SSE decoder supporting CRLF, chunk splits and multi-line data. */
634
+ declare class SseDecoder {
635
+ private buffer;
636
+ private event;
637
+ private id;
638
+ private retry;
639
+ private data;
640
+ push(chunk: string): SseEvent[];
641
+ finish(): SseEvent[];
642
+ private consumeLine;
643
+ private dispatch;
644
+ }
645
+ type TraeStreamEvent = {
646
+ type: 'queue';
647
+ position?: number;
648
+ } | {
649
+ type: 'progress';
650
+ notice: unknown;
651
+ } | {
652
+ type: 'delta';
653
+ text: string;
654
+ reasoning?: string;
655
+ toolCalls?: unknown;
656
+ } | {
657
+ type: 'usage';
658
+ inputTokens?: number;
659
+ outputTokens?: number;
660
+ totalTokens?: number;
661
+ reasoningTokens?: number;
662
+ } | {
663
+ type: 'done';
664
+ finishReason: string;
665
+ } | {
666
+ type: 'unknown';
667
+ event?: string;
668
+ data: unknown;
669
+ };
670
+ declare function decodeTraeEvent(event: SseEvent): TraeStreamEvent;
671
+ //#endregion
672
+ //#region src/solo.d.ts
673
+ declare const TRAE_SOLO_FUNCTION = "solo_work_lite";
674
+ declare const TRAE_SOLO_CHAT_PATH = "/api/agent/v3/llm_utils_chat";
675
+ declare const TRAE_SOLO_MODELS_PATH = "/api/ide/v1/get_detail_param";
676
+ declare function prepareSoloBody(source: string, defaultModel?: string): string;
677
+ interface TraeSoloModel {
678
+ id: string;
679
+ name: string;
680
+ contextWindow?: number;
681
+ maxTokens?: number;
682
+ reasoning?: TraeReasoningCapability;
683
+ }
684
+ interface TraeSoloClientOptions {
685
+ credential(): Promise<TraeCredential>;
686
+ identity(): Promise<TraeIdentity>;
687
+ baseUrl?: string;
688
+ fetchImpl?: typeof fetch;
689
+ }
690
+ declare class TraeSoloUpstreamClient {
691
+ private readonly options;
692
+ private readonly fetchImpl;
693
+ constructor(options: TraeSoloClientOptions);
694
+ fetchModels(signal?: AbortSignal): Promise<TraeSoloModel[]>;
695
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
696
+ }
697
+ //#endregion
698
+ //#region src/solo-bridge.d.ts
699
+ /** Convert Trae's named SSE events into OpenAI chat-completion SSE chunks. */
700
+ declare function bridgeTraeSoloStream(response: Response, model: string): Response;
701
+ /** Native SOLO client wrapper used by the loopback OpenAI adapter. */
702
+ declare class TraeSoloBridge implements TraeUpstreamClient {
703
+ private readonly upstream;
704
+ constructor(upstream: TraeUpstreamClient);
705
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
706
+ }
707
+ //#endregion
708
+ //#region src/solo-remote.d.ts
709
+ declare const TRAE_SOLO_REMOTE_BASE = "https://solo.trae.cn/api/remote/v1";
710
+ declare const TRAE_SOLO_REMOTE_MODELS: readonly {
711
+ name: string;
712
+ displayName: string;
713
+ multimodal: boolean;
714
+ }[];
715
+ interface TraeSoloRemoteOptions {
716
+ credential(): Promise<TraeCredential>;
717
+ fetchImpl?: typeof fetch;
718
+ baseUrl?: string;
719
+ pollIntervalMs?: number;
720
+ timeoutMs?: number;
721
+ }
722
+ interface TraeRemoteInputMessage {
723
+ role: string;
724
+ content: string;
725
+ }
726
+ declare class TraeSoloRemoteClient {
727
+ private readonly options;
728
+ private readonly fetchImpl;
729
+ private readonly baseUrl;
730
+ private readonly pollIntervalMs;
731
+ private readonly timeoutMs;
732
+ constructor(options: TraeSoloRemoteOptions);
733
+ private headers;
734
+ chat(messages: readonly TraeRemoteInputMessage[], model: string, signal?: AbortSignal): Promise<{
735
+ content: string;
736
+ sessionId: string;
737
+ }>;
738
+ fetchModels(signal?: AbortSignal): Promise<TraeDiscoveredModel[]>;
739
+ }
740
+ //#endregion
741
+ //#region src/solo-remote-bridge.d.ts
742
+ /**
743
+ * Bridges the SOLO remote polling-based API into the shim's stream interface.
744
+ * The remote API uses create-session + poll-messages rather than raw SSE,
745
+ * so this bridge converts the final result into a synthetic OpenAI SSE stream.
746
+ */
747
+ declare class TraeSoloRemoteBridge implements TraeUpstreamClient {
748
+ private readonly remote;
749
+ constructor(remote: TraeSoloRemoteClient);
750
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
751
+ }
752
+ //#endregion
753
+ //#region src/delegating-upstream.d.ts
754
+ /** Stable shim dependency whose delegate can be replaced after async setup. */
755
+ declare class TraeDelegatingUpstreamClient implements TraeUpstreamClient {
756
+ private delegate;
757
+ constructor(delegate: TraeUpstreamClient);
758
+ replace(delegate: TraeUpstreamClient): void;
759
+ chatStream(bodyJson: string, signal?: AbortSignal): Promise<TraeChatResult>;
760
+ }
761
+ //#endregion
762
+ //#region src/usage.d.ts
763
+ /**
764
+ * Read-only Trae usage/credits client.
765
+ *
766
+ * Sources the verified `api.trae.cn` pay/ug endpoints (see
767
+ * `docs/USAGE_API_RESEARCH.md`). All queries are read-only and do not consume
768
+ * Trae credits. The per-session consumption detail table is deliberately not
769
+ * included: the endpoint returns no rows for the current account, so we only
770
+ * expose what is actually retrievable.
771
+ */
772
+ declare const TRAE_PAY_BASE = "https://api.trae.cn";
773
+ interface TraeUsageOptions {
774
+ credential(): Promise<TraeCredential | undefined>;
775
+ fetchImpl?: typeof fetch;
776
+ baseUrl?: string;
777
+ timeoutMs?: number;
778
+ }
779
+ interface TraeUsageSummary {
780
+ totalAmount: number;
781
+ consumedAmount: number;
782
+ consumptionRatio: number;
783
+ }
784
+ interface TraeUsagePack {
785
+ displayDesc: string;
786
+ entitlementId: string;
787
+ endTimeMs: number;
788
+ currency: number;
789
+ /** 0 = non-Work/general endpoint, 1 = Work endpoint. */
790
+ availableEndpoint?: number;
791
+ creditsLimit?: number;
792
+ /** Credits consumed from this pack (`usage.credits_amount`). */
793
+ consumedCredits?: number;
794
+ }
795
+ interface TraeUsageSnapshot {
796
+ isCreditsBilling: boolean;
797
+ isDollarUsageBilling: boolean;
798
+ isPayFreshman: boolean;
799
+ inTrial: boolean;
800
+ trialEndTimeMs: number;
801
+ summary: TraeUsageSummary;
802
+ packs: TraeUsagePack[];
803
+ }
804
+ interface TraeCheckinStatus {
805
+ checkedIn: boolean;
806
+ credits: number;
807
+ enabled: boolean;
808
+ }
809
+ interface TraeActivityRule {
810
+ activityId: string;
811
+ enabled: boolean;
812
+ activityType: number;
813
+ startTimeMs: number;
814
+ endTimeMs: number;
815
+ workExtra?: Record<string, unknown>;
816
+ }
817
+ interface TraeUsageView {
818
+ snapshot: TraeUsageSnapshot;
819
+ checkin: TraeCheckinStatus;
820
+ activities: TraeActivityRule[];
821
+ }
822
+ /**
823
+ * A read-only client for the verified Trae usage/credits endpoints.
824
+ * All methods are safe to call from a plugin and never mutate account state.
825
+ */
826
+ declare class TraeUsageClient {
827
+ private readonly options;
828
+ private readonly fetchImpl;
829
+ private readonly baseUrl;
830
+ private readonly timeoutMs;
831
+ constructor(options: TraeUsageOptions);
832
+ private authedHeaders;
833
+ private post;
834
+ /** Total entitlements / credits and per-pack breakdown. */
835
+ snapshot(signal?: AbortSignal): Promise<TraeUsageSnapshot>;
836
+ /** Daily check-in status. */
837
+ checkinStatus(signal?: AbortSignal): Promise<TraeCheckinStatus>;
838
+ /** Rewards / activity rules. */
839
+ activities(signal?: AbortSignal): Promise<TraeActivityRule[]>;
840
+ /** Convenience: snapshot + check-in + activities in one call (best-effort, non-fatal on missing). */
841
+ view(signal?: AbortSignal): Promise<TraeUsageView>;
842
+ }
843
+ //#endregion
844
+ //#region src/status-paths.d.ts
845
+ /**
846
+ * Node-free constants and types shared by the Host and browser halves.
847
+ * Mirrors the `dsh-workbuddy-connect` status-route pattern so the plugin card
848
+ * stays consistent with that project's external presentation.
849
+ */
850
+ /** Plugin-owned usage endpoint consumed by its browser half. */
851
+ declare const TRAE_USAGE_PATH = "/plugins/dsh-connect-trae/usage";
852
+ /** One credit pack and its remaining credit. */
853
+ interface TraeWebCreditAccount {
854
+ displayDesc: string;
855
+ remain: number;
856
+ size: number;
857
+ }
858
+ /** Aggregated usage/credit answer rendered by the plugin card. */
859
+ interface TraeWebCredits {
860
+ total: number;
861
+ consumed: number;
862
+ available: number;
863
+ workAvailable: number;
864
+ generalAvailable: number;
865
+ accounts: readonly TraeWebCreditAccount[];
866
+ }
867
+ /** Editable Trae model row rendered by the plugin-owned settings card. */
868
+ interface TraeWebModel {
869
+ id: string;
870
+ name: string;
871
+ contextWindow?: number;
872
+ maxTokens?: number;
873
+ input?: ('text' | 'image')[];
874
+ creditMultiplier?: number;
875
+ reasoningSupported?: boolean;
876
+ reasoning?: {
877
+ supported: string[];
878
+ defaultEffort?: string;
879
+ };
880
+ baseModelId?: string;
881
+ maxContext?: boolean;
882
+ maxContextWindow?: number;
883
+ maxContextEnabled?: boolean;
884
+ }
885
+ /** Daily check-in status rendered by the card. */
886
+ interface TraeWebCheckin {
887
+ checkedIn: boolean;
888
+ credits: number;
889
+ }
890
+ /** One reward activity rule (name + work/general credits when present). */
891
+ interface TraeWebActivity {
892
+ activityId: string;
893
+ enabled: boolean;
894
+ workCredits?: number;
895
+ generalCredits?: number;
896
+ }
897
+ interface TraeWebAccount {
898
+ id: string;
899
+ accountName: string;
900
+ edition: 'cn' | 'sg' | 'solo' | 'solo-sg';
901
+ source: 'desktop' | 'dsh';
902
+ tokenExpiresAtMs: number;
903
+ selected: boolean;
904
+ }
905
+ /** The JSON document the plugin card renders. */
906
+ type TraeWebUsage = {
907
+ status: 'signed-out';
908
+ accounts: readonly TraeWebAccount[];
909
+ message?: string;
910
+ } | {
911
+ status: 'signed-in';
912
+ accountId: string;
913
+ accountName: string;
914
+ tokenExpiresAtMs: number;
915
+ accounts: readonly TraeWebAccount[];
916
+ models: readonly TraeWebModel[];
917
+ enabledModelIds: readonly string[];
918
+ enabled1mModelIds: readonly string[];
919
+ rawChat?: {
920
+ state: 'disabled' | 'unchecked' | 'available' | 'protocol-gated' | 'authentication' | 'credit' | 'rate' | 'transport' | 'server';
921
+ checkedAtMs?: number;
922
+ status?: number;
923
+ };
924
+ credits?: TraeWebCredits;
925
+ creditsError?: string;
926
+ } | {
927
+ status: 'error';
928
+ message: string;
929
+ };
930
+ //#endregion
931
+ //#region src/web-status.d.ts
932
+ /** Constructor dependencies. */
933
+ interface TraeUsageRouteOptions {
934
+ store: TraeCredentialStore;
935
+ client: TraeUsageClient;
936
+ /** The last-refreshed Trae raw directory (no generated @1m variants) for card display. */
937
+ displayModels(): readonly TraeModelInfo[];
938
+ /** The user's ordinary-model selection stored as model id (= Trae name). */
939
+ enabledModelIds(): readonly string[];
940
+ /** The user's 1M selection stored as base-model id. */
941
+ enabled1mModelIds(): readonly string[];
942
+ discoverModels?(signal?: AbortSignal): Promise<readonly TraeModelInfo[]>;
943
+ rawDiagnostic?(): TraeRawDiagnostic;
944
+ }
945
+ /**
946
+ * Assemble the card's usage document. Sign-in state is read-only; credit is a
947
+ * live billing answer whose failure degrades to `creditsError` rather than
948
+ * failing the whole document.
949
+ */
950
+ declare function traeWebUsage(deps: TraeUsageRouteOptions): Promise<TraeWebUsage>;
951
+ /** Mount the GET usage route on an optional webServer context. */
952
+ declare function registerTraeUsageRoute(ctx: Context, deps: TraeUsageRouteOptions): void;
953
+ //#endregion
954
+ //#region src/index.d.ts
955
+ declare const name = "llm-trae";
956
+ declare const inject: string[];
957
+ declare const TRAE_SETTINGS_NS: import("@deepseek-ai/dsh-settings").SettingsNamespace;
958
+ interface Config {
959
+ authFile?: string;
960
+ edition?: 'auto' | 'cn' | 'sg' | 'solo' | 'solo-sg';
961
+ /** Stable local account selector; tokens remain outside settings. */
962
+ accountId?: string;
963
+ /** The last-refreshed Trae raw directory; what the plugin card displays. */
964
+ lastCatalog?: TraeModelInfo[];
965
+ /** The user's ordinary-model selection, as model id (= Trae name). */
966
+ enabledModelIds?: string[];
967
+ /** The user's 1M selection, as base-model id. */
968
+ enabled1mModels?: string[];
969
+ /** Legacy generated runtime catalog; kept for backwards compatibility. */
970
+ models?: TraeModelInfo[];
971
+ }
972
+ declare const Config: z<Config>;
973
+ declare function apply(ctx: Context, config: Config): void;
974
+ //#endregion
975
+ export { Config, FALLBACK_TRAE_MODELS, type RawChatDelta, type RawChatMessage, type RawChatTool, SseDecoder, type SseEvent, TRAE_CN_AGENT_TASK_PATH, TRAE_CN_TITLE_PATH, TRAE_MODEL_DETAIL_FUNCTIONS, TRAE_MODEL_DETAIL_PATH, TRAE_PAY_BASE, TRAE_PROVIDER, TRAE_RAW_CHAT_V1_PATH, TRAE_RAW_CHAT_V2_PATH, TRAE_REASONING_EFFORTS, TRAE_SETTINGS_NS, TRAE_SOLO_CHAT_PATH, TRAE_SOLO_FUNCTION, TRAE_SOLO_MODELS_PATH, TRAE_SOLO_REMOTE_BASE, TRAE_SOLO_REMOTE_MODELS, TRAE_STREAM_IDLE_TIMEOUT_MS, TRAE_USAGE_PATH, TRAE_VERSION_CODE_FALLBACK, type TraeActivityRule, type TraeCachedModelConfig, TraeCatalog, type TraeChatResult, type TraeCheckinStatus, type TraeCredential, TraeCredentialStore, TraeDelegatingUpstreamClient, type TraeDiscoveredModel, type TraeDiscoveredReasoning, type TraeEdition, TraeFallbackUpstreamClient, type TraeFallbackUpstreamOptions, type TraeFusionRawChatEnvelope, TraeGatedUpstreamClient, type TraeGatedUpstreamOptions, type TraeIdentity, type TraeModelDetailRequest, type TraeModelInfo, type TraeObservedModelConfig, TraeRawCapabilityController, type TraeRawCapabilityControllerOptions, type TraeRawCapabilitySnapshot, TraeRawCapabilityState, type TraeRawChatBehaviorConfig, type TraeRawChatCapability, type TraeRawChatClientOptions, type TraeRawChatConfig, type TraeRawChatFailureReason, type TraeRawChatRuntimeConfig, TraeRawChatUpstreamClient, type TraeRawDiagnostic, type TraeRawDiagnosticState, type TraeRawGateway, type TraeRawGatewayOptions, type TraeRawResolverResult, type TraeReasoningCapability, type TraeReasoningEffort, type TraeShim, TraeSoloBridge, type TraeSoloClientOptions, TraeSoloRemoteBridge, TraeSoloRemoteClient, type TraeSoloRemoteOptions, TraeSoloUpstreamClient, type TraeStorageCandidate, type TraeStreamEvent, type TraeUpstreamClient, TraeUsageClient, type TraeUsageOptions, type TraeUsagePack, type TraeUsageRouteOptions, type TraeUsageSnapshot, type TraeUsageSummary, type TraeUsageView, type TraeWebActivity, type TraeWebCheckin, type TraeWebCredits, type TraeWebUsage, UnconfiguredTraeUpstreamClient, apply, applyReasoningEffort, bridgeTraeSoloStream, buildTraeAgentTaskBody, buildTraeCnHeaders, buildTraeFusionRawChatEnvelope, buildTraeModelDetailRequest, buildTraeRawChatDraft, buildTraeRawChatRuntimeConfig, classifyTraeRawChatFailure, createTraeAdapter, createTraeRawGateway, createTraeShim, decodeRawChatChunk, decodeTraeEvent, decryptTraeStorageValue, discoveredCatalog, hashTraeRawChatArg, identityHeaders, inject, name, normalizeTraeCredential, normalizeTraeVersionCode, parseObservedModelConfig, parseReasoningCapability, parseTraeAuthValue, parseTraeCachedModel, parseTraeModelExtraConfigLogLine, parseTraeRawChatBehaviorConfig, parseTraeRemoteModel, parseTraeStorageDocument, prepareSoloBody, probeTraeRawChatCapability, rawCapabilityDiagnostic, rawCapabilityFingerprint, readTraeCachedModel, readTraeIdentity, refreshTraeCredential, registerTraeUsageRoute, resolveTraeRawRuntime, traeEndpoint, traeOwnAuthPath, traeRawChatExtraInfo, traeStorageCandidates, traeWebUsage };