@nexface/agent 0.1.15-alpha.0 → 0.1.15-alpha.2
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/dist/agent.d.ts +1 -2
- package/dist/agent.js +918 -333
- package/dist/browser-policy/gpt.js +36 -12
- package/dist/browser-policy/jev.js +21 -9
- package/dist/browser-policy/response-error.js +4 -2
- package/dist/browser-policy/shared.js +49 -21
- package/dist/browser-prompt.generated.js +0 -1
- package/dist/browser-prompt.js +0 -1
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +3 -4
- package/dist/history-compaction.js +47 -26
- package/dist/history-version.js +11 -4
- package/dist/index.js +0 -1
- package/dist/model/binding.js +0 -1
- package/dist/model/error.js +0 -1
- package/dist/model/internal-adapter.js +1 -2
- package/dist/model/types.js +0 -1
- package/dist/models/3.js +5553 -0
- package/dist/models/3e.js +4 -0
- package/dist/models/6.js +506 -0
- package/dist/models/anthropic-messages.js +5 -20
- package/dist/models/anthropic-messages~1.js +5629 -0
- package/dist/models/deferred-tools.js +28 -0
- package/dist/models/error-body.js +64 -0
- package/dist/models/google-generative-ai.js +4 -19
- package/dist/models/google-generative-ai~1.js +18305 -0
- package/dist/models/google-generative-ai~1.js.LICENSE.txt +5 -0
- package/dist/models/{39.js → k.js} +168 -336
- package/dist/models/openai-completions.js +3 -10
- package/dist/models/openai-completions~1.js +987 -0
- package/dist/models/openai-responses.js +3 -10
- package/dist/models/openai-responses~1.js +848 -0
- package/dist/models/rslib-runtime.js +32 -56
- package/dist/models/v.js +346 -0
- package/dist/page-decision.js +197 -59
- package/dist/page-decisions/gpt.js +0 -1
- package/dist/page-decisions/jev.js +0 -1
- package/dist/page-decisions/shared.js +26 -9
- package/dist/page-diagnostics.js +8 -3
- package/dist/page-observation.js +11 -6
- package/dist/request.js +169 -41
- package/dist/shared/definition.js +2 -3
- package/dist/shared/errors.d.ts +1 -1
- package/dist/shared/errors.js +0 -1
- package/dist/shared/page-protocol.js +0 -1
- package/dist/shared/page-tools.js +0 -1
- package/dist/shared/runtime-controller.d.ts +1 -0
- package/dist/shared/runtime-controller.js +0 -1
- package/dist/shared/runtime-execution.js +0 -1
- package/dist/shared/schema.js +45 -19
- package/dist/tool-catalog.js +23 -25
- package/dist/tool-result.js +7 -3
- package/dist/types.js +0 -1
- package/package.json +6 -2
- package/dist/agent.js.map +0 -1
- package/dist/browser-policy/gpt.js.map +0 -1
- package/dist/browser-policy/jev.js.map +0 -1
- package/dist/browser-policy/response-error.js.map +0 -1
- package/dist/browser-policy/shared.js.map +0 -1
- package/dist/browser-prompt.generated.js.map +0 -1
- package/dist/browser-prompt.js.map +0 -1
- package/dist/errors.js.map +0 -1
- package/dist/history-compaction.js.map +0 -1
- package/dist/history-version.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/model/binding.js.map +0 -1
- package/dist/model/error.js.map +0 -1
- package/dist/model/internal-adapter.js.map +0 -1
- package/dist/model/types.js.map +0 -1
- package/dist/models/851.js +0 -10
- package/dist/models/_chunks/360-7e580bb2.js +0 -1189
- package/dist/models/_chunks/474-e1813138.js +0 -8304
- package/dist/models/_chunks/86-c0c5ac98.js +0 -453
- package/dist/models/_chunks/anthropic-messages~1-d35e3e7d.js +0 -8057
- package/dist/models/_chunks/deferred-tools-90f3c977.js +0 -37
- package/dist/models/_chunks/error-body-8bee35c2.js +0 -134
- package/dist/models/_chunks/google-generative-ai~1-2ba71457.js +0 -22104
- package/dist/models/_chunks/openai-completions~1-b340f0e0.js +0 -1285
- package/dist/models/_chunks/openai-responses~1-b53c65c2.js +0 -958
- package/dist/page-decision.js.map +0 -1
- package/dist/page-decisions/gpt.js.map +0 -1
- package/dist/page-decisions/jev.js.map +0 -1
- package/dist/page-decisions/shared.js.map +0 -1
- package/dist/page-diagnostics.js.map +0 -1
- package/dist/page-observation.js.map +0 -1
- package/dist/request.js.map +0 -1
- package/dist/shared/definition.js.map +0 -1
- package/dist/shared/errors.js.map +0 -1
- package/dist/shared/page-protocol.js.map +0 -1
- package/dist/shared/page-tools.js.map +0 -1
- package/dist/shared/runtime-controller.js.map +0 -1
- package/dist/shared/runtime-execution.js.map +0 -1
- package/dist/shared/schema.js.map +0 -1
- package/dist/shared/tool-registry.d.ts +0 -6
- package/dist/shared/tool-registry.js +0 -10
- package/dist/shared/tool-registry.js.map +0 -1
- package/dist/tool-catalog.js.map +0 -1
- package/dist/tool-result.js.map +0 -1
- package/dist/types.js.map +0 -1
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { defineAgentModelConfig } from "../model/binding.js";
|
|
2
|
-
|
|
3
2
|
function flattenModelCatalog(_provider, groups) {
|
|
4
3
|
return Object.assign({}, ...Object.values(groups));
|
|
5
4
|
}
|
|
6
|
-
//# sourceMappingURL=model-catalog.js.map
|
|
7
|
-
// Generic event stream class for async iteration
|
|
8
5
|
class EventStream {
|
|
9
6
|
queue = [];
|
|
10
7
|
waiting = [];
|
|
@@ -13,54 +10,44 @@ class EventStream {
|
|
|
13
10
|
resolveFinalResult;
|
|
14
11
|
isComplete;
|
|
15
12
|
extractResult;
|
|
16
|
-
constructor(isComplete, extractResult)
|
|
13
|
+
constructor(isComplete, extractResult){
|
|
17
14
|
this.isComplete = isComplete;
|
|
18
15
|
this.extractResult = extractResult;
|
|
19
|
-
this.finalResultPromise = new Promise((resolve)
|
|
16
|
+
this.finalResultPromise = new Promise((resolve)=>{
|
|
20
17
|
this.resolveFinalResult = resolve;
|
|
21
18
|
});
|
|
22
19
|
}
|
|
23
20
|
push(event) {
|
|
24
|
-
if (this.done)
|
|
25
|
-
return;
|
|
21
|
+
if (this.done) return;
|
|
26
22
|
if (this.isComplete(event)) {
|
|
27
23
|
this.done = true;
|
|
28
24
|
this.resolveFinalResult(this.extractResult(event));
|
|
29
25
|
}
|
|
30
|
-
// Deliver to waiting consumer or queue it
|
|
31
26
|
const waiter = this.waiting.shift();
|
|
32
|
-
if (waiter) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
27
|
+
if (waiter) waiter({
|
|
28
|
+
value: event,
|
|
29
|
+
done: false
|
|
30
|
+
});
|
|
31
|
+
else this.queue.push(event);
|
|
38
32
|
}
|
|
39
33
|
end(result) {
|
|
40
34
|
this.done = true;
|
|
41
|
-
if (
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
-
// Notify all waiting consumers that we're done
|
|
45
|
-
while (this.waiting.length > 0) {
|
|
35
|
+
if (void 0 !== result) this.resolveFinalResult(result);
|
|
36
|
+
while(this.waiting.length > 0){
|
|
46
37
|
const waiter = this.waiting.shift();
|
|
47
|
-
waiter({
|
|
38
|
+
waiter({
|
|
39
|
+
value: void 0,
|
|
40
|
+
done: true
|
|
41
|
+
});
|
|
48
42
|
}
|
|
49
43
|
}
|
|
50
44
|
async *[Symbol.asyncIterator]() {
|
|
51
|
-
while
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
}
|
|
58
|
-
else {
|
|
59
|
-
const result = await new Promise((resolve) => this.waiting.push(resolve));
|
|
60
|
-
if (result.done)
|
|
61
|
-
return;
|
|
62
|
-
yield result.value;
|
|
63
|
-
}
|
|
45
|
+
while(true)if (this.queue.length > 0) yield this.queue.shift();
|
|
46
|
+
else {
|
|
47
|
+
if (this.done) return;
|
|
48
|
+
const result = await new Promise((resolve)=>this.waiting.push(resolve));
|
|
49
|
+
if (result.done) return;
|
|
50
|
+
yield result.value;
|
|
64
51
|
}
|
|
65
52
|
}
|
|
66
53
|
result() {
|
|
@@ -68,24 +55,14 @@ class EventStream {
|
|
|
68
55
|
}
|
|
69
56
|
}
|
|
70
57
|
class AssistantMessageEventStream extends EventStream {
|
|
71
|
-
constructor()
|
|
72
|
-
super((event)
|
|
73
|
-
if (event.type
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
else if (event.type === "error") {
|
|
77
|
-
return event.error;
|
|
78
|
-
}
|
|
58
|
+
constructor(){
|
|
59
|
+
super((event)=>"done" === event.type || "error" === event.type, (event)=>{
|
|
60
|
+
if ("done" === event.type) return event.message;
|
|
61
|
+
else if ("error" === event.type) return event.error;
|
|
79
62
|
throw new Error("Unexpected event type for final result");
|
|
80
63
|
});
|
|
81
64
|
}
|
|
82
65
|
}
|
|
83
|
-
/** Factory function for AssistantMessageEventStream (for use in extensions) */
|
|
84
|
-
function createAssistantMessageEventStream() {
|
|
85
|
-
return new AssistantMessageEventStream();
|
|
86
|
-
}
|
|
87
|
-
//# sourceMappingURL=event-stream.js.map
|
|
88
|
-
|
|
89
66
|
function createSetupErrorMessage(model, error) {
|
|
90
67
|
return {
|
|
91
68
|
role: "assistant",
|
|
@@ -99,62 +76,56 @@ function createSetupErrorMessage(model, error) {
|
|
|
99
76
|
cacheRead: 0,
|
|
100
77
|
cacheWrite: 0,
|
|
101
78
|
totalTokens: 0,
|
|
102
|
-
cost: {
|
|
79
|
+
cost: {
|
|
80
|
+
input: 0,
|
|
81
|
+
output: 0,
|
|
82
|
+
cacheRead: 0,
|
|
83
|
+
cacheWrite: 0,
|
|
84
|
+
total: 0
|
|
85
|
+
}
|
|
103
86
|
},
|
|
104
87
|
stopReason: "error",
|
|
105
88
|
errorMessage: error instanceof Error ? error.message : String(error),
|
|
106
|
-
timestamp: Date.now()
|
|
89
|
+
timestamp: Date.now()
|
|
107
90
|
};
|
|
108
91
|
}
|
|
109
92
|
function hasResult(source) {
|
|
110
|
-
return typeof source.result
|
|
93
|
+
return "function" == typeof source.result;
|
|
111
94
|
}
|
|
112
95
|
async function forwardStream(target, source) {
|
|
113
|
-
for await (const event of source)
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
target.end(hasResult(source) ? await source.result() : undefined);
|
|
96
|
+
for await (const event of source)target.push(event);
|
|
97
|
+
target.end(hasResult(source) ? await source.result() : void 0);
|
|
117
98
|
}
|
|
118
|
-
/**
|
|
119
|
-
* Returns a stream synchronously while running async setup (auth resolution,
|
|
120
|
-
* lazy module loading) behind it. Setup failures terminate the stream with an
|
|
121
|
-
* error event.
|
|
122
|
-
*/
|
|
123
99
|
function lazyStream(model, setup) {
|
|
124
100
|
const outer = new AssistantMessageEventStream();
|
|
125
|
-
setup()
|
|
126
|
-
.then((inner) => forwardStream(outer, inner))
|
|
127
|
-
.catch((error) => {
|
|
101
|
+
setup().then((inner)=>forwardStream(outer, inner)).catch((error)=>{
|
|
128
102
|
const message = createSetupErrorMessage(model, error);
|
|
129
|
-
outer.push({
|
|
103
|
+
outer.push({
|
|
104
|
+
type: "error",
|
|
105
|
+
reason: "error",
|
|
106
|
+
error: message
|
|
107
|
+
});
|
|
130
108
|
outer.end(message);
|
|
131
109
|
});
|
|
132
110
|
return outer;
|
|
133
111
|
}
|
|
134
112
|
function lazyApi(load, capabilities) {
|
|
135
113
|
const api = {
|
|
136
|
-
stream: (model, context, options)
|
|
137
|
-
streamSimple: (model, context, options)
|
|
114
|
+
stream: (model, context, options)=>lazyStream(model, async ()=>(await load()).stream(model, context, options)),
|
|
115
|
+
streamSimple: (model, context, options)=>lazyStream(model, async ()=>(await load()).streamSimple(model, context, options))
|
|
138
116
|
};
|
|
139
|
-
if (capabilities?.fetchDeferred) {
|
|
140
|
-
api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
|
|
117
|
+
if (capabilities?.fetchDeferred) api.fetchDeferred = (model, handle, options)=>lazyStream(model, async ()=>{
|
|
141
118
|
const implementation = await load();
|
|
142
|
-
if (!implementation.fetchDeferred)
|
|
143
|
-
throw new Error("API does not support deferred responses");
|
|
119
|
+
if (!implementation.fetchDeferred) throw new Error("API does not support deferred responses");
|
|
144
120
|
return implementation.fetchDeferred(model, handle, options);
|
|
145
121
|
});
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
throw new Error("API cannot cancel deferred responses");
|
|
152
|
-
await implementation.cancelDeferred(model, handle, options);
|
|
153
|
-
};
|
|
154
|
-
}
|
|
122
|
+
if (capabilities?.cancelDeferred) api.cancelDeferred = async (model, handle, options)=>{
|
|
123
|
+
const implementation = await load();
|
|
124
|
+
if (!implementation.cancelDeferred) throw new Error("API cannot cancel deferred responses");
|
|
125
|
+
await implementation.cancelDeferred(model, handle, options);
|
|
126
|
+
};
|
|
155
127
|
return api;
|
|
156
128
|
}
|
|
157
|
-
//# sourceMappingURL=lazy.js.map
|
|
158
129
|
const LEGACY_TOOL_NAMES = new Set([
|
|
159
130
|
"callAppTool",
|
|
160
131
|
"getSnapshot",
|
|
@@ -165,12 +136,8 @@ const LEGACY_TOOL_NAMES = new Set([
|
|
|
165
136
|
]);
|
|
166
137
|
const HISTORY_VERSION_ERROR = "Unsupported Nexface history version. Upgrade client and server together and start a new conversation.";
|
|
167
138
|
function assertCurrentHistory(messages) {
|
|
168
|
-
for (const message of messages)
|
|
169
|
-
if (message.role === "assistant" && message.toolCalls.some((call)=>LEGACY_TOOL_NAMES.has(call.name)) || message.role === "tool" && LEGACY_TOOL_NAMES.has(message.name)) throw new Error(HISTORY_VERSION_ERROR);
|
|
170
|
-
}
|
|
139
|
+
for (const message of messages)if ("assistant" === message.role && message.toolCalls.some((call)=>LEGACY_TOOL_NAMES.has(call.name)) || "tool" === message.role && LEGACY_TOOL_NAMES.has(message.name)) throw new Error(HISTORY_VERSION_ERROR);
|
|
171
140
|
}
|
|
172
|
-
|
|
173
|
-
|
|
174
141
|
const AGENT_ERROR_CODES = [
|
|
175
142
|
"EXECUTION_OUTCOME_UNKNOWN",
|
|
176
143
|
"AGENT_RUN_ACTIVE",
|
|
@@ -194,22 +161,8 @@ const AGENT_MODEL_ERROR_CODES = [
|
|
|
194
161
|
"MODEL_REQUEST_FAILED",
|
|
195
162
|
"MODEL_INPUT_UNSUPPORTED"
|
|
196
163
|
];
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
function isAgentError(error) {
|
|
200
|
-
if (!error || typeof error !== "object") return false;
|
|
201
|
-
const candidate = error;
|
|
202
|
-
if (candidate.type !== "agent_error" || typeof candidate.code !== "string" || typeof candidate.message !== "string") {
|
|
203
|
-
return false;
|
|
204
|
-
}
|
|
205
|
-
if (candidate.domain === "agent") {
|
|
206
|
-
return AGENT_ERROR_CODE_SET.has(candidate.code);
|
|
207
|
-
}
|
|
208
|
-
if (candidate.domain === "model") {
|
|
209
|
-
return AGENT_MODEL_ERROR_CODE_SET.has(candidate.code);
|
|
210
|
-
}
|
|
211
|
-
return false;
|
|
212
|
-
}
|
|
164
|
+
new Set(AGENT_ERROR_CODES);
|
|
165
|
+
new Set(AGENT_MODEL_ERROR_CODES);
|
|
213
166
|
class AgentError extends Error {
|
|
214
167
|
code;
|
|
215
168
|
details;
|
|
@@ -220,16 +173,13 @@ class AgentError extends Error {
|
|
|
220
173
|
this.name = "AgentError";
|
|
221
174
|
}
|
|
222
175
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
176
|
class AgentModelError extends AgentError {
|
|
226
177
|
code;
|
|
227
178
|
constructor(code, message){
|
|
228
|
-
super(code, message,
|
|
179
|
+
super(code, message, void 0, "model"), this.code = code;
|
|
229
180
|
this.name = "AgentModelError";
|
|
230
181
|
}
|
|
231
182
|
}
|
|
232
|
-
|
|
233
183
|
const HOST_PAGE_TOOLS = new Set([
|
|
234
184
|
"nxf_getSnapshot",
|
|
235
185
|
"nxf_applyAction",
|
|
@@ -240,40 +190,32 @@ function hideHostPageToolNames(content) {
|
|
|
240
190
|
}
|
|
241
191
|
function projectPageDelegationHistory(entries) {
|
|
242
192
|
const hiddenCallIds = new Set();
|
|
243
|
-
for (const { message } of entries){
|
|
244
|
-
if (message.role !== "assistant") continue;
|
|
193
|
+
for (const { message } of entries)if ("assistant" === message.role) {
|
|
245
194
|
for (const call of message.toolCalls)if (HOST_PAGE_TOOLS.has(call.name)) hiddenCallIds.add(call.id);
|
|
246
195
|
}
|
|
247
196
|
const visible = [];
|
|
248
197
|
for (const entry of entries){
|
|
249
198
|
const { message, index } = entry;
|
|
250
|
-
if (message.role
|
|
199
|
+
if ("assistant" === message.role) {
|
|
251
200
|
const toolCalls = message.toolCalls.filter((call)=>!HOST_PAGE_TOOLS.has(call.name));
|
|
252
201
|
const removedPageCall = toolCalls.length !== message.toolCalls.length;
|
|
253
|
-
const content = typeof message.content
|
|
202
|
+
const content = "string" == typeof message.content && index < 0 ? hideHostPageToolNames(message.content) : message.content;
|
|
254
203
|
if (removedPageCall && !toolCalls.length && !content) continue;
|
|
255
|
-
if (removedPageCall || content !== message.content) {
|
|
256
|
-
|
|
257
|
-
message
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
} else if (message.role !== "tool" || !hiddenCallIds.has(message.toolCallId) && !HOST_PAGE_TOOLS.has(message.name)) {
|
|
266
|
-
visible.push(entry);
|
|
267
|
-
}
|
|
204
|
+
if (removedPageCall || content !== message.content) visible.push({
|
|
205
|
+
message: {
|
|
206
|
+
...message,
|
|
207
|
+
content,
|
|
208
|
+
toolCalls
|
|
209
|
+
},
|
|
210
|
+
index: -1
|
|
211
|
+
});
|
|
212
|
+
else visible.push(entry);
|
|
213
|
+
} else if ("tool" !== message.role || !hiddenCallIds.has(message.toolCallId) && !HOST_PAGE_TOOLS.has(message.name)) visible.push(entry);
|
|
268
214
|
}
|
|
269
215
|
return visible;
|
|
270
216
|
}
|
|
271
|
-
const HISTORY_COMPACTION_TRIGGER_BYTES = (/* unused pure expression or super */ null && (128 * 1024));
|
|
272
|
-
const HISTORY_COMPACTION_MIN_NEW_BYTES = (/* unused pure expression or super */ null && (32 * 1024));
|
|
273
|
-
const HISTORY_COMPACTION_MIN_SAVINGS_BYTES = (/* unused pure expression or super */ null && (16 * 1024));
|
|
274
|
-
const HISTORY_SUMMARY_MAX_BYTES = (/* unused pure expression or super */ null && (16 * 1024));
|
|
275
217
|
const RECENT_BATCHES = 2;
|
|
276
|
-
|
|
218
|
+
new TextEncoder();
|
|
277
219
|
function historyLayout(messages) {
|
|
278
220
|
const batches = [];
|
|
279
221
|
const unsafeIndices = [];
|
|
@@ -285,48 +227,45 @@ function historyLayout(messages) {
|
|
|
285
227
|
let latestDelegationBatch;
|
|
286
228
|
const settle = ()=>{
|
|
287
229
|
if (current) {
|
|
288
|
-
current.complete = valid && pending.size
|
|
230
|
+
current.complete = valid && 0 === pending.size;
|
|
289
231
|
if (!current.complete) unsafeIndices.push(current.start);
|
|
290
232
|
}
|
|
291
|
-
current =
|
|
233
|
+
current = void 0;
|
|
292
234
|
};
|
|
293
|
-
for (const [index, message] of messages.entries()){
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
continue;
|
|
316
|
-
}
|
|
317
|
-
current.indices.push(index);
|
|
318
|
-
if (pending.get(message.toolCallId) !== message.name) valid = false;
|
|
319
|
-
pending.delete(message.toolCallId);
|
|
320
|
-
if (message.name === "nxf_getSnapshot" || message.name === "nxf_executeAction" || message.name === "nxf_applyAction") latestBrowserBatch = current;
|
|
321
|
-
if (message.name === "nxf_delegatePageTask") latestDelegationBatch = current;
|
|
235
|
+
for (const [index, message] of messages.entries())if ("user" === message.role) {
|
|
236
|
+
settle();
|
|
237
|
+
latestUser = index;
|
|
238
|
+
} else if ("assistant" === message.role) {
|
|
239
|
+
settle();
|
|
240
|
+
current = {
|
|
241
|
+
start: index,
|
|
242
|
+
indices: [
|
|
243
|
+
index
|
|
244
|
+
],
|
|
245
|
+
complete: false
|
|
246
|
+
};
|
|
247
|
+
batches.push(current);
|
|
248
|
+
pending = new Map(message.toolCalls.map((call)=>[
|
|
249
|
+
call.id,
|
|
250
|
+
call.name
|
|
251
|
+
]));
|
|
252
|
+
valid = pending.size === message.toolCalls.length;
|
|
253
|
+
} else if ("tool" === message.role) {
|
|
254
|
+
if (!current) {
|
|
255
|
+
unsafeIndices.push(index);
|
|
256
|
+
continue;
|
|
322
257
|
}
|
|
258
|
+
current.indices.push(index);
|
|
259
|
+
if (pending.get(message.toolCallId) !== message.name) valid = false;
|
|
260
|
+
pending.delete(message.toolCallId);
|
|
261
|
+
if ("nxf_getSnapshot" === message.name || "nxf_executeAction" === message.name || "nxf_applyAction" === message.name) latestBrowserBatch = current;
|
|
262
|
+
if ("nxf_delegatePageTask" === message.name) latestDelegationBatch = current;
|
|
323
263
|
}
|
|
324
264
|
settle();
|
|
325
265
|
const protectedIndices = new Set(latestUser < 0 ? [] : [
|
|
326
266
|
latestUser
|
|
327
267
|
]);
|
|
328
268
|
const recent = batches.filter((batch)=>batch.complete).slice(-RECENT_BATCHES);
|
|
329
|
-
// A page stage updates its original delegation receipt after internal steps finish.
|
|
330
269
|
for (const batch of [
|
|
331
270
|
...recent,
|
|
332
271
|
...latestBrowserBatch ? [
|
|
@@ -335,9 +274,7 @@ function historyLayout(messages) {
|
|
|
335
274
|
...latestDelegationBatch ? [
|
|
336
275
|
latestDelegationBatch
|
|
337
276
|
] : []
|
|
338
|
-
])
|
|
339
|
-
for (const index of batch.indices)protectedIndices.add(index);
|
|
340
|
-
}
|
|
277
|
+
])for (const index of batch.indices)protectedIndices.add(index);
|
|
341
278
|
return {
|
|
342
279
|
batches,
|
|
343
280
|
latestUser,
|
|
@@ -346,17 +283,14 @@ function historyLayout(messages) {
|
|
|
346
283
|
};
|
|
347
284
|
}
|
|
348
285
|
function boundaryIndex(messages, messageId, layout) {
|
|
349
|
-
const index = messages.findIndex((message)=>message.id === messageId && (
|
|
350
|
-
if (index < 0 || layout.unsafeIndices.some((unsafe)=>unsafe < index) || messages[index].role
|
|
351
|
-
throw new Error("History compaction boundary does not reference a complete batch or user message.");
|
|
352
|
-
}
|
|
286
|
+
const index = messages.findIndex((message)=>message.id === messageId && ("user" === message.role || "assistant" === message.role));
|
|
287
|
+
if (index < 0 || layout.unsafeIndices.some((unsafe)=>unsafe < index) || "assistant" === messages[index].role && !layout.batches.some((batch)=>batch.start === index && batch.complete)) throw new Error("History compaction boundary does not reference a complete batch or user message.");
|
|
353
288
|
return index;
|
|
354
289
|
}
|
|
355
290
|
function summaryMessage(summary, messages, boundary) {
|
|
356
291
|
let latestUser = -1;
|
|
357
292
|
let coveredUser = -1;
|
|
358
|
-
for (const [index, message] of messages.entries()){
|
|
359
|
-
if (message.role !== "user") continue;
|
|
293
|
+
for (const [index, message] of messages.entries())if ("user" === message.role) {
|
|
360
294
|
latestUser = index;
|
|
361
295
|
if (index < boundary) coveredUser = index;
|
|
362
296
|
}
|
|
@@ -369,51 +303,27 @@ function summaryMessage(summary, messages, boundary) {
|
|
|
369
303
|
}
|
|
370
304
|
function latestContextIndex(messages) {
|
|
371
305
|
let latest = -1;
|
|
372
|
-
let revision = -
|
|
373
|
-
for (const [index, message] of messages.entries()){
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
revision = message.revision;
|
|
377
|
-
}
|
|
306
|
+
let revision = -1 / 0;
|
|
307
|
+
for (const [index, message] of messages.entries())if ("application_context" === message.role && message.revision >= revision) {
|
|
308
|
+
latest = index;
|
|
309
|
+
revision = message.revision;
|
|
378
310
|
}
|
|
379
311
|
return latest;
|
|
380
312
|
}
|
|
381
|
-
function validateHistorySummary(value, canonicalMessages) {
|
|
382
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid history summary.");
|
|
383
|
-
const summary = value;
|
|
384
|
-
if (Object.keys(summary).some((key)=>key !== "beforeMessageId" && key !== "content") || typeof summary.beforeMessageId !== "string" || !summary.beforeMessageId || typeof summary.content !== "string" || !summary.content.trim() || encoder.encode(summary.content).byteLength > HISTORY_SUMMARY_MAX_BYTES) {
|
|
385
|
-
throw new Error("Invalid history summary.");
|
|
386
|
-
}
|
|
387
|
-
const validated = {
|
|
388
|
-
beforeMessageId: summary.beforeMessageId,
|
|
389
|
-
content: summary.content.trim()
|
|
390
|
-
};
|
|
391
|
-
boundaryIndex(canonicalMessages, validated.beforeMessageId, historyLayout(canonicalMessages));
|
|
392
|
-
return validated;
|
|
393
|
-
}
|
|
394
|
-
function validateCompactionAttempt(value, messages, summary) {
|
|
395
|
-
if (typeof value !== "string" || !value) throw new Error("Invalid history compaction attempt.");
|
|
396
|
-
const layout = historyLayout(messages);
|
|
397
|
-
const index = boundaryIndex(messages, value, layout);
|
|
398
|
-
if (summary && index < boundaryIndex(messages, summary.beforeMessageId, layout)) {
|
|
399
|
-
throw new Error("History compaction attempt precedes the summary.");
|
|
400
|
-
}
|
|
401
|
-
return value;
|
|
402
|
-
}
|
|
403
313
|
function selectModelHistory(messages, summary, options) {
|
|
404
314
|
const layout = historyLayout(messages);
|
|
405
315
|
const boundary = summary ? boundaryIndex(messages, summary.beforeMessageId, layout) : 0;
|
|
406
316
|
const contextIndex = latestContextIndex(messages);
|
|
407
|
-
const catalogIndex = messages.reduce((last, message, index)=>message.role
|
|
317
|
+
const catalogIndex = messages.reduce((last, message, index)=>"system" === message.role && message.content.startsWith("[NEXFACE_RUNTIME_V1]") ? index : last, -1);
|
|
408
318
|
const entries = [];
|
|
409
319
|
for (const [index, message] of messages.entries()){
|
|
410
320
|
if (summary && index === boundary) entries.push({
|
|
411
321
|
message: summaryMessage(summary, messages, boundary),
|
|
412
322
|
index: -1
|
|
413
323
|
});
|
|
414
|
-
if (message.role
|
|
324
|
+
if ("system" === message.role) {
|
|
415
325
|
if (message.content.startsWith("[NEXFACE_RUNTIME_V1]") && index !== catalogIndex) continue;
|
|
416
|
-
} else if (message.role
|
|
326
|
+
} else if ("application_context" === message.role) {
|
|
417
327
|
if (index !== contextIndex) continue;
|
|
418
328
|
} else if (index < boundary && !layout.protectedIndices.has(index)) continue;
|
|
419
329
|
entries.push({
|
|
@@ -423,49 +333,10 @@ function selectModelHistory(messages, summary, options) {
|
|
|
423
333
|
}
|
|
424
334
|
return options?.pageDelegation ? projectPageDelegationHistory(entries) : entries;
|
|
425
335
|
}
|
|
426
|
-
function serializedBytes(messages) {
|
|
427
|
-
return encoder.encode(JSON.stringify(messages)).byteLength;
|
|
428
|
-
}
|
|
429
|
-
function modelHistoryBytes(messages, summary, options) {
|
|
430
|
-
return serializedBytes(selectModelHistory(messages, summary, options).map((entry)=>entry.message));
|
|
431
|
-
}
|
|
432
|
-
function getHistoryCompactionInput(messages, previous, attemptBeforeMessageId, options) {
|
|
433
|
-
const layout = historyLayout(messages);
|
|
434
|
-
// A pending or malformed tool batch must be settled before choosing any new cut.
|
|
435
|
-
if (layout.unsafeIndices.length || layout.batches.length <= RECENT_BATCHES) return undefined;
|
|
436
|
-
const boundary = layout.batches[layout.batches.length - RECENT_BATCHES].start;
|
|
437
|
-
const beforeMessageId = messages[boundary].id;
|
|
438
|
-
const start = previous ? boundaryIndex(messages, previous.beforeMessageId, layout) : 0;
|
|
439
|
-
const attemptStart = attemptBeforeMessageId ? boundaryIndex(messages, attemptBeforeMessageId, layout) : start;
|
|
440
|
-
if (!beforeMessageId || boundary <= Math.max(start, attemptStart) || modelHistoryBytes(messages, previous, options) <= HISTORY_COMPACTION_TRIGGER_BYTES) return undefined;
|
|
441
|
-
const removable = messages.slice(attemptStart, boundary).filter((message, offset)=>message.role !== "system" && message.role !== "application_context" && !layout.protectedIndices.has(offset + attemptStart));
|
|
442
|
-
const visibleRemovable = options?.pageDelegation ? projectPageDelegationHistory(removable.map((message, index)=>({
|
|
443
|
-
message,
|
|
444
|
-
index
|
|
445
|
-
}))).map(({ message })=>message) : removable;
|
|
446
|
-
if (serializedBytes(visibleRemovable) < HISTORY_COMPACTION_MIN_NEW_BYTES) return undefined;
|
|
447
|
-
const prefix = previous ? [
|
|
448
|
-
summaryMessage(previous, messages, start)
|
|
449
|
-
] : [];
|
|
450
|
-
for(let index = start; index < boundary; index += 1){
|
|
451
|
-
const message = messages[index];
|
|
452
|
-
if (message.role !== "system" && message.role !== "application_context") prefix.push(message);
|
|
453
|
-
}
|
|
454
|
-
return {
|
|
455
|
-
beforeMessageId,
|
|
456
|
-
messages: prefix,
|
|
457
|
-
...layout.latestUser < 0 ? {} : {
|
|
458
|
-
latestUser: messages[layout.latestUser]
|
|
459
|
-
}
|
|
460
|
-
};
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
336
|
function parseArguments(value) {
|
|
466
337
|
try {
|
|
467
338
|
const parsed = JSON.parse(value);
|
|
468
|
-
return parsed && typeof parsed
|
|
339
|
+
return parsed && "object" == typeof parsed && !Array.isArray(parsed) ? parsed : {};
|
|
469
340
|
} catch {
|
|
470
341
|
return {};
|
|
471
342
|
}
|
|
@@ -517,22 +388,17 @@ function toolIsError(content) {
|
|
|
517
388
|
}
|
|
518
389
|
}
|
|
519
390
|
function createPiContext(messages, tools, model, replay, historySummary, pageDelegationHistory = false) {
|
|
520
|
-
// pi-ai exposes one trusted systemPrompt rather than chronological system messages.
|
|
521
|
-
// Keep canonical checkpoints append-only, then consolidate them in their original order.
|
|
522
391
|
const system = [];
|
|
523
392
|
const piMessages = [];
|
|
524
393
|
selectModelHistory(messages, historySummary, {
|
|
525
394
|
pageDelegation: pageDelegationHistory
|
|
526
395
|
}).forEach(({ message, index })=>{
|
|
527
|
-
if (message.role
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
if (message.role === "user") {
|
|
532
|
-
const content = typeof message.content === "string" ? message.content : message.content.map((part)=>{
|
|
533
|
-
if (part.type === "text") return part;
|
|
396
|
+
if ("system" === message.role || "application_context" === message.role) return void system.push(message.content);
|
|
397
|
+
if ("user" === message.role) {
|
|
398
|
+
const content = "string" == typeof message.content ? message.content : message.content.map((part)=>{
|
|
399
|
+
if ("text" === part.type) return part;
|
|
534
400
|
if (!model.input.includes("image")) throw new AgentModelError("MODEL_INPUT_UNSUPPORTED", "The configured model does not support image input.");
|
|
535
|
-
if (part.source.type
|
|
401
|
+
if ("data" !== part.source.type) throw new AgentModelError("MODEL_INPUT_UNSUPPORTED", "Only inline image data is supported.");
|
|
536
402
|
return {
|
|
537
403
|
type: "image",
|
|
538
404
|
data: part.source.value,
|
|
@@ -546,25 +412,20 @@ function createPiContext(messages, tools, model, replay, historySummary, pageDel
|
|
|
546
412
|
});
|
|
547
413
|
return;
|
|
548
414
|
}
|
|
549
|
-
if (message.role
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
],
|
|
564
|
-
isError: toolIsError(message.content),
|
|
565
|
-
timestamp: Date.now()
|
|
566
|
-
});
|
|
567
|
-
}
|
|
415
|
+
if ("assistant" === message.role) return void piMessages.push(replay.get(index) ?? genericAssistant(message, model));
|
|
416
|
+
if ("tool" === message.role) piMessages.push({
|
|
417
|
+
role: "toolResult",
|
|
418
|
+
toolCallId: message.toolCallId,
|
|
419
|
+
toolName: message.name,
|
|
420
|
+
content: [
|
|
421
|
+
{
|
|
422
|
+
type: "text",
|
|
423
|
+
text: message.content
|
|
424
|
+
}
|
|
425
|
+
],
|
|
426
|
+
isError: toolIsError(message.content),
|
|
427
|
+
timestamp: Date.now()
|
|
428
|
+
});
|
|
568
429
|
});
|
|
569
430
|
const piTools = tools.map((tool)=>({
|
|
570
431
|
name: tool.name,
|
|
@@ -580,10 +441,10 @@ function createPiContext(messages, tools, model, replay, historySummary, pageDel
|
|
|
580
441
|
};
|
|
581
442
|
}
|
|
582
443
|
function fromPiAssistant(message) {
|
|
583
|
-
const text = message.content.filter((block)=>block.type
|
|
444
|
+
const text = message.content.filter((block)=>"text" === block.type).map((block)=>block.text).join("");
|
|
584
445
|
return {
|
|
585
446
|
content: text || null,
|
|
586
|
-
toolCalls: message.content.filter((block)=>block.type
|
|
447
|
+
toolCalls: message.content.filter((block)=>"toolCall" === block.type).map((block)=>({
|
|
587
448
|
id: block.id,
|
|
588
449
|
name: block.name,
|
|
589
450
|
arguments: JSON.stringify(block.arguments)
|
|
@@ -597,11 +458,6 @@ function fromPiAssistant(message) {
|
|
|
597
458
|
}
|
|
598
459
|
};
|
|
599
460
|
}
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
461
|
const DEFAULT_CAPABILITIES = {
|
|
606
462
|
reasoning: false,
|
|
607
463
|
input: [
|
|
@@ -615,7 +471,7 @@ function invalid(message) {
|
|
|
615
471
|
throw new AgentModelError("MODEL_CONFIG_INVALID", message);
|
|
616
472
|
}
|
|
617
473
|
function assertNonEmpty(value, name) {
|
|
618
|
-
if (typeof value
|
|
474
|
+
if ("string" != typeof value || !value.trim()) invalid(`${name} must be a non-empty string.`);
|
|
619
475
|
}
|
|
620
476
|
function normalizedBaseURL(value, fallback) {
|
|
621
477
|
const candidate = value ?? fallback;
|
|
@@ -628,9 +484,7 @@ function normalizedBaseURL(value, fallback) {
|
|
|
628
484
|
return invalid("baseURL must be absolute outside a browser environment.");
|
|
629
485
|
}
|
|
630
486
|
if (url.search || url.hash) invalid("baseURL must not contain a query or hash.");
|
|
631
|
-
if (url.protocol
|
|
632
|
-
invalid("baseURL must use http or https.");
|
|
633
|
-
}
|
|
487
|
+
if ("http:" !== url.protocol && "https:" !== url.protocol) invalid("baseURL must use http or https.");
|
|
634
488
|
if (url.username || url.password) invalid("baseURL must not contain credentials.");
|
|
635
489
|
url.pathname = url.pathname.replace(/\/+$/, "") || "/";
|
|
636
490
|
return url.toString().replace(/\/$/, "");
|
|
@@ -641,17 +495,14 @@ function hasAuthenticationHeader(headers) {
|
|
|
641
495
|
"x-api-key",
|
|
642
496
|
"x-goog-api-key"
|
|
643
497
|
]);
|
|
644
|
-
for (const [name, value] of Object.entries(headers ?? {})){
|
|
645
|
-
if (!authenticationHeaders.has(name.toLowerCase())) continue;
|
|
498
|
+
for (const [name, value] of Object.entries(headers ?? {}))if (authenticationHeaders.has(name.toLowerCase())) {
|
|
646
499
|
assertNonEmpty(value, `headers.${name}`);
|
|
647
500
|
return true;
|
|
648
501
|
}
|
|
649
502
|
return false;
|
|
650
503
|
}
|
|
651
504
|
function assertFiniteNumber(value, name, minimum) {
|
|
652
|
-
if (
|
|
653
|
-
invalid(`${name} must be a finite number greater than or equal to ${minimum}.`);
|
|
654
|
-
}
|
|
505
|
+
if (void 0 !== value && (!Number.isFinite(value) || value < minimum)) invalid(`${name} must be a finite number greater than or equal to ${minimum}.`);
|
|
655
506
|
}
|
|
656
507
|
function stripKeylessSecret(input, init) {
|
|
657
508
|
const headers = new Headers(init?.headers);
|
|
@@ -661,9 +512,7 @@ function stripKeylessSecret(input, init) {
|
|
|
661
512
|
"x-goog-api-key"
|
|
662
513
|
]){
|
|
663
514
|
const value = headers.get(name);
|
|
664
|
-
if (value === KEYLESS_GATEWAY_API_KEY || value === `Bearer ${KEYLESS_GATEWAY_API_KEY}`)
|
|
665
|
-
headers.delete(name);
|
|
666
|
-
}
|
|
515
|
+
if (value === KEYLESS_GATEWAY_API_KEY || value === `Bearer ${KEYLESS_GATEWAY_API_KEY}`) headers.delete(name);
|
|
667
516
|
}
|
|
668
517
|
let nextInput = input;
|
|
669
518
|
const rawURL = input instanceof Request ? input.url : String(input);
|
|
@@ -672,13 +521,9 @@ function stripKeylessSecret(input, init) {
|
|
|
672
521
|
for (const name of [
|
|
673
522
|
"key",
|
|
674
523
|
"api_key"
|
|
675
|
-
])
|
|
676
|
-
if (url.searchParams.get(name) === KEYLESS_GATEWAY_API_KEY) url.searchParams.delete(name);
|
|
677
|
-
}
|
|
524
|
+
])if (url.searchParams.get(name) === KEYLESS_GATEWAY_API_KEY) url.searchParams.delete(name);
|
|
678
525
|
nextInput = input instanceof Request ? new Request(url, input) : url;
|
|
679
|
-
} catch {
|
|
680
|
-
// Keep non-URL RequestInfo unchanged.
|
|
681
|
-
}
|
|
526
|
+
} catch {}
|
|
682
527
|
return [
|
|
683
528
|
nextInput,
|
|
684
529
|
{
|
|
@@ -696,28 +541,24 @@ function createKeylessFetch(fetchImpl) {
|
|
|
696
541
|
async function consumeStream(stream, onTextDelta, onReasoning) {
|
|
697
542
|
let result;
|
|
698
543
|
for await (const event of stream){
|
|
699
|
-
if (event.type
|
|
700
|
-
if (event.type
|
|
544
|
+
if ("text_delta" === event.type) onTextDelta?.(event.delta);
|
|
545
|
+
if ("thinking_start" === event.type) onReasoning?.({
|
|
701
546
|
type: "start"
|
|
702
547
|
});
|
|
703
|
-
if (event.type
|
|
548
|
+
if ("thinking_delta" === event.type) onReasoning?.({
|
|
704
549
|
type: "delta",
|
|
705
550
|
delta: event.delta
|
|
706
551
|
});
|
|
707
|
-
if (event.type
|
|
552
|
+
if ("thinking_end" === event.type) onReasoning?.({
|
|
708
553
|
type: "end"
|
|
709
554
|
});
|
|
710
|
-
if (event.type
|
|
711
|
-
if (event.type
|
|
712
|
-
if (event.reason
|
|
713
|
-
throw new DOMException("The model request was aborted.", "AbortError");
|
|
714
|
-
}
|
|
555
|
+
if ("done" === event.type) result = event.message;
|
|
556
|
+
if ("error" === event.type) {
|
|
557
|
+
if ("aborted" === event.reason) throw new DOMException("The model request was aborted.", "AbortError");
|
|
715
558
|
throw new AgentModelError("MODEL_REQUEST_FAILED", "The model request failed.");
|
|
716
559
|
}
|
|
717
560
|
}
|
|
718
|
-
if (!result)
|
|
719
|
-
throw new AgentModelError("INVALID_MODEL_RESPONSE", "Model stream ended without a final message.");
|
|
720
|
-
}
|
|
561
|
+
if (!result) throw new AgentModelError("INVALID_MODEL_RESPONSE", "Model stream ended without a final message.");
|
|
721
562
|
return result;
|
|
722
563
|
}
|
|
723
564
|
class PiModelBinding {
|
|
@@ -748,7 +589,7 @@ class PiModelBinding {
|
|
|
748
589
|
restoreReplay(replay, messages) {
|
|
749
590
|
if (!Array.isArray(replay)) throw new Error("Invalid model replay.");
|
|
750
591
|
for (const entry of replay){
|
|
751
|
-
const index = typeof entry?.messageId
|
|
592
|
+
const index = "string" == typeof entry?.messageId ? messages.findIndex((message)=>message.id === entry.messageId) : -1;
|
|
752
593
|
const canonical = messages[index];
|
|
753
594
|
const raw = entry?.message;
|
|
754
595
|
if (canonical?.role !== "assistant" || raw?.role !== "assistant" || !Array.isArray(raw.content)) throw new Error("Invalid replay message association.");
|
|
@@ -760,8 +601,8 @@ class PiModelBinding {
|
|
|
760
601
|
toolCalls: converted.toolCalls
|
|
761
602
|
}
|
|
762
603
|
]);
|
|
763
|
-
const finish = converted.toolCalls.length
|
|
764
|
-
const expectedContent = finish?.status === "completed" && typeof finish.output
|
|
604
|
+
const finish = 1 === converted.toolCalls.length && converted.toolCalls[0]?.name === "nxf_finish" ? JSON.parse(converted.toolCalls[0].arguments) : void 0;
|
|
605
|
+
const expectedContent = finish?.status === "completed" && "string" == typeof finish.output ? finish.output.trim() : converted.content;
|
|
765
606
|
if (JSON.stringify(converted.toolCalls) !== JSON.stringify(canonical.toolCalls) || expectedContent !== canonical.content) throw new Error("Replay does not match its assistant message.");
|
|
766
607
|
this.#replay.set(index + 1, structuredClone(raw));
|
|
767
608
|
}
|
|
@@ -789,10 +630,10 @@ function resolveModel(definition, config, baseURL) {
|
|
|
789
630
|
const catalogModel = definition.resolveCatalogModel?.(config.model);
|
|
790
631
|
const capabilities = config.capabilities;
|
|
791
632
|
return {
|
|
792
|
-
...definition.preserveCatalogCompat && catalogModel?.compat !==
|
|
633
|
+
...definition.preserveCatalogCompat && catalogModel?.compat !== void 0 ? {
|
|
793
634
|
compat: catalogModel.compat
|
|
794
635
|
} : {},
|
|
795
|
-
...catalogModel?.thinkingLevelMap ===
|
|
636
|
+
...catalogModel?.thinkingLevelMap === void 0 ? {} : {
|
|
796
637
|
thinkingLevelMap: catalogModel.thinkingLevelMap
|
|
797
638
|
},
|
|
798
639
|
id: config.model,
|
|
@@ -815,40 +656,32 @@ function resolveModel(definition, config, baseURL) {
|
|
|
815
656
|
};
|
|
816
657
|
}
|
|
817
658
|
function createProtocolModelConfig(definition, config) {
|
|
818
|
-
if (!config || typeof config
|
|
659
|
+
if (!config || "object" != typeof config) invalid("model config must be an object.");
|
|
819
660
|
assertNonEmpty(config.model, "model");
|
|
820
|
-
if (config.apiKey
|
|
821
|
-
if (hasAuthenticationHeader(config.headers) && config.apiKey)
|
|
822
|
-
|
|
823
|
-
}
|
|
824
|
-
if (definition.supportsCustomFetch === false && config.fetch) {
|
|
825
|
-
invalid(`Custom fetch is not supported for provider "${definition.provider}".`);
|
|
826
|
-
}
|
|
661
|
+
if (void 0 !== config.apiKey) assertNonEmpty(config.apiKey, "apiKey");
|
|
662
|
+
if (hasAuthenticationHeader(config.headers) && config.apiKey) invalid("apiKey and an authentication header cannot be configured together.");
|
|
663
|
+
if (false === definition.supportsCustomFetch && config.fetch) invalid(`Custom fetch is not supported for provider "${definition.provider}".`);
|
|
827
664
|
assertFiniteNumber(config.temperature, "temperature", 0);
|
|
828
665
|
assertFiniteNumber(config.maxTokens, "maxTokens", 1);
|
|
829
666
|
assertFiniteNumber(config.timeoutMs, "timeoutMs", 1);
|
|
830
667
|
assertFiniteNumber(config.maxRetries, "maxRetries", 0);
|
|
831
|
-
if (config.maxRetries
|
|
832
|
-
invalid("maxRetries must be an integer.");
|
|
833
|
-
}
|
|
668
|
+
if (void 0 !== config.maxRetries && !Number.isInteger(config.maxRetries)) invalid("maxRetries must be an integer.");
|
|
834
669
|
assertFiniteNumber(config.capabilities?.contextWindow, "capabilities.contextWindow", 1);
|
|
835
670
|
assertFiniteNumber(config.capabilities?.maxOutputTokens, "capabilities.maxOutputTokens", 1);
|
|
836
671
|
const baseURL = normalizedBaseURL(config.baseURL, definition.defaultBaseURL);
|
|
837
|
-
if ((
|
|
838
|
-
invalid("baseURL must be an API root and must not include the final endpoint.");
|
|
839
|
-
}
|
|
672
|
+
if (("openai-completions" === definition.api || "openai-responses" === definition.api) && /\/(?:chat\/completions|responses)$/i.test(new URL(baseURL).pathname)) invalid("baseURL must be an API root and must not include the final endpoint.");
|
|
840
673
|
const preparedConfig = {
|
|
841
674
|
...config,
|
|
842
675
|
baseURL,
|
|
843
|
-
...config.headers
|
|
676
|
+
...void 0 === config.headers ? {} : {
|
|
844
677
|
headers: {
|
|
845
678
|
...config.headers
|
|
846
679
|
}
|
|
847
680
|
},
|
|
848
|
-
...config.capabilities
|
|
681
|
+
...void 0 === config.capabilities ? {} : {
|
|
849
682
|
capabilities: {
|
|
850
683
|
...config.capabilities,
|
|
851
|
-
...config.capabilities.input
|
|
684
|
+
...void 0 === config.capabilities.input ? {} : {
|
|
852
685
|
input: [
|
|
853
686
|
...config.capabilities.input
|
|
854
687
|
]
|
|
@@ -866,30 +699,30 @@ function createProtocolModelConfig(definition, config) {
|
|
|
866
699
|
const model = resolveModel(definition, preparedConfig, baseURL);
|
|
867
700
|
const configuredFetch = preparedConfig.fetch ?? globalThis.fetch;
|
|
868
701
|
const options = {
|
|
869
|
-
...preparedConfig.temperature
|
|
702
|
+
...void 0 === preparedConfig.temperature ? {} : {
|
|
870
703
|
temperature: preparedConfig.temperature
|
|
871
704
|
},
|
|
872
|
-
...preparedConfig.maxTokens
|
|
705
|
+
...void 0 === preparedConfig.maxTokens ? {} : {
|
|
873
706
|
maxTokens: preparedConfig.maxTokens
|
|
874
707
|
},
|
|
875
|
-
...model.reasoning && preparedConfig.reasoning
|
|
708
|
+
...model.reasoning && void 0 !== preparedConfig.reasoning ? {
|
|
876
709
|
reasoning: preparedConfig.reasoning
|
|
877
710
|
} : {},
|
|
878
|
-
...preparedConfig.timeoutMs
|
|
711
|
+
...void 0 === preparedConfig.timeoutMs ? {} : {
|
|
879
712
|
timeoutMs: preparedConfig.timeoutMs
|
|
880
713
|
},
|
|
881
|
-
...preparedConfig.maxRetries
|
|
714
|
+
...void 0 === preparedConfig.maxRetries ? {} : {
|
|
882
715
|
maxRetries: preparedConfig.maxRetries
|
|
883
716
|
},
|
|
884
|
-
...preparedConfig.headers
|
|
717
|
+
...void 0 === preparedConfig.headers ? {} : {
|
|
885
718
|
headers: preparedConfig.headers
|
|
886
719
|
},
|
|
887
|
-
...definition.supportsCustomFetch
|
|
720
|
+
...false === definition.supportsCustomFetch || void 0 === preparedConfig.apiKey ? {} : {
|
|
888
721
|
fetch: configuredFetch
|
|
889
722
|
},
|
|
890
|
-
...preparedConfig.apiKey
|
|
723
|
+
...void 0 === preparedConfig.apiKey ? {
|
|
891
724
|
apiKey: KEYLESS_GATEWAY_API_KEY,
|
|
892
|
-
...definition.supportsCustomFetch
|
|
725
|
+
...false === definition.supportsCustomFetch ? {} : {
|
|
893
726
|
fetch: createKeylessFetch(configuredFetch)
|
|
894
727
|
}
|
|
895
728
|
} : {
|
|
@@ -900,5 +733,4 @@ function createProtocolModelConfig(definition, config) {
|
|
|
900
733
|
}
|
|
901
734
|
});
|
|
902
735
|
}
|
|
903
|
-
|
|
904
736
|
export { AgentModelError, AssistantMessageEventStream, createProtocolModelConfig, flattenModelCatalog, lazyApi };
|