@openclaw/opencode-provider 0.0.0 → 2026.8.1-beta.3
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/README.md +15 -2
- package/dist/doctor-contract-api.js +170 -0
- package/dist/index.js +742 -0
- package/dist/media-understanding-provider.js +25 -0
- package/dist/onboard.js +20 -0
- package/dist/provider-catalog.js +1218 -0
- package/dist/provider-discovery.js +14 -0
- package/dist/provider-policy-api.js +37 -0
- package/dist/session-catalog-plugin.js +248 -0
- package/dist/session-catalog-shared.js +11 -0
- package/dist/session-catalog.js +294 -0
- package/dist/session-upstream-activity.js +232 -0
- package/dist/stream.js +166 -0
- package/openclaw.plugin.json +685 -0
- package/package.json +43 -8
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { OPENCODE_SESSION_ID_PATTERN } from "./session-catalog-shared.js";
|
|
2
|
+
import { exportOpenCodeSession, queryOpenCodeDatabase } from "./session-catalog.js";
|
|
3
|
+
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
4
|
+
import { isExternalUserText, normalizeUserText } from "openclaw/plugin-sdk/session-catalog";
|
|
5
|
+
//#region extensions/opencode/session-upstream-activity.ts
|
|
6
|
+
const OPENCODE_EXPORT_CONCURRENCY = 4;
|
|
7
|
+
const OPENCODE_REPLAY_LOOKBACK_USER_MESSAGES = 50;
|
|
8
|
+
const OPENCODE_SHELL_SENTINEL = "The following tool was executed by the user";
|
|
9
|
+
async function mapConcurrent(values, limit, mapper) {
|
|
10
|
+
const results = [];
|
|
11
|
+
results.length = values.length;
|
|
12
|
+
let nextIndex = 0;
|
|
13
|
+
const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
|
|
14
|
+
while (nextIndex < values.length) {
|
|
15
|
+
const index = nextIndex++;
|
|
16
|
+
results[index] = await mapper(values[index]);
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
await Promise.all(workers);
|
|
20
|
+
return results;
|
|
21
|
+
}
|
|
22
|
+
function sqlString(value) {
|
|
23
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
24
|
+
}
|
|
25
|
+
function readProbeThreadId(probe) {
|
|
26
|
+
if (probe.hostId !== "gateway" || probe.upstreamKind !== "opencode-cli" || !isRecord(probe.upstreamRef) || probe.upstreamRef.threadId !== probe.threadId || !OPENCODE_SESSION_ID_PATTERN.test(probe.threadId)) return;
|
|
27
|
+
return probe.threadId;
|
|
28
|
+
}
|
|
29
|
+
function readMarker(probe) {
|
|
30
|
+
if (!isRecord(probe.marker)) return;
|
|
31
|
+
return Number.isSafeInteger(probe.marker.seq) && Number(probe.marker.seq) >= 0 && (probe.marker.lastHumanMessageId === null || typeof probe.marker.lastHumanMessageId === "string") ? {
|
|
32
|
+
seq: Number(probe.marker.seq),
|
|
33
|
+
lastHumanMessageId: probe.marker.lastHumanMessageId
|
|
34
|
+
} : void 0;
|
|
35
|
+
}
|
|
36
|
+
async function readIndicators(threadIds) {
|
|
37
|
+
if (threadIds.length === 0) return /* @__PURE__ */ new Map();
|
|
38
|
+
const value = await queryOpenCodeDatabase([
|
|
39
|
+
"SELECT s.id AS id, es.seq AS seq",
|
|
40
|
+
"FROM session AS s",
|
|
41
|
+
"LEFT JOIN event_sequence AS es ON es.aggregate_id = s.id",
|
|
42
|
+
`WHERE s.id IN (${threadIds.map(sqlString).join(", ")})`
|
|
43
|
+
].join(" "));
|
|
44
|
+
if (!Array.isArray(value)) throw new Error("OpenCode returned invalid upstream indicators");
|
|
45
|
+
const indicators = /* @__PURE__ */ new Map();
|
|
46
|
+
for (const row of value) {
|
|
47
|
+
const seq = isRecord(row) && row.seq === null ? 0 : isRecord(row) ? row.seq : void 0;
|
|
48
|
+
if (!isRecord(row) || typeof row.id !== "string" || !OPENCODE_SESSION_ID_PATTERN.test(row.id) || !Number.isSafeInteger(seq) || Number(seq) < 0) throw new Error("OpenCode returned invalid upstream indicators");
|
|
49
|
+
indicators.set(row.id, {
|
|
50
|
+
threadId: row.id,
|
|
51
|
+
seq: Number(seq)
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return indicators;
|
|
55
|
+
}
|
|
56
|
+
function readExportPart(value) {
|
|
57
|
+
if (!isRecord(value) || typeof value.type !== "string") return;
|
|
58
|
+
const sourceText = isRecord(value.source) && isRecord(value.source.text) && typeof value.source.text.value === "string" && typeof value.source.text.start === "number" && Number.isFinite(value.source.text.start) && typeof value.source.text.end === "number" && Number.isFinite(value.source.text.end) ? {
|
|
59
|
+
value: value.source.text.value,
|
|
60
|
+
start: value.source.text.start,
|
|
61
|
+
end: value.source.text.end
|
|
62
|
+
} : void 0;
|
|
63
|
+
return {
|
|
64
|
+
type: value.type,
|
|
65
|
+
...typeof value.text === "string" ? { text: value.text } : {},
|
|
66
|
+
...typeof value.synthetic === "boolean" ? { synthetic: value.synthetic } : {},
|
|
67
|
+
...typeof value.ignored === "boolean" ? { ignored: value.ignored } : {},
|
|
68
|
+
...isRecord(value.metadata) ? { metadata: value.metadata } : {},
|
|
69
|
+
...typeof value.mime === "string" ? { mime: value.mime } : {},
|
|
70
|
+
...typeof value.filename === "string" ? { filename: value.filename } : {},
|
|
71
|
+
...sourceText ? { sourceText } : {}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function visibleTextPart(part, sourceRanges) {
|
|
75
|
+
if (part.type !== "text" || part.text === void 0 || part.synthetic === true || part.ignored === true || part.metadata?.compaction_continue === true) return;
|
|
76
|
+
let text = part.text;
|
|
77
|
+
for (const source of sourceRanges) if (Number.isInteger(source.start) && Number.isInteger(source.end) && source.start >= 0 && source.end >= source.start && source.end <= text.length && text.slice(source.start, source.end) === source.value) text = text.slice(0, source.start) + text.slice(source.end);
|
|
78
|
+
return text;
|
|
79
|
+
}
|
|
80
|
+
function messageSourceRanges(message) {
|
|
81
|
+
return message.parts.flatMap((part) => part.sourceText ? [part.sourceText] : []).toSorted((left, right) => right.start - left.start);
|
|
82
|
+
}
|
|
83
|
+
function visibleTextParts(message) {
|
|
84
|
+
const sourceRanges = messageSourceRanges(message);
|
|
85
|
+
return message.parts.flatMap((part) => {
|
|
86
|
+
const text = visibleTextPart(part, sourceRanges);
|
|
87
|
+
return text === void 0 ? [] : [text];
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function readExportMessages(value) {
|
|
91
|
+
if (!isRecord(value) || !Array.isArray(value.messages)) throw new Error("OpenCode returned an invalid session export");
|
|
92
|
+
return value.messages.flatMap((message) => {
|
|
93
|
+
if (!isRecord(message) || !isRecord(message.info) || !Array.isArray(message.parts)) return [];
|
|
94
|
+
const id = message.info.id;
|
|
95
|
+
const role = message.info.role;
|
|
96
|
+
if (typeof id !== "string" || typeof role !== "string") return [];
|
|
97
|
+
const createdAt = isRecord(message.info.time) && typeof message.info.time.created === "number" && Number.isFinite(message.info.time.created) ? message.info.time.created : void 0;
|
|
98
|
+
return [{
|
|
99
|
+
id,
|
|
100
|
+
role,
|
|
101
|
+
parts: message.parts.flatMap((part) => {
|
|
102
|
+
const parsed = readExportPart(part);
|
|
103
|
+
return parsed ? [parsed] : [];
|
|
104
|
+
}),
|
|
105
|
+
...createdAt === void 0 ? {} : { createdAt }
|
|
106
|
+
}];
|
|
107
|
+
}).toSorted((left, right) => (left.createdAt ?? Number.NEGATIVE_INFINITY) - (right.createdAt ?? Number.NEGATIVE_INFINITY) || left.id.localeCompare(right.id));
|
|
108
|
+
}
|
|
109
|
+
function normalizedMessageText(message) {
|
|
110
|
+
if (message.role !== "user") return;
|
|
111
|
+
const sourceRanges = messageSourceRanges(message);
|
|
112
|
+
const texts = message.parts.flatMap((part) => {
|
|
113
|
+
const visibleText = visibleTextPart(part, sourceRanges);
|
|
114
|
+
if (visibleText !== void 0) return [visibleText];
|
|
115
|
+
if (part.type === "file" && part.mime !== void 0 && (part.mime.startsWith("image/") || part.mime === "application/pdf")) return [`[Attached ${part.mime}: ${part.filename ?? "file"}]`];
|
|
116
|
+
return [];
|
|
117
|
+
});
|
|
118
|
+
return texts.length > 0 ? normalizeUserText(texts.join("\n")) : void 0;
|
|
119
|
+
}
|
|
120
|
+
function directHumanText(message) {
|
|
121
|
+
if (message.role !== "user" || message.parts.some((part) => part.type === "compaction") || message.parts.some((part) => part.metadata?.compaction_continue === true)) return;
|
|
122
|
+
const texts = visibleTextParts(message);
|
|
123
|
+
if (texts.length === 0) return;
|
|
124
|
+
const text = normalizeUserText(texts.join("\n"));
|
|
125
|
+
return !text || text === OPENCODE_SHELL_SENTINEL ? void 0 : text;
|
|
126
|
+
}
|
|
127
|
+
function latestMessageId(current, candidate) {
|
|
128
|
+
return current === null || candidate > current ? candidate : current;
|
|
129
|
+
}
|
|
130
|
+
function latestBaselineHumanMessageId(messages) {
|
|
131
|
+
let latest = null;
|
|
132
|
+
for (const message of messages) if (directHumanText(message) !== void 0) latest = latestMessageId(latest, message.id);
|
|
133
|
+
return latest;
|
|
134
|
+
}
|
|
135
|
+
function classifyExport(params) {
|
|
136
|
+
let humanTurns = 0;
|
|
137
|
+
let occurredAt;
|
|
138
|
+
let lastHumanMessageId = params.marker.lastHumanMessageId;
|
|
139
|
+
let latestExternalMessageId;
|
|
140
|
+
const earlierUserTexts = [];
|
|
141
|
+
for (const message of params.messages) {
|
|
142
|
+
const text = directHumanText(message);
|
|
143
|
+
const replay = text !== void 0 && earlierUserTexts.slice(-50).includes(text);
|
|
144
|
+
const newerThanMarker = params.marker.lastHumanMessageId === null || message.id > params.marker.lastHumanMessageId;
|
|
145
|
+
if (text !== void 0 && message.createdAt !== void 0 && newerThanMarker) lastHumanMessageId = latestMessageId(lastHumanMessageId, message.id);
|
|
146
|
+
if (text !== void 0 && !replay && message.createdAt !== void 0 && newerThanMarker && isExternalUserText(params.probe, text)) {
|
|
147
|
+
humanTurns += 1;
|
|
148
|
+
occurredAt = Math.max(occurredAt ?? 0, message.createdAt);
|
|
149
|
+
latestExternalMessageId = message.id;
|
|
150
|
+
}
|
|
151
|
+
if (message.role === "user") {
|
|
152
|
+
earlierUserTexts.push(normalizedMessageText(message));
|
|
153
|
+
if (earlierUserTexts.length > OPENCODE_REPLAY_LOOKBACK_USER_MESSAGES) earlierUserTexts.shift();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const nextMarker = {
|
|
157
|
+
seq: params.seq,
|
|
158
|
+
lastHumanMessageId
|
|
159
|
+
};
|
|
160
|
+
return {
|
|
161
|
+
kind: "activity",
|
|
162
|
+
sessionKey: params.probe.sessionKey,
|
|
163
|
+
humanTurns,
|
|
164
|
+
nextMarker,
|
|
165
|
+
...humanTurns > 0 ? {
|
|
166
|
+
occurredAt: occurredAt ?? Date.now(),
|
|
167
|
+
dedupeId: latestExternalMessageId ?? String(params.seq)
|
|
168
|
+
} : {}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
async function linkContinuedOpenCodeSession(sessionKey, threadId) {
|
|
172
|
+
try {
|
|
173
|
+
const indicator = (await readIndicators([threadId])).get(threadId);
|
|
174
|
+
if (!indicator) return { sessionKey };
|
|
175
|
+
const messages = readExportMessages(await exportOpenCodeSession(threadId));
|
|
176
|
+
return {
|
|
177
|
+
sessionKey,
|
|
178
|
+
upstream: {
|
|
179
|
+
kind: "opencode-cli",
|
|
180
|
+
ref: { threadId },
|
|
181
|
+
marker: {
|
|
182
|
+
seq: indicator.seq,
|
|
183
|
+
lastHumanMessageId: latestBaselineHumanMessageId(messages)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
} catch {
|
|
188
|
+
return { sessionKey };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async function classifyChangedProbe(probe, indicator) {
|
|
192
|
+
const marker = readMarker(probe);
|
|
193
|
+
if (!marker || indicator.seq === marker.seq) return;
|
|
194
|
+
if (indicator.seq < marker.seq) return {
|
|
195
|
+
kind: "activity",
|
|
196
|
+
sessionKey: probe.sessionKey,
|
|
197
|
+
humanTurns: 0,
|
|
198
|
+
nextMarker: {
|
|
199
|
+
seq: indicator.seq,
|
|
200
|
+
lastHumanMessageId: marker.lastHumanMessageId
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
return classifyExport({
|
|
204
|
+
probe,
|
|
205
|
+
marker,
|
|
206
|
+
seq: indicator.seq,
|
|
207
|
+
messages: readExportMessages(await exportOpenCodeSession(probe.threadId))
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
async function checkOpenCodeUpstreamActivity(probes) {
|
|
211
|
+
const eligible = probes.flatMap((probe) => readProbeThreadId(probe) ? [probe] : []);
|
|
212
|
+
let indicators;
|
|
213
|
+
try {
|
|
214
|
+
indicators = await readIndicators([...new Set(eligible.map((probe) => probe.threadId))]);
|
|
215
|
+
} catch {
|
|
216
|
+
return [];
|
|
217
|
+
}
|
|
218
|
+
return (await mapConcurrent(eligible, OPENCODE_EXPORT_CONCURRENCY, async (probe) => {
|
|
219
|
+
const indicator = indicators.get(probe.threadId);
|
|
220
|
+
if (!indicator) return {
|
|
221
|
+
kind: "missing",
|
|
222
|
+
sessionKey: probe.sessionKey
|
|
223
|
+
};
|
|
224
|
+
try {
|
|
225
|
+
return await classifyChangedProbe(probe, indicator);
|
|
226
|
+
} catch {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
})).filter((outcome) => outcome !== void 0);
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
export { checkOpenCodeUpstreamActivity, linkContinuedOpenCodeSession };
|
package/dist/stream.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
2
|
+
import { streamSimple } from "openclaw/plugin-sdk/llm";
|
|
3
|
+
//#region extensions/opencode/stream.ts
|
|
4
|
+
const WEB_SEARCH = "web_search";
|
|
5
|
+
const WEB_SEARCH_ALIAS = "openclaw_web_search";
|
|
6
|
+
function payloadFunctions(payload) {
|
|
7
|
+
const choice = isRecord(payload.tool_choice) ? payload.tool_choice : void 0;
|
|
8
|
+
return [
|
|
9
|
+
...Array.isArray(payload.tools) ? payload.tools : [],
|
|
10
|
+
...Array.isArray(payload.input) ? payload.input : [],
|
|
11
|
+
...Array.isArray(choice?.tools) ? choice.tools : [],
|
|
12
|
+
choice
|
|
13
|
+
].filter((item) => isRecord(item) && (item.type === "function" || item.type === "function_call") && typeof item.name === "string");
|
|
14
|
+
}
|
|
15
|
+
function rewriteDynamicRecordSchemas(payload) {
|
|
16
|
+
const fieldsByTool = /* @__PURE__ */ new Map();
|
|
17
|
+
for (const tool of payloadFunctions(payload)) {
|
|
18
|
+
if (tool.type !== "function" || !isRecord(tool.parameters)) continue;
|
|
19
|
+
const properties = tool.parameters.properties;
|
|
20
|
+
if (!isRecord(properties)) continue;
|
|
21
|
+
const fields = [];
|
|
22
|
+
for (const [name, schema] of Object.entries(properties)) {
|
|
23
|
+
if (!isRecord(schema)) continue;
|
|
24
|
+
const patterns = schema.patternProperties;
|
|
25
|
+
if (isRecord(schema.properties) && Object.keys(schema.properties).length > 0 || !isRecord(patterns) || Object.keys(patterns).length !== 1 || !Object.hasOwn(patterns, "^.*$")) continue;
|
|
26
|
+
const valueSchema = patterns["^.*$"];
|
|
27
|
+
const jsonValues = !isRecord(valueSchema) || valueSchema.type !== "string";
|
|
28
|
+
const description = typeof schema.description === "string" ? `${schema.description} ` : "";
|
|
29
|
+
properties[name] = {
|
|
30
|
+
...schema,
|
|
31
|
+
type: "array",
|
|
32
|
+
description: `${description}Provide as key/value entries.${jsonValues ? " JSON-encode every value, including strings." : ""}`,
|
|
33
|
+
items: {
|
|
34
|
+
type: "object",
|
|
35
|
+
properties: {
|
|
36
|
+
key: { type: "string" },
|
|
37
|
+
value: jsonValues ? {
|
|
38
|
+
type: "string",
|
|
39
|
+
description: "JSON-encoded value, including JSON encoding for string values."
|
|
40
|
+
} : valueSchema
|
|
41
|
+
},
|
|
42
|
+
required: ["key", "value"],
|
|
43
|
+
additionalProperties: false
|
|
44
|
+
},
|
|
45
|
+
properties: void 0,
|
|
46
|
+
patternProperties: void 0,
|
|
47
|
+
additionalProperties: void 0,
|
|
48
|
+
required: void 0
|
|
49
|
+
};
|
|
50
|
+
fields.push([name, jsonValues]);
|
|
51
|
+
}
|
|
52
|
+
fieldsByTool.set(tool.name, fields);
|
|
53
|
+
}
|
|
54
|
+
return fieldsByTool;
|
|
55
|
+
}
|
|
56
|
+
function transformArguments(toolName, args, fields, toWire) {
|
|
57
|
+
for (const [name, jsonValues] of fields.get(toolName) ?? []) {
|
|
58
|
+
const value = args[name];
|
|
59
|
+
if (toWire) {
|
|
60
|
+
if (isRecord(value)) args[name] = Object.entries(value).map(([key, item]) => ({
|
|
61
|
+
key,
|
|
62
|
+
value: jsonValues || typeof item !== "string" ? JSON.stringify(item) ?? "null" : item
|
|
63
|
+
}));
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!Array.isArray(value)) continue;
|
|
67
|
+
const entries = [];
|
|
68
|
+
const keys = /* @__PURE__ */ new Set();
|
|
69
|
+
let valid = true;
|
|
70
|
+
for (const entry of value) {
|
|
71
|
+
if (!isRecord(entry) || typeof entry.key !== "string" || typeof entry.value !== "string" || keys.has(entry.key)) {
|
|
72
|
+
valid = false;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
keys.add(entry.key);
|
|
76
|
+
let item = entry.value;
|
|
77
|
+
if (jsonValues) try {
|
|
78
|
+
item = JSON.parse(entry.value);
|
|
79
|
+
} catch {
|
|
80
|
+
valid = false;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
entries.push([entry.key, item]);
|
|
84
|
+
}
|
|
85
|
+
if (valid) args[name] = Object.fromEntries(entries);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function transformCall(call, state, toWire) {
|
|
89
|
+
if (typeof call.name !== "string") return;
|
|
90
|
+
let toolName = call.name;
|
|
91
|
+
if (!toWire && state.alias && toolName === state.alias) call.name = toolName = WEB_SEARCH;
|
|
92
|
+
const serialized = typeof call.arguments === "string";
|
|
93
|
+
try {
|
|
94
|
+
const args = serialized ? JSON.parse(call.arguments) : !toWire && isRecord(call.arguments) ? { ...call.arguments } : call.arguments;
|
|
95
|
+
if (isRecord(args)) {
|
|
96
|
+
transformArguments(toolName, args, state.fields, toWire);
|
|
97
|
+
call.arguments = serialized ? JSON.stringify(args) : args;
|
|
98
|
+
}
|
|
99
|
+
} catch {}
|
|
100
|
+
}
|
|
101
|
+
function aliasWebSearch(payload) {
|
|
102
|
+
const functions = payloadFunctions(payload);
|
|
103
|
+
const names = new Set(functions.map((item) => item.name));
|
|
104
|
+
if (!names.has(WEB_SEARCH)) return;
|
|
105
|
+
let alias = WEB_SEARCH_ALIAS;
|
|
106
|
+
for (let suffix = 2; names.has(alias); suffix += 1) alias = `${WEB_SEARCH_ALIAS}_${suffix}`;
|
|
107
|
+
for (const item of functions) if (item.name === WEB_SEARCH) item.name = alias;
|
|
108
|
+
return alias;
|
|
109
|
+
}
|
|
110
|
+
function restoreMessage(message, state) {
|
|
111
|
+
const restored = {
|
|
112
|
+
...message,
|
|
113
|
+
content: message.content.map((block) => ({ ...block }))
|
|
114
|
+
};
|
|
115
|
+
for (const block of restored.content) if (block.type === "toolCall") transformCall(block, state, false);
|
|
116
|
+
return restored;
|
|
117
|
+
}
|
|
118
|
+
function restoreEvent(event, state) {
|
|
119
|
+
const restored = { ...event };
|
|
120
|
+
if ("partial" in restored && restored.partial) restored.partial = restoreMessage(restored.partial, state);
|
|
121
|
+
if (restored.type === "toolcall_delta") {
|
|
122
|
+
const call = restored.partial.content[restored.contentIndex];
|
|
123
|
+
if (call?.type === "toolCall" && (state.fields.get(call.name)?.length ?? 0) > 0) restored.delta = "";
|
|
124
|
+
} else if (restored.type === "toolcall_end") {
|
|
125
|
+
restored.toolCall = { ...restored.toolCall };
|
|
126
|
+
transformCall(restored.toolCall, state, false);
|
|
127
|
+
} else if (restored.type === "done") restored.message = restoreMessage(restored.message, state);
|
|
128
|
+
else if (restored.type === "error") restored.error = restoreMessage(restored.error, state);
|
|
129
|
+
return restored;
|
|
130
|
+
}
|
|
131
|
+
function wrapResponseStream(stream, state) {
|
|
132
|
+
return {
|
|
133
|
+
async *[Symbol.asyncIterator]() {
|
|
134
|
+
for await (const event of stream) yield restoreEvent(event, state);
|
|
135
|
+
},
|
|
136
|
+
async result() {
|
|
137
|
+
return restoreMessage(await stream.result(), state);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function wrapOpencodeProviderStream(ctx) {
|
|
142
|
+
const underlying = ctx.streamFn ?? streamSimple;
|
|
143
|
+
return (model, context, options) => {
|
|
144
|
+
if (model.api !== "openai-responses") return underlying(model, context, options);
|
|
145
|
+
const originalOnPayload = options?.onPayload;
|
|
146
|
+
const state = { fields: /* @__PURE__ */ new Map() };
|
|
147
|
+
const maybeStream = underlying(model, context, {
|
|
148
|
+
...options,
|
|
149
|
+
async onPayload(payload, payloadModel) {
|
|
150
|
+
const finalPayload = await originalOnPayload?.(payload, payloadModel) ?? payload;
|
|
151
|
+
state.fields = /* @__PURE__ */ new Map();
|
|
152
|
+
state.alias = void 0;
|
|
153
|
+
if (isRecord(finalPayload)) {
|
|
154
|
+
state.fields = rewriteDynamicRecordSchemas(finalPayload);
|
|
155
|
+
for (const call of payloadFunctions(finalPayload)) if (call.type === "function_call") transformCall(call, state, true);
|
|
156
|
+
state.alias = aliasWebSearch(finalPayload);
|
|
157
|
+
}
|
|
158
|
+
return finalPayload;
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
const wrap = (stream) => wrapResponseStream(stream, state);
|
|
162
|
+
return maybeStream && typeof maybeStream === "object" && "then" in maybeStream ? Promise.resolve(maybeStream).then(wrap) : wrap(maybeStream);
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
export { wrapOpencodeProviderStream };
|