pi-tsgw 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pi-tsgw contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # pi-tsgw
2
+
3
+ Pi extension for the TOSSP AIH gateway. Registers the `tsgw` provider with a
4
+ model catalog spanning four wire protocols (openai-completions,
5
+ openai-responses, anthropic-messages, google-generative-ai) and applies
6
+ per-vendor request-body operations so thinking levels, reasoning formats, and
7
+ optional built-in web search behave correctly on the gateway.
8
+
9
+ No API keys, endpoints, or pricing are baked into this package: everything
10
+ gateway-specific is configuration.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pi install git:github.com/tossp/pi-tsgw
16
+ ```
17
+
18
+ or, for npm:
19
+
20
+ ```bash
21
+ pi install npm:pi-tsgw
22
+ ```
23
+
24
+ Then `/reload` (or restart pi). The provider appears as `tsgw` in the model
25
+ picker.
26
+
27
+ ## Configuration
28
+
29
+ All configuration lives in the `tsgw` namespace of `~/.pi/agent/settings.json`.
30
+ The plugin reads no environment variables; only Pi's own credential
31
+ resolution handles API keys.
32
+
33
+ Example:
34
+
35
+ ```json
36
+ {
37
+ "tsgw": {
38
+ "baseUrl": "https://aih.example.net",
39
+ "webSearch": "off",
40
+ "traceHeaders": false,
41
+ "includeModels": ["gpt-5.6-*", "claude-*"],
42
+ "excludeModels": ["gpt-5.3-*"]
43
+ }
44
+ }
45
+ ```
46
+
47
+ ### Gateway address
48
+
49
+ `baseUrl` points at your AIH gateway (any instance — the public one or a
50
+ self-hosted one). The `/v1` suffix is normalized away. If unset, a neutral
51
+ placeholder root is used that will not work.
52
+
53
+ ### API key
54
+
55
+ The extension never reads credential files. Pi resolves the key itself:
56
+
57
+ 1. **`/login`** — select the `tsgw` provider and enter the key; pi stores it
58
+ in `~/.pi/agent/auth.json` (preferred)
59
+ 2. **`TSGW_API_KEY`** environment variable — Pi's fallback when nothing is
60
+ stored
61
+
62
+ ### Options
63
+
64
+ | Setting (`settings.json` `tsgw.*`) | Default | Meaning |
65
+ | --- | --- | --- |
66
+ | `baseUrl` | placeholder | Gateway root (the `/v1` suffix is normalized away) |
67
+ | `webSearch` | `off` | `off`, `cached`, or `live` — appends the built-in `web_search` tool for models with built-in search (GPT / Grok) |
68
+ | `traceHeaders` | `false` | Adds `AH-Thread-Id` / `AH-Trace-Id` headers for gateway-side tracing |
69
+ | `includeModels` | unset | Whitelist: only these model ids are registered (exact id or `prefix-*` glob) |
70
+ | `excludeModels` | unset | Blacklist: these model ids are dropped (exact id or `prefix-*` glob); blacklist wins over whitelist |
71
+
72
+ ## Model catalog
73
+
74
+ The catalog is assembled from per-vendor slices (`extensions/models/vendors/`),
75
+ currently covering 10 vendor families: DeepSeek, GLM (Zhipu), MiMo (Xiaomi),
76
+ MiniMax, Kimi (Moonshot), Qwen (Alibaba), GPT (OpenAI), Gemini (Google),
77
+ Claude (Anthropic), and LongCat — 59 chat models in total. Each vendor file
78
+ carries the official documentation URL in its header comment. Pricing entries
79
+ mirror the vendors' public list prices; replace them with your gateway's
80
+ actual pricing if it differs.
81
+
82
+ Use `includeModels` / `excludeModels` to register only the models your
83
+ gateway plan actually supports.
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ npm install
89
+ npm test
90
+ ```
91
+
92
+ Tests run against a fake pi host (`FakePi` + `FakeContext`) and isolate the
93
+ config directory through `PI_CODING_AGENT_DIR`, so no pi installation is
94
+ needed to run them.
95
+
96
+ ## Technical details
97
+
98
+ Per-vendor thinking profiles (the request-body matrix), the built-in web
99
+ search injection semantics, and the pi lifecycle compatibility notes live in
100
+ [AGENTS.md](AGENTS.md).
@@ -0,0 +1,509 @@
1
+ import { deepStrictEqual, equal, match, strictEqual } from "node:assert";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type {
6
+ ExtensionAPI,
7
+ ProviderConfig,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import registerTsgw from "./index.ts";
10
+
11
+ type HookName =
12
+ | "session_start"
13
+ | "agent_start"
14
+ | "model_select"
15
+ | "thinking_level_select"
16
+ | "before_provider_request"
17
+ | "before_provider_headers";
18
+
19
+ const STALE_ERROR = "Extension context is stale after runtime replacement";
20
+ const TEST_ROOT = "https://aih.example.com";
21
+ const TSGW_TERRA = {
22
+ provider: "tsgw",
23
+ id: "gpt-5.6-terra",
24
+ api: "openai-responses",
25
+ baseUrl: `${TEST_ROOT}/v1`,
26
+ };
27
+ const TSGW_DEEPSEEK = {
28
+ provider: "tsgw",
29
+ id: "deepseek-v4-flash",
30
+ api: "openai-completions",
31
+ baseUrl: `${TEST_ROOT}/v1`,
32
+ };
33
+ const TSGW_GLM = {
34
+ provider: "tsgw",
35
+ id: "glm-5.2",
36
+ api: "openai-completions",
37
+ baseUrl: `${TEST_ROOT}/v1`,
38
+ };
39
+
40
+ class FakeContext {
41
+ private stale = false;
42
+
43
+ constructor(
44
+ private readonly currentModel:
45
+ | typeof TSGW_TERRA
46
+ | typeof TSGW_DEEPSEEK
47
+ | typeof TSGW_GLM
48
+ | { provider: string; id: string; api: string; baseUrl: string }
49
+ | undefined,
50
+ private readonly currentThinkingLevel: "off" | "high" | "low",
51
+ ) {}
52
+
53
+ get model(): typeof this.currentModel {
54
+ this.assertFresh();
55
+ return this.currentModel;
56
+ }
57
+
58
+ get thinkingLevel(): typeof this.currentThinkingLevel {
59
+ this.assertFresh();
60
+ return this.currentThinkingLevel;
61
+ }
62
+
63
+ makeStale(): void {
64
+ this.stale = true;
65
+ }
66
+
67
+ private assertFresh(): void {
68
+ if (this.stale) throw new Error(STALE_ERROR);
69
+ }
70
+ }
71
+
72
+ class FakePi {
73
+ readonly providers: Array<{ name: string; config: unknown }> = [];
74
+ private readonly handlers = new Map<HookName, unknown[]>();
75
+
76
+ on: ExtensionAPI["on"] = (event, handler) => {
77
+ if (!this.isHookName(event)) return;
78
+ const handlers = this.handlers.get(event) ?? [];
79
+ handlers.push(handler);
80
+ this.handlers.set(event, handlers);
81
+ };
82
+ registerTool: ExtensionAPI["registerTool"] = () => {};
83
+ registerCommand: ExtensionAPI["registerCommand"] = () => {};
84
+ registerShortcut: ExtensionAPI["registerShortcut"] = () => {};
85
+ registerFlag: ExtensionAPI["registerFlag"] = () => {};
86
+ getFlag: ExtensionAPI["getFlag"] = () => undefined;
87
+ registerMessageRenderer: ExtensionAPI["registerMessageRenderer"] = () => {};
88
+ registerEntryRenderer: ExtensionAPI["registerEntryRenderer"] = () => {};
89
+ sendMessage: ExtensionAPI["sendMessage"] = () => {};
90
+ sendUserMessage: ExtensionAPI["sendUserMessage"] = () => {};
91
+ appendEntry: ExtensionAPI["appendEntry"] = () => {};
92
+ setSessionName: ExtensionAPI["setSessionName"] = () => {};
93
+ getSessionName: ExtensionAPI["getSessionName"] = () => undefined;
94
+ setLabel: ExtensionAPI["setLabel"] = () => {};
95
+ exec: ExtensionAPI["exec"] = async () => {
96
+ throw new Error("FakePi.exec is not used by this test");
97
+ };
98
+ getActiveTools: ExtensionAPI["getActiveTools"] = () => [];
99
+ getAllTools: ExtensionAPI["getAllTools"] = () => [];
100
+ setActiveTools: ExtensionAPI["setActiveTools"] = () => {};
101
+ getCommands: ExtensionAPI["getCommands"] = () => [];
102
+ setModel: ExtensionAPI["setModel"] = async () => false;
103
+ getThinkingLevel: ExtensionAPI["getThinkingLevel"] = () => {
104
+ throw new Error("legacy getThinkingLevel must not be called");
105
+ };
106
+ setThinkingLevel: ExtensionAPI["setThinkingLevel"] = () => {};
107
+ unregisterProvider: ExtensionAPI["unregisterProvider"] = () => {};
108
+
109
+ get events(): ExtensionAPI["events"] {
110
+ throw new Error("FakePi.events is not used by this test");
111
+ }
112
+
113
+ registerProvider(_provider: unknown): void;
114
+ registerProvider(name: string, config: ProviderConfig): void;
115
+ registerProvider(nameOrProvider: unknown, config?: ProviderConfig): void {
116
+ if (typeof nameOrProvider === "string")
117
+ this.providers.push({ name: nameOrProvider, config });
118
+ }
119
+
120
+ has(event: HookName): boolean {
121
+ return (this.handlers.get(event)?.length ?? 0) > 0;
122
+ }
123
+
124
+ invoke(event: HookName, payload: unknown, ctx?: unknown): unknown {
125
+ const handlers = this.handlers.get(event);
126
+ if (!handlers?.length) throw new Error(`missing ${event} handler`);
127
+ let result: unknown;
128
+ for (const handler of handlers) {
129
+ if (typeof handler !== "function")
130
+ throw new Error(`invalid ${event} handler`);
131
+ result = handler(payload, ctx);
132
+ }
133
+ return result;
134
+ }
135
+
136
+ private isHookName(event: string): event is HookName {
137
+ return (
138
+ event === "session_start" ||
139
+ event === "agent_start" ||
140
+ event === "model_select" ||
141
+ event === "thinking_level_select" ||
142
+ event === "before_provider_request" ||
143
+ event === "before_provider_headers"
144
+ );
145
+ }
146
+ }
147
+
148
+ async function createPi(settings?: unknown): Promise<FakePi> {
149
+ const pi = new FakePi();
150
+ await withAgentDir(settings, async () => {
151
+ await registerTsgw(pi);
152
+ });
153
+ return pi;
154
+ }
155
+
156
+ function sessionStart(
157
+ pi: FakePi,
158
+ ctx: FakeContext,
159
+ reason: "startup" | "reload" | "new" | "resume" | "fork" = "startup",
160
+ ): void {
161
+ pi.invoke("session_start", { type: "session_start", reason }, ctx);
162
+ }
163
+
164
+ function agentStart(pi: FakePi, ctx: FakeContext): void {
165
+ pi.invoke("agent_start", { type: "agent_start" }, ctx);
166
+ }
167
+
168
+ function providerRequest(pi: FakePi, payload: unknown): unknown {
169
+ return pi.invoke("before_provider_request", {
170
+ type: "before_provider_request",
171
+ payload,
172
+ });
173
+ }
174
+
175
+ function providerHeaders(
176
+ pi: FakePi,
177
+ headers: Record<string, string | null>,
178
+ ): void {
179
+ pi.invoke("before_provider_headers", {
180
+ type: "before_provider_headers",
181
+ headers,
182
+ });
183
+ }
184
+
185
+ /**
186
+ * Isolate the extension from the real Pi config directory: point
187
+ * PI_CODING_AGENT_DIR at a throwaway directory that may contain a
188
+ * settings.json with a `tsgw` namespace.
189
+ */
190
+ function withAgentDir(
191
+ settings: unknown,
192
+ run: () => Promise<void>,
193
+ ): Promise<void> {
194
+ const dir = mkdtempSync(join(tmpdir(), "pi-tsgw-test-"));
195
+ if (settings !== undefined) {
196
+ writeFileSync(join(dir, "settings.json"), JSON.stringify(settings));
197
+ }
198
+ const previous = process.env.PI_CODING_AGENT_DIR;
199
+ process.env.PI_CODING_AGENT_DIR = dir;
200
+ return run().finally(() => {
201
+ if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR;
202
+ else process.env.PI_CODING_AGENT_DIR = previous;
203
+ rmSync(dir, { recursive: true, force: true });
204
+ });
205
+ }
206
+
207
+ function assertUuid(value: string | null | undefined): void {
208
+ match(
209
+ value ?? "",
210
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
211
+ );
212
+ }
213
+
214
+ async function testChatCompletionsCompatibility(): Promise<void> {
215
+ const pi = await createPi();
216
+ const provider = pi.providers.find(({ name }) => name === "tsgw");
217
+ const models =
218
+ (
219
+ provider?.config as
220
+ | {
221
+ models?: Array<{
222
+ id: string;
223
+ api?: string;
224
+ compat?: { supportsDeveloperRole?: boolean };
225
+ }>;
226
+ }
227
+ | undefined
228
+ )?.models ?? [];
229
+ const completionModels = models.filter(
230
+ ({ api }) => api === "openai-completions",
231
+ );
232
+
233
+ equal(completionModels.length > 0, true);
234
+ for (const model of completionModels) {
235
+ strictEqual(
236
+ model.compat?.supportsDeveloperRole,
237
+ false,
238
+ `${model.id} must send its instruction prompt as system, not developer`,
239
+ );
240
+ }
241
+ }
242
+
243
+ async function testSafeProviderHooksAfterContextStales(): Promise<void> {
244
+ const pi = await createPi({
245
+ tsgw: { traceHeaders: true, webSearch: "cached" },
246
+ });
247
+ const sessionContext = new FakeContext(TSGW_TERRA, "high");
248
+ sessionStart(pi, sessionContext);
249
+
250
+ const firstHeaders: Record<string, string | null> = {};
251
+ providerHeaders(pi, firstHeaders);
252
+ const agentContext = new FakeContext(TSGW_TERRA, "high");
253
+ agentStart(pi, agentContext);
254
+ sessionContext.makeStale();
255
+ agentContext.makeStale();
256
+ pi.getThinkingLevel = () => {
257
+ throw new Error(STALE_ERROR);
258
+ };
259
+
260
+ deepStrictEqual(providerRequest(pi, { tools: [] }), {
261
+ tools: [
262
+ {
263
+ type: "web_search",
264
+ search_context_size: "medium",
265
+ external_web_access: false,
266
+ },
267
+ ],
268
+ service_tier: "flex",
269
+ text: { verbosity: "medium" },
270
+ });
271
+ const headers: Record<string, string | null> = {};
272
+ providerHeaders(pi, headers);
273
+ assertUuid(headers["AH-Thread-Id"]);
274
+ assertUuid(headers["AH-Trace-Id"]);
275
+ strictEqual(headers["AH-Thread-Id"], firstHeaders["AH-Thread-Id"]);
276
+ if (headers["AH-Trace-Id"] === firstHeaders["AH-Trace-Id"])
277
+ throw new Error("agent_start must refresh AH-Trace-Id");
278
+
279
+ const preserved = {
280
+ "ah-thread-id": "keep-thread",
281
+ "AH-Trace-Id": "keep-trace",
282
+ };
283
+ providerHeaders(pi, preserved);
284
+ deepStrictEqual(preserved, {
285
+ "ah-thread-id": "keep-thread",
286
+ "AH-Trace-Id": "keep-trace",
287
+ });
288
+ }
289
+
290
+ async function testLifecycleStateUpdates(): Promise<void> {
291
+ const pi = await createPi();
292
+ sessionStart(pi, new FakeContext(TSGW_DEEPSEEK, "high"));
293
+ deepStrictEqual(providerRequest(pi, {}), {
294
+ reasoning_effort: "high",
295
+ thinking: { type: "enabled" },
296
+ });
297
+
298
+ pi.invoke("thinking_level_select", {
299
+ type: "thinking_level_select",
300
+ level: "off",
301
+ previousLevel: "high",
302
+ });
303
+ deepStrictEqual(providerRequest(pi, {}), {
304
+ thinking: { type: "disabled" },
305
+ });
306
+
307
+ pi.invoke("model_select", {
308
+ type: "model_select",
309
+ model: TSGW_GLM,
310
+ previousModel: TSGW_DEEPSEEK,
311
+ source: "set",
312
+ });
313
+ deepStrictEqual(providerRequest(pi, { stream: true }), {
314
+ stream: true,
315
+ tool_stream: true,
316
+ reasoning_effort: "none",
317
+ thinking: { type: "disabled" },
318
+ });
319
+
320
+ pi.invoke("thinking_level_select", {
321
+ type: "thinking_level_select",
322
+ level: "high",
323
+ previousLevel: "off",
324
+ });
325
+ deepStrictEqual(providerRequest(pi, { stream: true }), {
326
+ stream: true,
327
+ tool_stream: true,
328
+ reasoning_effort: "high",
329
+ thinking: { type: "enabled", clear_thinking: false },
330
+ });
331
+
332
+ const agentContext = new FakeContext(TSGW_DEEPSEEK, "off");
333
+ agentStart(pi, agentContext);
334
+ agentContext.makeStale();
335
+ deepStrictEqual(providerRequest(pi, {}), {
336
+ thinking: { type: "disabled" },
337
+ });
338
+ }
339
+
340
+ async function testNoStateAndTraceLimits(): Promise<void> {
341
+ const pi = await createPi();
342
+ const payload = { untouched: true };
343
+ strictEqual(providerRequest(pi, payload), undefined);
344
+ // 未启用 trace 时,不注册 before_provider_headers 钩子。
345
+ equal(pi.has("before_provider_headers"), false);
346
+ }
347
+
348
+ async function testTraceHeaderSettings(): Promise<void> {
349
+ const pi = await createPi({ tsgw: { traceHeaders: true } });
350
+ equal(pi.has("before_provider_headers"), true);
351
+
352
+ // 无 session 状态:不产生追踪头。
353
+ const empty: Record<string, string | null> = {};
354
+ providerHeaders(pi, empty);
355
+ deepStrictEqual(empty, {});
356
+
357
+ // 非 tsgw provider 不追踪。
358
+ sessionStart(
359
+ pi,
360
+ new FakeContext({ ...TSGW_TERRA, provider: "other" }, "high"),
361
+ );
362
+ const foreign: Record<string, string | null> = {};
363
+ providerHeaders(pi, foreign);
364
+ deepStrictEqual(foreign, {});
365
+
366
+ // 模型 baseUrl 与配置 root 不同 host 时不追踪。
367
+ sessionStart(
368
+ pi,
369
+ new FakeContext(
370
+ { ...TSGW_TERRA, baseUrl: "https://example.test/v1" },
371
+ "high",
372
+ ),
373
+ );
374
+ const otherHost: Record<string, string | null> = {};
375
+ providerHeaders(pi, otherHost);
376
+ deepStrictEqual(otherHost, {});
377
+
378
+ // 匹配 host:产生追踪头。
379
+ sessionStart(pi, new FakeContext(TSGW_TERRA, "high"));
380
+ const headers: Record<string, string | null> = {};
381
+ providerHeaders(pi, headers);
382
+ assertUuid(headers["AH-Thread-Id"]);
383
+ assertUuid(headers["AH-Trace-Id"]);
384
+ }
385
+
386
+ async function testOldInstanceCallbacksKeepOwnSnapshot(): Promise<void> {
387
+ const replacements = [
388
+ { label: "reload", reason: "reload" },
389
+ { label: "new", reason: "new" },
390
+ { label: "fork", reason: "fork" },
391
+ { label: "switch", reason: "resume" },
392
+ ] as const;
393
+
394
+ for (const replacement of replacements) {
395
+ const oldPi = await createPi({
396
+ tsgw: { traceHeaders: true, webSearch: "cached" },
397
+ });
398
+ const oldContext = new FakeContext(TSGW_TERRA, "high");
399
+ sessionStart(oldPi, oldContext);
400
+ agentStart(oldPi, oldContext);
401
+ oldContext.makeStale();
402
+ oldPi.getThinkingLevel = () => {
403
+ throw new Error(STALE_ERROR);
404
+ };
405
+
406
+ const newPi = await createPi();
407
+ sessionStart(
408
+ newPi,
409
+ new FakeContext(TSGW_DEEPSEEK, "off"),
410
+ replacement.reason,
411
+ );
412
+
413
+ deepStrictEqual(
414
+ providerRequest(oldPi, { tools: [] }),
415
+ {
416
+ tools: [
417
+ {
418
+ type: "web_search",
419
+ search_context_size: "medium",
420
+ external_web_access: false,
421
+ },
422
+ ],
423
+ service_tier: "flex",
424
+ text: { verbosity: "medium" },
425
+ },
426
+ `${replacement.label}: late old callback must retain its own state`,
427
+ );
428
+ deepStrictEqual(
429
+ providerRequest(newPi, {}),
430
+ { thinking: { type: "disabled" } },
431
+ `${replacement.label}: new instance must use its own state`,
432
+ );
433
+
434
+ const headers: Record<string, string | null> = {};
435
+ providerHeaders(oldPi, headers);
436
+ assertUuid(headers["AH-Thread-Id"]);
437
+ assertUuid(headers["AH-Trace-Id"]);
438
+ }
439
+ }
440
+
441
+ async function testSettingsConfig(): Promise<void> {
442
+ // settings.json `tsgw.baseUrl` drives the registered provider root.
443
+ const piBase = await createPi({
444
+ tsgw: { baseUrl: "https://gateway.example.net" },
445
+ });
446
+ const provider = piBase.providers.find(({ name }) => name === "tsgw");
447
+ const baseUrl = (provider?.config as { baseUrl?: string } | undefined)
448
+ ?.baseUrl;
449
+ strictEqual(baseUrl, "https://gateway.example.net/v1");
450
+
451
+ // `tsgw.webSearch: "live"` enables the built-in search injection.
452
+ const piSearch = await createPi({ tsgw: { webSearch: "live" } });
453
+ sessionStart(piSearch, new FakeContext(TSGW_TERRA, "high"));
454
+ deepStrictEqual(providerRequest(piSearch, { tools: [] }), {
455
+ tools: [
456
+ {
457
+ type: "web_search",
458
+ search_context_size: "medium",
459
+ external_web_access: true,
460
+ },
461
+ ],
462
+ service_tier: "flex",
463
+ text: { verbosity: "medium" },
464
+ });
465
+
466
+ // `tsgw.includeModels` / `tsgw.excludeModels` filter the model catalog.
467
+ const piFiltered = await createPi({
468
+ tsgw: {
469
+ includeModels: ["glm-*"],
470
+ excludeModels: ["glm-5.1"],
471
+ },
472
+ });
473
+ const filtered = piFiltered.providers.find(({ name }) => name === "tsgw");
474
+ const modelIds = (
475
+ (filtered?.config as { models?: Array<{ id: string }> } | undefined)
476
+ ?.models ?? []
477
+ ).map(({ id }) => id);
478
+ equal(modelIds.length > 1, true);
479
+ equal(
480
+ modelIds.every((id) => id.startsWith("glm-")),
481
+ true,
482
+ );
483
+ equal(modelIds.includes("glm-5.2"), true);
484
+ equal(modelIds.includes("glm-5.1"), false);
485
+
486
+ // Malformed or missing `tsgw` namespaces are ignored.
487
+ const piBroken = await createPi({ tsgw: "not-an-object" });
488
+ const brokenProvider = piBroken.providers.find(({ name }) => name === "tsgw");
489
+ const brokenBase = (
490
+ brokenProvider?.config as { baseUrl?: string } | undefined
491
+ )?.baseUrl;
492
+ strictEqual(brokenBase, `${TEST_ROOT}/v1`);
493
+ }
494
+
495
+ async function main(): Promise<void> {
496
+ await testChatCompletionsCompatibility();
497
+ await testSafeProviderHooksAfterContextStales();
498
+ await testLifecycleStateUpdates();
499
+ await testNoStateAndTraceLimits();
500
+ await testTraceHeaderSettings();
501
+ await testOldInstanceCallbacksKeepOwnSnapshot();
502
+ await testSettingsConfig();
503
+ console.log("index.test.ts: all assertions passed");
504
+ }
505
+
506
+ void main().catch((error: unknown) => {
507
+ console.error(error);
508
+ process.exitCode = 1;
509
+ });