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.
@@ -0,0 +1,185 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ import {
7
+ DEFAULT_ROOT,
8
+ PROVIDER_ID,
9
+ modelsForRoot,
10
+ normalizeRoot,
11
+ type ModelFilter,
12
+ } from "./models/catalog.ts";
13
+ import { applyModelOperations } from "./models/operations.ts";
14
+ import type { ThinkingLevel, WebSearchMode } from "./models/_tools.ts";
15
+ import { applyWebSearchTool } from "./web-search/web-search.ts";
16
+
17
+ /**
18
+ * The data needed by provider hooks, copied while the lifecycle context is
19
+ * fresh. Keep this structural: stale runners may invoke those hooks later.
20
+ */
21
+ interface RequestState {
22
+ provider: string;
23
+ modelId: string;
24
+ api: string;
25
+ baseUrl: string;
26
+ thinkingLevel: ThinkingLevel;
27
+ }
28
+
29
+ interface RequestModel {
30
+ provider: string;
31
+ id: string;
32
+ api: string;
33
+ baseUrl: string;
34
+ }
35
+
36
+ /**
37
+ * Extension configuration from the `tsgw` namespace of the Pi settings file
38
+ * (settings.json). All plugin configuration lives here; the plugin reads no
39
+ * environment variables (only Pi's own credential resolution handles keys).
40
+ */
41
+ interface TsgwSettings {
42
+ baseUrl?: string;
43
+ webSearch?: string;
44
+ traceHeaders?: boolean;
45
+ includeModels?: string[];
46
+ excludeModels?: string[];
47
+ }
48
+
49
+ function readTsgwSettings(): TsgwSettings {
50
+ try {
51
+ const raw: unknown = JSON.parse(
52
+ readFileSync(join(getAgentDir(), "settings.json"), "utf8"),
53
+ );
54
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
55
+ return {};
56
+ const tsgw = (raw as { tsgw?: unknown }).tsgw;
57
+ if (tsgw === null || typeof tsgw !== "object" || Array.isArray(tsgw))
58
+ return {};
59
+ return tsgw as TsgwSettings;
60
+ } catch {
61
+ return {};
62
+ }
63
+ }
64
+
65
+ function rootForRuntime(configured: string | undefined): string {
66
+ try {
67
+ return normalizeRoot(configured);
68
+ } catch {
69
+ console.error("TSGW: invalid baseUrl; using the default root.");
70
+ return DEFAULT_ROOT;
71
+ }
72
+ }
73
+
74
+ function hasHeader(
75
+ headers: Record<string, string | null>,
76
+ name: string,
77
+ ): boolean {
78
+ return Object.keys(headers).some(
79
+ (key) => key.toLowerCase() === name.toLowerCase(),
80
+ );
81
+ }
82
+
83
+ function requestStateFor(
84
+ model: RequestModel | undefined,
85
+ thinkingLevel: ThinkingLevel,
86
+ ): RequestState | undefined {
87
+ if (!model) return undefined;
88
+ return {
89
+ provider: model.provider,
90
+ modelId: model.id,
91
+ api: model.api,
92
+ baseUrl: model.baseUrl,
93
+ thinkingLevel,
94
+ };
95
+ }
96
+
97
+ function isTsgwTraceTarget(state: RequestState, root: string): boolean {
98
+ if (state.provider !== PROVIDER_ID) return false;
99
+ try {
100
+ // Only trace requests that target the configured gateway root, so a
101
+ // model whose baseUrl was overridden elsewhere never gets trace headers.
102
+ return new URL(state.baseUrl).hostname === new URL(root).hostname;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
109
+ const settings = readTsgwSettings();
110
+ const root = rootForRuntime(settings.baseUrl);
111
+ const webSearchMode: WebSearchMode =
112
+ settings.webSearch === "cached" || settings.webSearch === "live"
113
+ ? settings.webSearch
114
+ : "off";
115
+ const traceEnabled = settings.traceHeaders === true;
116
+ const modelFilter: ModelFilter = {
117
+ include: settings.includeModels,
118
+ exclude: settings.excludeModels,
119
+ };
120
+ let requestState: RequestState | undefined;
121
+
122
+ const refreshRequestState = (ctx: {
123
+ model: RequestModel | undefined;
124
+ thinkingLevel?: ThinkingLevel;
125
+ }): void => {
126
+ requestState = requestStateFor(ctx.model, ctx.thinkingLevel ?? "off");
127
+ };
128
+
129
+ pi.registerProvider(PROVIDER_ID, {
130
+ name: "TSGW",
131
+ baseUrl: `${root}/v1`,
132
+ api: "openai-completions",
133
+ apiKey: "$TSGW_API_KEY",
134
+ models: modelsForRoot(root, modelFilter),
135
+ });
136
+
137
+ pi.on("session_start", (_event, ctx) => {
138
+ refreshRequestState(ctx);
139
+ });
140
+ pi.on("agent_start", (_event, ctx) => {
141
+ refreshRequestState(ctx);
142
+ });
143
+ pi.on("model_select", (event) => {
144
+ requestState = requestStateFor(
145
+ event.model,
146
+ requestState?.thinkingLevel ?? "off",
147
+ );
148
+ });
149
+ pi.on("thinking_level_select", (event) => {
150
+ if (requestState)
151
+ requestState = { ...requestState, thinkingLevel: event.level };
152
+ });
153
+
154
+ pi.on("before_provider_request", (event) => {
155
+ const state = requestState;
156
+ if (!state) return;
157
+ const context = {
158
+ provider: state.provider,
159
+ modelId: state.modelId,
160
+ api: state.api,
161
+ thinkingLevel: state.thinkingLevel,
162
+ };
163
+ // 模型模块:厂商思维链改写 → 网络模块:内置查询工具注入(两模块互不感知)。
164
+ return applyWebSearchTool(applyModelOperations(event.payload, context), {
165
+ modelId: state.modelId,
166
+ api: state.api,
167
+ mode: webSearchMode,
168
+ });
169
+ });
170
+
171
+ if (!traceEnabled) return;
172
+ const threadId = randomUUID();
173
+ let traceId = randomUUID();
174
+ pi.on("agent_start", () => {
175
+ traceId = randomUUID();
176
+ });
177
+ pi.on("before_provider_headers", (event) => {
178
+ const state = requestState;
179
+ if (!state || !isTsgwTraceTarget(state, root)) return;
180
+ if (!hasHeader(event.headers, "AH-Thread-Id"))
181
+ event.headers["AH-Thread-Id"] = threadId;
182
+ if (!hasHeader(event.headers, "AH-Trace-Id"))
183
+ event.headers["AH-Trace-Id"] = traceId;
184
+ });
185
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * 通用请求改写工具:copy-on-write 的 PayloadWriter、类型与共享辅助函数。
3
+ *
4
+ * 这是 models 模块的内部工具层(下划线前缀 = 不对外暴露),vendors 分片
5
+ * 与 operations 调度都从这里引用,避免 vendors ↔ operations 循环依赖。
6
+ */
7
+
8
+ export type ThinkingLevel =
9
+ | "off"
10
+ | "minimal"
11
+ | "low"
12
+ | "medium"
13
+ | "high"
14
+ | "xhigh"
15
+ | "max";
16
+ export type WebSearchMode = "off" | "cached" | "live";
17
+
18
+ export interface ModelOperationContext {
19
+ provider: string;
20
+ modelId: string;
21
+ api: string;
22
+ thinkingLevel: ThinkingLevel;
23
+ }
24
+
25
+ export type Payload = Record<string, unknown>;
26
+ type GoogleThinkingField =
27
+ | "includeThoughts"
28
+ | "thinkingLevel"
29
+ | "thinkingBudget";
30
+ type ThinkingUpdate = Partial<Pick<Payload, "type" | "clear_thinking">>;
31
+ type GoogleThinkingUpdate = Partial<Pick<Payload, GoogleThinkingField>>;
32
+
33
+ export function isPlainObject(value: unknown): value is Payload {
34
+ if (value === null || typeof value !== "object") return false;
35
+ const prototype = Object.getPrototypeOf(value);
36
+ return prototype === Object.prototype || prototype === null;
37
+ }
38
+
39
+ /** Copy the top level and nested objects only when a declared operation changes them. */
40
+ export class PayloadWriter {
41
+ private copy: Payload | undefined;
42
+
43
+ constructor(private readonly payload: Payload) {}
44
+
45
+ get(key: string): unknown {
46
+ return (this.copy ?? this.payload)[key];
47
+ }
48
+
49
+ set(key: string, value: unknown): void {
50
+ if (Object.is(this.get(key), value)) return;
51
+ this.mutable()[key] = value;
52
+ }
53
+
54
+ remove(key: string): void {
55
+ if (!Object.hasOwn(this.copy ?? this.payload, key)) return;
56
+ delete this.mutable()[key];
57
+ }
58
+
59
+ setThinking(values: ThinkingUpdate): void {
60
+ const current = this.get("thinking");
61
+ const thinking = isPlainObject(current) ? current : {};
62
+ const changed =
63
+ !isPlainObject(current) ||
64
+ THINKING_FIELDS.some(
65
+ (key) => key in values && !Object.is(thinking[key], values[key]),
66
+ );
67
+ if (changed) this.set("thinking", { ...thinking, ...values });
68
+ }
69
+
70
+ setGoogleThinking(
71
+ values: GoogleThinkingUpdate,
72
+ remove: readonly GoogleThinkingField[] = [],
73
+ ): void {
74
+ const currentConfig = this.get("config");
75
+ if (currentConfig !== undefined && !isPlainObject(currentConfig)) return;
76
+
77
+ const config = isPlainObject(currentConfig) ? currentConfig : {};
78
+ const currentThinking = config.thinkingConfig;
79
+ const thinking = isPlainObject(currentThinking) ? currentThinking : {};
80
+ const valuesChanged =
81
+ !isPlainObject(currentThinking) ||
82
+ GOOGLE_THINKING_FIELDS.some(
83
+ (key) => key in values && !Object.is(thinking[key], values[key]),
84
+ );
85
+ const removeChanged = remove.some((key) => Object.hasOwn(thinking, key));
86
+ if (!valuesChanged && !removeChanged) return;
87
+
88
+ const nextThinking = { ...thinking, ...values };
89
+ for (const key of remove) delete nextThinking[key];
90
+ this.set("config", { ...config, thinkingConfig: nextThinking });
91
+ }
92
+
93
+ setTextVerbosity(verbosity: "low" | "medium"): void {
94
+ const current = this.get("text");
95
+ if (current !== undefined && !isPlainObject(current)) return;
96
+ const text = isPlainObject(current) ? current : {};
97
+ if (text.verbosity === verbosity) return;
98
+ this.set("text", { ...text, verbosity });
99
+ }
100
+
101
+ result(): Payload {
102
+ return this.copy ?? this.payload;
103
+ }
104
+
105
+ private mutable(): Payload {
106
+ this.copy ??= { ...this.payload };
107
+ return this.copy;
108
+ }
109
+ }
110
+
111
+ const THINKING_FIELDS = ["type", "clear_thinking"] as const;
112
+ const GOOGLE_THINKING_FIELDS = [
113
+ "includeThoughts",
114
+ "thinkingLevel",
115
+ "thinkingBudget",
116
+ ] as const;
117
+
118
+ export function isAtLeastHigh(level: ThinkingLevel): boolean {
119
+ return level === "high" || level === "xhigh" || level === "max";
120
+ }
121
+
122
+ export function isMaximum(level: ThinkingLevel): boolean {
123
+ return level === "xhigh" || level === "max";
124
+ }
125
+
126
+ /** 通用开关式 thinking:`off` 禁用,其余启用;移除通用 effort 字段。 */
127
+ export function applyEnabledThinking(
128
+ writer: PayloadWriter,
129
+ level: ThinkingLevel,
130
+ ): void {
131
+ writer.remove("reasoning_effort");
132
+ writer.setThinking({ type: level === "off" ? "disabled" : "enabled" });
133
+ }
134
+
135
+ /** 厂商思维链策略:对指定模型的请求体应用该厂商的 thinking 改写。 */
136
+ export type ThinkingApplier = (
137
+ writer: PayloadWriter,
138
+ context: ModelOperationContext,
139
+ ) => void;
@@ -0,0 +1,137 @@
1
+ import { deepStrictEqual, equal, strictEqual, throws } from "node:assert";
2
+ import {
3
+ DEFAULT_ROOT,
4
+ filterModels,
5
+ modelsForRoot,
6
+ normalizeRoot,
7
+ PROVIDER_ID,
8
+ } from "./catalog.ts";
9
+
10
+ const ROOT = "https://aih.example.com";
11
+
12
+ function testCatalogConcatenation(): void {
13
+ const models = modelsForRoot(ROOT);
14
+ const ids = models.map(({ id }) => id);
15
+
16
+ // 10 家供应商分片拼接,共 59 个模型(22 原有 + 37 新增)。
17
+ equal(ids.length, 59);
18
+ // id 全局唯一。
19
+ equal(new Set(ids).size, ids.length);
20
+
21
+ // 供应商覆盖:每家至少一个模型。
22
+ for (const prefix of [
23
+ "deepseek-",
24
+ "glm-",
25
+ "mimo-",
26
+ "minimax-",
27
+ "kimi-",
28
+ "longcat-",
29
+ "qwen",
30
+ "gpt-",
31
+ "gemini-",
32
+ "claude-",
33
+ ]) {
34
+ equal(
35
+ ids.some((id) => id.startsWith(prefix)),
36
+ true,
37
+ `expected a model with prefix ${prefix}`,
38
+ );
39
+ }
40
+
41
+ // 拼接顺序保持目录顺序(deepseek → … → claude)。
42
+ equal(ids[0], "deepseek-v4-flash");
43
+ equal(ids[ids.length - 1], "claude-sonnet-5");
44
+
45
+ // 模型 baseUrl 按协议端点派生。
46
+ const deepseek = models.find(({ id }) => id === "deepseek-v4-flash");
47
+ strictEqual(deepseek?.baseUrl, `${ROOT}/v1`);
48
+ const gemini = models.find(({ id }) => id === "gemini-flash");
49
+ strictEqual(gemini?.baseUrl, `${ROOT}/gemini`);
50
+ const claude = models.find(({ id }) => id === "claude-fable-5");
51
+ strictEqual(claude?.baseUrl, `${ROOT}/anthropic`);
52
+ }
53
+
54
+ function testFilterModels(): void {
55
+ const all = modelsForRoot(ROOT);
56
+
57
+ // 无过滤条件:原样返回(新数组,元素不变)。
58
+ const untouched = filterModels(all);
59
+ equal(untouched.length, all.length);
60
+ strictEqual(untouched[0], all[0]);
61
+
62
+ // 白名单精确匹配。
63
+ deepStrictEqual(
64
+ filterModels(all, { include: ["glm-5.2"] }).map(({ id }) => id),
65
+ ["glm-5.2"],
66
+ );
67
+
68
+ // 白名单前缀通配。
69
+ deepStrictEqual(
70
+ filterModels(all, { include: ["gpt-5.6-*"] }).map(({ id }) => id),
71
+ ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"],
72
+ );
73
+ // 黑名单精确匹配。
74
+ const excluded = filterModels(all, { exclude: ["claude-sonnet"] });
75
+ equal(
76
+ excluded.some(({ id }) => id === "claude-sonnet"),
77
+ false,
78
+ );
79
+ equal(excluded.length, all.length - 1);
80
+
81
+ // 黑名单前缀通配。
82
+ const noGemini = filterModels(all, { exclude: ["gemini-*"] });
83
+ equal(
84
+ noGemini.some(({ id }) => id.startsWith("gemini-")),
85
+ false,
86
+ );
87
+
88
+ // 黑白名单并存:黑名单优先于白名单。
89
+ const both = filterModels(all, {
90
+ include: ["glm-*", "claude-*"],
91
+ exclude: ["glm-5.1", "claude-sonnet"],
92
+ });
93
+ equal(
94
+ both.some(({ id }) => id.startsWith("glm-")),
95
+ true,
96
+ );
97
+ equal(
98
+ both.some(({ id }) => id.startsWith("claude-")),
99
+ true,
100
+ );
101
+ equal(
102
+ both.some(({ id }) => id === "glm-5.1"),
103
+ false,
104
+ );
105
+ equal(
106
+ both.some(({ id }) => id === "claude-sonnet"),
107
+ false,
108
+ );
109
+ }
110
+
111
+ function testNormalizeRoot(): void {
112
+ strictEqual(normalizeRoot(), DEFAULT_ROOT);
113
+ strictEqual(
114
+ normalizeRoot("https://gw.example.com/v1"),
115
+ "https://gw.example.com",
116
+ );
117
+ strictEqual(
118
+ normalizeRoot("https://gw.example.com/v1/"),
119
+ "https://gw.example.com",
120
+ );
121
+ strictEqual(
122
+ normalizeRoot("https://gw.example.com/"),
123
+ "https://gw.example.com",
124
+ );
125
+ strictEqual(
126
+ normalizeRoot("https://gw.example.com/base/v1"),
127
+ "https://gw.example.com/base",
128
+ );
129
+ throws(() => normalizeRoot("ftp://gw.example.com"), /http or https/);
130
+ throws(() => normalizeRoot("not-a-url"), /not a valid URL/);
131
+ equal(PROVIDER_ID, "tsgw");
132
+ }
133
+
134
+ testCatalogConcatenation();
135
+ testFilterModels();
136
+ testNormalizeRoot();
137
+ console.log("catalog.test.ts: all assertions passed");
@@ -0,0 +1,100 @@
1
+ import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
2
+ import { anthropicModels } from "./vendors/anthropic.ts";
3
+ import { deepseekModels } from "./vendors/deepseek.ts";
4
+ import { geminiModels } from "./vendors/gemini.ts";
5
+ import { glmModels } from "./vendors/glm.ts";
6
+ import { kimiModels } from "./vendors/kimi.ts";
7
+ import { longcatModels } from "./vendors/longcat.ts";
8
+ import { mimoModels } from "./vendors/mimo.ts";
9
+ import { minimaxModels } from "./vendors/minimax.ts";
10
+ import { openaiModels } from "./vendors/openai.ts";
11
+ import { qwenModels } from "./vendors/qwen.ts";
12
+
13
+ export const PROVIDER_ID = "tsgw";
14
+
15
+ /**
16
+ * Neutral placeholder root. Point the extension at your gateway through
17
+ * settings.json (`"tsgw": { "baseUrl": ... }`); this default only applies
18
+ * when nothing is configured.
19
+ */
20
+ export const DEFAULT_ROOT = "https://aih.example.com";
21
+
22
+ /** Normalize a gateway root, including the common accidental `/v1` suffix. */
23
+ export function normalizeRoot(value = DEFAULT_ROOT): string {
24
+ let url: URL;
25
+ try {
26
+ url = new URL(value);
27
+ } catch {
28
+ throw new Error(`TSGW baseUrl is not a valid URL: ${value}`);
29
+ }
30
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
31
+ throw new Error("TSGW baseUrl must use http or https");
32
+ }
33
+ url.hash = "";
34
+ url.search = "";
35
+ url.pathname = url.pathname.replace(/\/+$/, "");
36
+ if (url.pathname === "/v1") url.pathname = "";
37
+ else if (url.pathname.endsWith("/v1"))
38
+ url.pathname = url.pathname.slice(0, -3);
39
+ url.pathname = url.pathname.replace(/\/+$/, "");
40
+ return url.toString().replace(/\/$/, "");
41
+ }
42
+
43
+ /** 模型黑白名单。`include` 只保留匹配的模型;`exclude` 始终生效(黑名单优先)。 */
44
+ export interface ModelFilter {
45
+ include?: readonly string[];
46
+ exclude?: readonly string[];
47
+ }
48
+
49
+ /** 前缀通配匹配:`gpt-5.6-*` 命中该系列全部;不带 `*` 时精确匹配。 */
50
+ function matches(pattern: string, id: string): boolean {
51
+ if (pattern.endsWith("*")) return id.startsWith(pattern.slice(0, -1));
52
+ return pattern === id;
53
+ }
54
+
55
+ function compilePatterns(patterns: readonly string[]): (id: string) => boolean {
56
+ return (id) => patterns.some((pattern) => matches(pattern, id));
57
+ }
58
+
59
+ /** 按黑白名单过滤模型目录;无过滤条件时原样返回。 */
60
+ export function filterModels(
61
+ models: readonly ProviderModelConfig[],
62
+ filter?: ModelFilter,
63
+ ): ProviderModelConfig[] {
64
+ if (!filter) return [...models];
65
+ const include = filter.include?.length
66
+ ? compilePatterns(filter.include)
67
+ : undefined;
68
+ const exclude = filter.exclude?.length
69
+ ? compilePatterns(filter.exclude)
70
+ : undefined;
71
+ return models.filter(
72
+ (model) =>
73
+ (!include || include(model.id)) && (!exclude || !exclude(model.id)),
74
+ );
75
+ }
76
+
77
+ /**
78
+ * The authoritative TSGW catalog: vendor slices concatenated in a fixed
79
+ * order, then filtered by the configured blacklist/whitelist.
80
+ *
81
+ * 新增模型 → 改对应 vendors 文件;新增供应商 → 这里加一行 import + spread。
82
+ */
83
+ export function modelsForRoot(
84
+ root: string,
85
+ filter?: ModelFilter,
86
+ ): ProviderModelConfig[] {
87
+ const models = [
88
+ ...deepseekModels(root),
89
+ ...glmModels(root),
90
+ ...mimoModels(root),
91
+ ...minimaxModels(root),
92
+ ...kimiModels(root),
93
+ ...longcatModels(root),
94
+ ...qwenModels(root),
95
+ ...openaiModels(root),
96
+ ...geminiModels(root),
97
+ ...anthropicModels(root),
98
+ ];
99
+ return filterModels(models, filter);
100
+ }