@soiljs/models 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +184 -2
- package/dist/anthropic/index.d.ts +16 -0
- package/dist/anthropic/index.js +4 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/chunk-4ONHQ7MX.js +10 -0
- package/dist/chunk-4ONHQ7MX.js.map +1 -0
- package/dist/chunk-5BTK5EOO.js +8 -0
- package/dist/chunk-5BTK5EOO.js.map +1 -0
- package/dist/chunk-EFJFQCXF.js +1828 -0
- package/dist/chunk-EFJFQCXF.js.map +1 -0
- package/dist/chunk-IBG2ZBNY.js +12 -0
- package/dist/chunk-IBG2ZBNY.js.map +1 -0
- package/dist/chunk-LB4ZT5HL.js +10 -0
- package/dist/chunk-LB4ZT5HL.js.map +1 -0
- package/dist/chunk-OVT5IQM2.js +37 -0
- package/dist/chunk-OVT5IQM2.js.map +1 -0
- package/dist/chunk-P42EM5RH.js +9 -0
- package/dist/chunk-P42EM5RH.js.map +1 -0
- package/dist/chunk-Q63QXXJS.js +9 -0
- package/dist/chunk-Q63QXXJS.js.map +1 -0
- package/dist/chunk-RTZJ6MXU.js +14 -0
- package/dist/chunk-RTZJ6MXU.js.map +1 -0
- package/dist/chunk-XNDA5XM4.js +10 -0
- package/dist/chunk-XNDA5XM4.js.map +1 -0
- package/dist/contracts-B5BERDgM.d.ts +180 -0
- package/dist/deepseek/index.d.ts +28 -0
- package/dist/deepseek/index.js +4 -0
- package/dist/deepseek/index.js.map +1 -0
- package/dist/gemini/index.d.ts +11 -0
- package/dist/gemini/index.js +4 -0
- package/dist/gemini/index.js.map +1 -0
- package/dist/glm/index.d.ts +30 -0
- package/dist/glm/index.js +4 -0
- package/dist/glm/index.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/kimi/index.d.ts +10 -0
- package/dist/kimi/index.js +4 -0
- package/dist/kimi/index.js.map +1 -0
- package/dist/openai/index.d.ts +20 -0
- package/dist/openai/index.js +4 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/openai-compatible/index.d.ts +21 -0
- package/dist/openai-compatible/index.js +4 -0
- package/dist/openai-compatible/index.js.map +1 -0
- package/dist/openrouter/index.d.ts +24 -0
- package/dist/openrouter/index.js +4 -0
- package/dist/openrouter/index.js.map +1 -0
- package/dist/recording/index.d.ts +20 -0
- package/dist/recording/index.js +260 -0
- package/dist/recording/index.js.map +1 -0
- package/package.json +70 -3
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { getProtocol } from '../chunk-OVT5IQM2.js';
|
|
2
|
+
import '../chunk-RTZJ6MXU.js';
|
|
3
|
+
import '../chunk-XNDA5XM4.js';
|
|
4
|
+
import '../chunk-IBG2ZBNY.js';
|
|
5
|
+
import '../chunk-LB4ZT5HL.js';
|
|
6
|
+
import '../chunk-Q63QXXJS.js';
|
|
7
|
+
import '../chunk-5BTK5EOO.js';
|
|
8
|
+
import '../chunk-P42EM5RH.js';
|
|
9
|
+
import '../chunk-4ONHQ7MX.js';
|
|
10
|
+
import { emptyUsage, object, canonical, abortError, ModelError } from '../chunk-EFJFQCXF.js';
|
|
11
|
+
import { readFile, mkdir, writeFile, rename, rm } from 'fs/promises';
|
|
12
|
+
import { dirname } from 'path';
|
|
13
|
+
|
|
14
|
+
function fixtureError(message) {
|
|
15
|
+
return new ModelError({ code: "fixture_error", message });
|
|
16
|
+
}
|
|
17
|
+
function checkSignal(input) {
|
|
18
|
+
if (input.signal?.aborted) throw abortError(input.signal, false);
|
|
19
|
+
}
|
|
20
|
+
function requestKey(model, input) {
|
|
21
|
+
return canonical({
|
|
22
|
+
body: model.encode(input).body,
|
|
23
|
+
continuations: input.messages.map((message) => message.continuation ?? null)
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function validResponse(value) {
|
|
27
|
+
const r = object(value), u = object(r.usage);
|
|
28
|
+
const counts = ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens"].map(
|
|
29
|
+
(key) => u[key]
|
|
30
|
+
);
|
|
31
|
+
const completeness = counts.every((n) => n !== null) ? "complete" : counts.some((n) => n !== null) ? "partial" : "unknown";
|
|
32
|
+
return typeof r.protocolId === "string" && typeof r.model === "string" && typeof r.text === "string" && typeof r.reasoningText === "string" && Array.isArray(r.toolCalls) && r.toolCalls.every((item) => {
|
|
33
|
+
const c = object(item);
|
|
34
|
+
return typeof c.id === "string" && typeof c.name === "string" && "input" in c;
|
|
35
|
+
}) && counts.every((n) => n === null || typeof n === "number" && Number.isFinite(n) && n >= 0) && u.completeness === completeness && ["stop", "length", "tool_calls", "content_filter", "unknown"].includes(String(r.finishReason));
|
|
36
|
+
}
|
|
37
|
+
function validEvents(value) {
|
|
38
|
+
if (!Array.isArray(value) || object(value.at(-1)).type !== "response.completed") return false;
|
|
39
|
+
return value.every((item, index) => {
|
|
40
|
+
const event = object(item);
|
|
41
|
+
switch (event.type) {
|
|
42
|
+
case "text.delta":
|
|
43
|
+
case "reasoning.delta":
|
|
44
|
+
return typeof event.delta === "string";
|
|
45
|
+
case "tool_call.start":
|
|
46
|
+
return typeof event.id === "string" && typeof event.name === "string";
|
|
47
|
+
case "tool_call.delta":
|
|
48
|
+
return typeof event.id === "string" && typeof event.delta === "string";
|
|
49
|
+
case "tool_call.done": {
|
|
50
|
+
const call = object(event.toolCall);
|
|
51
|
+
return typeof call.id === "string" && typeof call.name === "string" && "input" in call;
|
|
52
|
+
}
|
|
53
|
+
case "response.completed":
|
|
54
|
+
return index === value.length - 1 && validResponse(event.response);
|
|
55
|
+
default:
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async function save(path, fixture) {
|
|
61
|
+
await mkdir(dirname(path), { recursive: true });
|
|
62
|
+
const temporary = path + "." + globalThis.crypto.randomUUID() + ".tmp";
|
|
63
|
+
try {
|
|
64
|
+
await writeFile(temporary, JSON.stringify(fixture, null, 2) + "\n", { mode: 384 });
|
|
65
|
+
await rename(temporary, path);
|
|
66
|
+
} finally {
|
|
67
|
+
await rm(temporary, { force: true });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function withRecording(model, options) {
|
|
71
|
+
if (options.mode === "passthrough") return model;
|
|
72
|
+
let loaded, cursor = 0, writes = Promise.resolve();
|
|
73
|
+
const recorded = [];
|
|
74
|
+
const keyFor = (input) => {
|
|
75
|
+
try {
|
|
76
|
+
return requestKey(model, input);
|
|
77
|
+
} catch (cause) {
|
|
78
|
+
if (options.mode === "replay")
|
|
79
|
+
throw fixtureError("Invalid recording request or missing continuation");
|
|
80
|
+
throw cause;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const validateResult = (result) => {
|
|
84
|
+
if (!validResponse(result) || result.protocolId !== model.protocolId || result.model !== model.model)
|
|
85
|
+
throw fixtureError("Recorded result protocol/model mismatch or invalid result");
|
|
86
|
+
if (result.continuation) {
|
|
87
|
+
if (result.continuation.protocolId !== model.protocolId || result.continuation.model !== model.model)
|
|
88
|
+
throw fixtureError("Recorded continuation identity mismatch");
|
|
89
|
+
if (result.toolCalls.length) {
|
|
90
|
+
try {
|
|
91
|
+
model.replay(result.continuation);
|
|
92
|
+
} catch {
|
|
93
|
+
throw fixtureError("Incomplete recorded tool continuation");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
} else if (result.toolCalls.length) throw fixtureError("Missing recorded tool continuation");
|
|
97
|
+
};
|
|
98
|
+
const next = async (kind, input) => {
|
|
99
|
+
checkSignal(input);
|
|
100
|
+
const request = keyFor(input);
|
|
101
|
+
loaded ??= readFile(options.fixturePath, "utf8").then((text) => {
|
|
102
|
+
const value = object(JSON.parse(text));
|
|
103
|
+
if (value.version !== 2 || !Array.isArray(value.entries))
|
|
104
|
+
throw fixtureError("Unsupported recording fixture");
|
|
105
|
+
return value;
|
|
106
|
+
}).catch(() => {
|
|
107
|
+
throw fixtureError("Unable to read a valid recording fixture");
|
|
108
|
+
});
|
|
109
|
+
const fixture = await loaded;
|
|
110
|
+
checkSignal(input);
|
|
111
|
+
const entry = fixture.entries[cursor];
|
|
112
|
+
if (!entry || entry.kind !== kind || entry.protocolId !== model.protocolId || entry.model !== model.model || entry.request !== request)
|
|
113
|
+
throw fixtureError("Recording protocol/model/request/order mismatch or exhausted fixture");
|
|
114
|
+
const result = entry.kind === "generate" ? entry.response : validEvents(entry.events) ? entry.events.at(-1).response : void 0;
|
|
115
|
+
if (!result) throw fixtureError("Invalid or incomplete recorded stream");
|
|
116
|
+
validateResult(result);
|
|
117
|
+
if (typeof entry.hasContinuation !== "boolean" || entry.hasContinuation !== (result.continuation !== void 0) || canonical(entry.continuation) !== canonical(result.continuation ?? null))
|
|
118
|
+
throw fixtureError("Recording lost or changed continuation");
|
|
119
|
+
cursor++;
|
|
120
|
+
return structuredClone(entry);
|
|
121
|
+
};
|
|
122
|
+
const commit = async (index, entry) => {
|
|
123
|
+
recorded[index] = structuredClone(entry);
|
|
124
|
+
const snapshot = recorded.slice();
|
|
125
|
+
if (snapshot.some((item) => item === void 0)) return;
|
|
126
|
+
const entries = snapshot.filter((item) => item != null);
|
|
127
|
+
if (!entries.length) return;
|
|
128
|
+
writes = writes.then(() => save(options.fixturePath, { version: 2, entries }));
|
|
129
|
+
await writes;
|
|
130
|
+
};
|
|
131
|
+
const identity = (request, result) => ({
|
|
132
|
+
protocolId: model.protocolId,
|
|
133
|
+
model: model.model,
|
|
134
|
+
request,
|
|
135
|
+
continuation: result.continuation ?? null,
|
|
136
|
+
hasContinuation: result.continuation !== void 0
|
|
137
|
+
});
|
|
138
|
+
return Object.freeze({
|
|
139
|
+
protocolId: model.protocolId,
|
|
140
|
+
model: model.model,
|
|
141
|
+
baseUrl: model.baseUrl,
|
|
142
|
+
meta: model.meta,
|
|
143
|
+
encode: (input) => model.encode(input),
|
|
144
|
+
replay: (saved) => model.replay(saved),
|
|
145
|
+
async generate(input) {
|
|
146
|
+
checkSignal(input);
|
|
147
|
+
if (options.mode === "replay") {
|
|
148
|
+
const entry = await next("generate", input);
|
|
149
|
+
if (entry.kind !== "generate") throw fixtureError("Unexpected fixture kind");
|
|
150
|
+
return entry.response;
|
|
151
|
+
}
|
|
152
|
+
const request = keyFor(input), index = recorded.length;
|
|
153
|
+
recorded.push(void 0);
|
|
154
|
+
try {
|
|
155
|
+
const response = await model.generate(input);
|
|
156
|
+
validateResult(response);
|
|
157
|
+
await commit(index, { ...identity(request, response), kind: "generate", response });
|
|
158
|
+
return response;
|
|
159
|
+
} catch (cause) {
|
|
160
|
+
await commit(index, null);
|
|
161
|
+
throw cause;
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
async *stream(input) {
|
|
165
|
+
checkSignal(input);
|
|
166
|
+
if (options.mode === "replay") {
|
|
167
|
+
const entry = await next("stream", input);
|
|
168
|
+
if (entry.kind !== "stream") throw fixtureError("Unexpected fixture kind");
|
|
169
|
+
for (const event of entry.events) {
|
|
170
|
+
checkSignal(input);
|
|
171
|
+
yield event;
|
|
172
|
+
}
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const request = keyFor(input), index = recorded.length;
|
|
176
|
+
recorded.push(void 0);
|
|
177
|
+
const events = [];
|
|
178
|
+
let committed = false;
|
|
179
|
+
try {
|
|
180
|
+
for await (const event of model.stream(input)) {
|
|
181
|
+
events.push(structuredClone(event));
|
|
182
|
+
yield event;
|
|
183
|
+
}
|
|
184
|
+
if (!validEvents(events)) throw fixtureError("Cannot record an incomplete model stream");
|
|
185
|
+
const response = events.at(-1).response;
|
|
186
|
+
validateResult(response);
|
|
187
|
+
await commit(index, { ...identity(request, response), kind: "stream", events });
|
|
188
|
+
committed = true;
|
|
189
|
+
} finally {
|
|
190
|
+
if (!committed) await commit(index, null);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
function* eventsFor(response) {
|
|
196
|
+
if (response.reasoningText) yield { type: "reasoning.delta", delta: response.reasoningText };
|
|
197
|
+
if (response.text) yield { type: "text.delta", delta: response.text };
|
|
198
|
+
for (const toolCall of response.toolCalls) {
|
|
199
|
+
yield { type: "tool_call.start", id: toolCall.id, name: toolCall.name };
|
|
200
|
+
yield { type: "tool_call.delta", id: toolCall.id, delta: JSON.stringify(toolCall.input) };
|
|
201
|
+
yield { type: "tool_call.done", toolCall };
|
|
202
|
+
}
|
|
203
|
+
yield { type: "response.completed", response };
|
|
204
|
+
}
|
|
205
|
+
function createFixtureModel(options = {}) {
|
|
206
|
+
const config = Array.isArray(options) ? { responses: options } : options;
|
|
207
|
+
const protocolId = config.protocolId ?? "openai/chat", model = config.model ?? "fixture", protocol = getProtocol(protocolId);
|
|
208
|
+
const scripts = structuredClone(config.responses ?? config.scriptedResponses ?? []);
|
|
209
|
+
let cursor = 0;
|
|
210
|
+
const next = (input) => {
|
|
211
|
+
checkSignal(input);
|
|
212
|
+
const script = scripts[cursor++];
|
|
213
|
+
if (script === void 0) throw fixtureError("Fixture model exhausted");
|
|
214
|
+
const response = {
|
|
215
|
+
protocolId,
|
|
216
|
+
model,
|
|
217
|
+
text: "",
|
|
218
|
+
reasoningText: "",
|
|
219
|
+
toolCalls: [],
|
|
220
|
+
usage: emptyUsage(),
|
|
221
|
+
finishReason: "stop",
|
|
222
|
+
rawResponse: null,
|
|
223
|
+
...typeof script === "string" ? { text: script } : script
|
|
224
|
+
};
|
|
225
|
+
const events = Array.isArray(script) ? script : [...eventsFor(response)];
|
|
226
|
+
if (!validEvents(events)) throw fixtureError("Fixture requires exactly one final completion");
|
|
227
|
+
return structuredClone(events);
|
|
228
|
+
};
|
|
229
|
+
return Object.freeze({
|
|
230
|
+
protocolId,
|
|
231
|
+
model,
|
|
232
|
+
baseUrl: config.baseUrl ?? protocol.meta.defaultBaseUrl,
|
|
233
|
+
meta: protocol.meta,
|
|
234
|
+
encode(input) {
|
|
235
|
+
const { signal: _signal, ...body } = input;
|
|
236
|
+
return {
|
|
237
|
+
url: config.baseUrl ?? protocol.meta.defaultBaseUrl,
|
|
238
|
+
method: "POST",
|
|
239
|
+
headers: {},
|
|
240
|
+
body: { model, ...structuredClone(body) }
|
|
241
|
+
};
|
|
242
|
+
},
|
|
243
|
+
replay: (saved) => protocol.replay(saved, model),
|
|
244
|
+
async generate(input) {
|
|
245
|
+
const event = next(input).at(-1);
|
|
246
|
+
if (event?.type !== "response.completed") throw fixtureError("Missing fixture response");
|
|
247
|
+
return event.response;
|
|
248
|
+
},
|
|
249
|
+
async *stream(input) {
|
|
250
|
+
for (const event of next(input)) {
|
|
251
|
+
checkSignal(input);
|
|
252
|
+
yield event;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export { createFixtureModel, withRecording };
|
|
259
|
+
//# sourceMappingURL=index.js.map
|
|
260
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/recording/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AA+BA,SAAS,aAAa,OAAA,EAA6B;AACjD,EAAA,OAAO,IAAI,UAAA,CAAW,EAAE,IAAA,EAAM,eAAA,EAAiB,SAAS,CAAA;AAC1D;AACA,SAAS,YAAY,KAAA,EAA6B;AAChD,EAAA,IAAI,MAAM,MAAA,EAAQ,OAAA,QAAe,UAAA,CAAW,KAAA,CAAM,QAAQ,KAAK,CAAA;AACjE;AACA,SAAS,UAAA,CAAW,OAAmB,KAAA,EAA+B;AACpE,EAAA,OAAO,SAAA,CAAU;AAAA,IACf,IAAA,EAAM,KAAA,CAAM,MAAA,CAAO,KAAK,CAAA,CAAE,IAAA;AAAA,IAC1B,aAAA,EAAe,MAAM,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY,OAAA,CAAQ,gBAAgB,IAAI;AAAA,GAC5E,CAAA;AACH;AACA,SAAS,cAAc,KAAA,EAAsC;AAC3D,E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AA,CAAK,cAAA;AAAA,IACzC,MAAM,QAAA,CAAS,IAAA;AAAA,IACf,OAAO,KAAA,EAAuB;AAC5B,MAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,GAAG,MAAK,GAAI,KAAA;AACrC,MAAA,OAAO;AAAA,QACL,GAAA,EAAK,MAAA,CAAO,OAAA,IAAW,QAAA,CAAS,IAAA,CAAK,cAAA;AAAA,QACrC,MAAA,EAAQ,MAAA;AAAA,QACR,SAAS,EAAC;AAAA,QACV,MAAM,EAAE,KAAA,EAAO,GAAG,eAAA,CAAgB,IAAI,CAAA;AAAE,OAC1C;AAAA,IACF,CAAA;AAAA,IACA,QAAQ,CAAC,KAAA,KAA6B,QAAA,CAAS,MAAA,CAAO,OAAO,KAAK,CAAA;AAAA,IAClE,MAAM,SAAS,KAAA,EAAuB;AACpC,MAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAK,CAAA,CAAE,GAAG,EAAE,CAAA;AAC/B,MAAA,IAAI,KAAA,EAAO,IAAA,KAAS,oBAAA,EAAsB,MAAM,aAAa,0BAA0B,CAAA;AACvF,MAAA,OAAO,KAAA,CAAM,QAAA;AAAA,IACf,CAAA;AAAA,IACA,OAAO,OAAO,KAAA,EAAuB;AACnC,MAAA,KAAA,MAAW,KAAA,IAAS,IAAA,CAAK,KAAK,CAAA,EAAG;AAC/B,QAAA,WAAA,CAAY,KAAK,CAAA;AACjB,QAAA,MAAM,KAAA;AAAA,MACR;AAAA,IACF;AAAA,GACD,CAAA;AACH","file":"index.js","sourcesContent":["import { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type {\n BoundCallInput,\n BoundModel,\n JsonValue,\n ModelContinuation,\n ModelResult,\n ModelStreamEvent,\n ProtocolId,\n} from \"../contracts.js\";\nimport { ModelError } from \"../error.js\";\nimport { getProtocol } from \"../registry.js\";\nimport { abortError } from \"../transport/http.js\";\nimport { emptyUsage, object } from \"../transport/shared.js\";\nimport { canonical } from \"../transport/protocol.js\";\nexport interface RecordingOptions {\n fixturePath: string;\n mode: \"record\" | \"replay\" | \"passthrough\";\n}\ntype Entry = {\n protocolId: ProtocolId;\n model: string;\n request: string;\n continuation: ModelContinuation | null;\n hasContinuation: boolean;\n} & ({ kind: \"generate\"; response: ModelResult } | { kind: \"stream\"; events: ModelStreamEvent[] });\ninterface Fixture {\n version: 2;\n entries: Entry[];\n}\nfunction fixtureError(message: string): ModelError {\n return new ModelError({ code: \"fixture_error\", message });\n}\nfunction checkSignal(input: BoundCallInput): void {\n if (input.signal?.aborted) throw abortError(input.signal, false);\n}\nfunction requestKey(model: BoundModel, input: BoundCallInput): string {\n return canonical({\n body: model.encode(input).body,\n continuations: input.messages.map((message) => message.continuation ?? null),\n });\n}\nfunction validResponse(value: unknown): value is ModelResult {\n const r = object(value),\n u = object(r.usage);\n const counts = [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\"].map(\n (key) => u[key],\n );\n const completeness = counts.every((n) => n !== null)\n ? \"complete\"\n : counts.some((n) => n !== null)\n ? \"partial\"\n : \"unknown\";\n return (\n typeof r.protocolId === \"string\" &&\n typeof r.model === \"string\" &&\n typeof r.text === \"string\" &&\n typeof r.reasoningText === \"string\" &&\n Array.isArray(r.toolCalls) &&\n r.toolCalls.every((item: unknown) => {\n const c = object(item);\n return typeof c.id === \"string\" && typeof c.name === \"string\" && \"input\" in c;\n }) &&\n counts.every((n) => n === null || (typeof n === \"number\" && Number.isFinite(n) && n >= 0)) &&\n u.completeness === completeness &&\n [\"stop\", \"length\", \"tool_calls\", \"content_filter\", \"unknown\"].includes(String(r.finishReason))\n );\n}\nfunction validEvents(value: unknown): value is ModelStreamEvent[] {\n if (!Array.isArray(value) || object(value.at(-1)).type !== \"response.completed\") return false;\n return value.every((item: unknown, index) => {\n const event = object(item);\n switch (event.type) {\n case \"text.delta\":\n case \"reasoning.delta\":\n return typeof event.delta === \"string\";\n case \"tool_call.start\":\n return typeof event.id === \"string\" && typeof event.name === \"string\";\n case \"tool_call.delta\":\n return typeof event.id === \"string\" && typeof event.delta === \"string\";\n case \"tool_call.done\": {\n const call = object(event.toolCall);\n return typeof call.id === \"string\" && typeof call.name === \"string\" && \"input\" in call;\n }\n case \"response.completed\":\n return index === value.length - 1 && validResponse(event.response);\n default:\n return false;\n }\n });\n}\nasync function save(path: string, fixture: Fixture): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temporary = path + \".\" + globalThis.crypto.randomUUID() + \".tmp\";\n try {\n await writeFile(temporary, JSON.stringify(fixture, null, 2) + \"\\n\", { mode: 0o600 });\n await rename(temporary, path);\n } finally {\n await rm(temporary, { force: true });\n }\n}\n/** Ordered offline fixtures, never a runtime ledger. Replay never invokes generate/stream. */\nexport function withRecording(model: BoundModel, options: RecordingOptions): BoundModel {\n if (options.mode === \"passthrough\") return model;\n let loaded: Promise<Fixture> | undefined,\n cursor = 0,\n writes = Promise.resolve();\n const recorded: (Entry | null | undefined)[] = [];\n const keyFor = (input: BoundCallInput): string => {\n try {\n return requestKey(model, input);\n } catch (cause) {\n if (options.mode === \"replay\")\n throw fixtureError(\"Invalid recording request or missing continuation\");\n throw cause;\n }\n };\n const validateResult = (result: ModelResult): void => {\n if (\n !validResponse(result) ||\n result.protocolId !== model.protocolId ||\n result.model !== model.model\n )\n throw fixtureError(\"Recorded result protocol/model mismatch or invalid result\");\n if (result.continuation) {\n if (\n result.continuation.protocolId !== model.protocolId ||\n result.continuation.model !== model.model\n )\n throw fixtureError(\"Recorded continuation identity mismatch\");\n // Completed text can legitimately lack encrypted replay state; tool chains cannot.\n if (result.toolCalls.length) {\n try {\n model.replay(result.continuation);\n } catch {\n throw fixtureError(\"Incomplete recorded tool continuation\");\n }\n }\n } else if (result.toolCalls.length) throw fixtureError(\"Missing recorded tool continuation\");\n };\n const next = async (kind: Entry[\"kind\"], input: BoundCallInput): Promise<Entry> => {\n checkSignal(input);\n const request = keyFor(input);\n loaded ??= readFile(options.fixturePath, \"utf8\")\n .then((text) => {\n const value = object(JSON.parse(text));\n if (value.version !== 2 || !Array.isArray(value.entries))\n throw fixtureError(\"Unsupported recording fixture\");\n return value as unknown as Fixture;\n })\n .catch(() => {\n throw fixtureError(\"Unable to read a valid recording fixture\");\n });\n const fixture = await loaded;\n checkSignal(input);\n const entry = fixture.entries[cursor];\n if (\n !entry ||\n entry.kind !== kind ||\n entry.protocolId !== model.protocolId ||\n entry.model !== model.model ||\n entry.request !== request\n )\n throw fixtureError(\"Recording protocol/model/request/order mismatch or exhausted fixture\");\n const result =\n entry.kind === \"generate\"\n ? entry.response\n : validEvents(entry.events)\n ? (entry.events.at(-1) as { type: \"response.completed\"; response: ModelResult }).response\n : undefined;\n if (!result) throw fixtureError(\"Invalid or incomplete recorded stream\");\n validateResult(result);\n if (\n typeof entry.hasContinuation !== \"boolean\" ||\n entry.hasContinuation !== (result.continuation !== undefined) ||\n canonical(entry.continuation) !== canonical(result.continuation ?? null)\n )\n throw fixtureError(\"Recording lost or changed continuation\");\n cursor++;\n return structuredClone(entry);\n };\n const commit = async (index: number, entry: Entry | null): Promise<void> => {\n recorded[index] = structuredClone(entry);\n const snapshot = recorded.slice();\n if (snapshot.some((item) => item === undefined)) return;\n const entries = snapshot.filter((item): item is Entry => item != null);\n if (!entries.length) return;\n writes = writes.then(() => save(options.fixturePath, { version: 2, entries }));\n await writes;\n };\n const identity = (request: string, result: ModelResult) => ({\n protocolId: model.protocolId,\n model: model.model,\n request,\n continuation: result.continuation ?? null,\n hasContinuation: result.continuation !== undefined,\n });\n return Object.freeze({\n protocolId: model.protocolId,\n model: model.model,\n baseUrl: model.baseUrl,\n meta: model.meta,\n encode: (input: BoundCallInput) => model.encode(input),\n replay: (saved: ModelContinuation) => model.replay(saved),\n async generate(input: BoundCallInput) {\n checkSignal(input);\n if (options.mode === \"replay\") {\n const entry = await next(\"generate\", input);\n if (entry.kind !== \"generate\") throw fixtureError(\"Unexpected fixture kind\");\n return entry.response;\n }\n const request = keyFor(input),\n index = recorded.length;\n recorded.push(undefined);\n try {\n const response = await model.generate(input);\n validateResult(response);\n await commit(index, { ...identity(request, response), kind: \"generate\", response });\n return response;\n } catch (cause) {\n await commit(index, null);\n throw cause;\n }\n },\n async *stream(input: BoundCallInput) {\n checkSignal(input);\n if (options.mode === \"replay\") {\n const entry = await next(\"stream\", input);\n if (entry.kind !== \"stream\") throw fixtureError(\"Unexpected fixture kind\");\n for (const event of entry.events) {\n checkSignal(input);\n yield event;\n }\n return;\n }\n const request = keyFor(input),\n index = recorded.length;\n recorded.push(undefined);\n const events: ModelStreamEvent[] = [];\n let committed = false;\n try {\n for await (const event of model.stream(input)) {\n events.push(structuredClone(event));\n yield event;\n }\n if (!validEvents(events)) throw fixtureError(\"Cannot record an incomplete model stream\");\n const response = (events.at(-1) as { type: \"response.completed\"; response: ModelResult })\n .response;\n validateResult(response);\n await commit(index, { ...identity(request, response), kind: \"stream\", events });\n committed = true;\n } finally {\n if (!committed) await commit(index, null);\n }\n },\n });\n}\nexport type ScriptedResponse = string | Partial<ModelResult> | readonly ModelStreamEvent[];\nexport interface FixtureModelOptions {\n protocolId?: ProtocolId;\n model?: string;\n baseUrl?: string;\n responses?: readonly ScriptedResponse[];\n scriptedResponses?: readonly ScriptedResponse[];\n}\nfunction* eventsFor(response: ModelResult): Generator<ModelStreamEvent> {\n if (response.reasoningText) yield { type: \"reasoning.delta\", delta: response.reasoningText };\n if (response.text) yield { type: \"text.delta\", delta: response.text };\n for (const toolCall of response.toolCalls) {\n yield { type: \"tool_call.start\", id: toolCall.id, name: toolCall.name };\n yield { type: \"tool_call.delta\", id: toolCall.id, delta: JSON.stringify(toolCall.input) };\n yield { type: \"tool_call.done\", toolCall };\n }\n yield { type: \"response.completed\", response };\n}\n/** Each invocation consumes one isolated script, with no network or environment access. */\nexport function createFixtureModel(\n options: FixtureModelOptions | readonly ScriptedResponse[] = {},\n): BoundModel {\n const config: FixtureModelOptions = Array.isArray(options)\n ? { responses: options }\n : (options as FixtureModelOptions);\n const protocolId = config.protocolId ?? \"openai/chat\",\n model = config.model ?? \"fixture\",\n protocol = getProtocol(protocolId);\n const scripts = structuredClone(config.responses ?? config.scriptedResponses ?? []);\n let cursor = 0;\n const next = (input: BoundCallInput): ModelStreamEvent[] => {\n checkSignal(input);\n const script = scripts[cursor++];\n if (script === undefined) throw fixtureError(\"Fixture model exhausted\");\n const response: ModelResult = {\n protocolId,\n model,\n text: \"\",\n reasoningText: \"\",\n toolCalls: [],\n usage: emptyUsage(),\n finishReason: \"stop\",\n rawResponse: null,\n ...(typeof script === \"string\" ? { text: script } : (script as Partial<ModelResult>)),\n };\n const events = Array.isArray(script)\n ? (script as ModelStreamEvent[])\n : [...eventsFor(response)];\n if (!validEvents(events)) throw fixtureError(\"Fixture requires exactly one final completion\");\n return structuredClone(events);\n };\n return Object.freeze({\n protocolId,\n model,\n baseUrl: config.baseUrl ?? protocol.meta.defaultBaseUrl,\n meta: protocol.meta,\n encode(input: BoundCallInput) {\n const { signal: _signal, ...body } = input;\n return {\n url: config.baseUrl ?? protocol.meta.defaultBaseUrl,\n method: \"POST\" as const,\n headers: {},\n body: { model, ...structuredClone(body) } as unknown as { [key: string]: JsonValue },\n };\n },\n replay: (saved: ModelContinuation) => protocol.replay(saved, model),\n async generate(input: BoundCallInput) {\n const event = next(input).at(-1);\n if (event?.type !== \"response.completed\") throw fixtureError(\"Missing fixture response\");\n return event.response;\n },\n async *stream(input: BoundCallInput) {\n for (const event of next(input)) {\n checkSignal(input);\n yield event;\n }\n },\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@soiljs/models",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Independent, zero-dependency model calls, streaming, and offline fixtures.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/ximing/agent-foundation.git",
|
|
9
|
+
"directory": "packages/models"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://ximing.github.io/agent-foundation/",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/ximing/agent-foundation/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=22.19"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./openai": {
|
|
29
|
+
"types": "./dist/openai/index.d.ts",
|
|
30
|
+
"import": "./dist/openai/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./openai-compatible": {
|
|
33
|
+
"types": "./dist/openai-compatible/index.d.ts",
|
|
34
|
+
"import": "./dist/openai-compatible/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./anthropic": {
|
|
37
|
+
"types": "./dist/anthropic/index.d.ts",
|
|
38
|
+
"import": "./dist/anthropic/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./gemini": {
|
|
41
|
+
"types": "./dist/gemini/index.d.ts",
|
|
42
|
+
"import": "./dist/gemini/index.js"
|
|
43
|
+
},
|
|
44
|
+
"./glm": {
|
|
45
|
+
"types": "./dist/glm/index.d.ts",
|
|
46
|
+
"import": "./dist/glm/index.js"
|
|
47
|
+
},
|
|
48
|
+
"./kimi": {
|
|
49
|
+
"types": "./dist/kimi/index.d.ts",
|
|
50
|
+
"import": "./dist/kimi/index.js"
|
|
51
|
+
},
|
|
52
|
+
"./deepseek": {
|
|
53
|
+
"types": "./dist/deepseek/index.d.ts",
|
|
54
|
+
"import": "./dist/deepseek/index.js"
|
|
55
|
+
},
|
|
56
|
+
"./openrouter": {
|
|
57
|
+
"types": "./dist/openrouter/index.d.ts",
|
|
58
|
+
"import": "./dist/openrouter/index.js"
|
|
59
|
+
},
|
|
60
|
+
"./recording": {
|
|
61
|
+
"types": "./dist/recording/index.d.ts",
|
|
62
|
+
"import": "./dist/recording/index.js"
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"publishConfig": {
|
|
66
|
+
"access": "public"
|
|
67
|
+
},
|
|
68
|
+
"dependencies": {},
|
|
69
|
+
"scripts": {
|
|
70
|
+
"build": "../../node_modules/.bin/tsup",
|
|
71
|
+
"typecheck": "../../node_modules/.bin/tsc -p tsconfig.json --noEmit"
|
|
72
|
+
}
|
|
6
73
|
}
|