@nexface/agent 0.1.20-alpha.1 → 0.1.20-alpha.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/dist/agent.d.ts +2 -0
- package/dist/agent.js +82 -79
- package/dist/ark/model.d.ts +10 -0
- package/dist/ark/model.js +113 -0
- package/dist/ark/state.d.ts +45 -0
- package/dist/ark/state.js +68 -0
- package/dist/ark/transport.d.ts +71 -0
- package/dist/ark/transport.js +397 -0
- package/dist/ark.d.ts +16 -0
- package/dist/ark.js +83 -0
- package/dist/model/binding.d.ts +2 -0
- package/dist/model/strict-tools.d.ts +5 -0
- package/dist/model/strict-tools.js +58 -0
- package/dist/models/k.js +151 -8
- package/dist/request.d.ts +2 -2
- package/dist/request.js +2 -2
- package/dist/shared/tool-proxy.d.ts +6 -0
- package/dist/shared/tool-proxy.js +25 -0
- package/package.json +9 -2
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { AgentModelError } from "../model/error.js";
|
|
2
|
+
import { canonical, submissionId } from "./state.js";
|
|
3
|
+
const baseUrl = "https://ark.cn-beijing.volces.com/api/v3";
|
|
4
|
+
export const pageToolBridge = {
|
|
5
|
+
type: "custom",
|
|
6
|
+
name: "nexface_call_page_tool",
|
|
7
|
+
description: "Execute a Nexface page tool. Use the exact name and input schema from the latest Nexface page tool catalog in the user message or tool result. The catalog replaces earlier catalogs, including after navigation. Use this bridge for page tools.",
|
|
8
|
+
input_schema: {
|
|
9
|
+
type: "object",
|
|
10
|
+
properties: {
|
|
11
|
+
name: { type: "string" },
|
|
12
|
+
input: { type: "object" },
|
|
13
|
+
progressLabel: {
|
|
14
|
+
type: "string",
|
|
15
|
+
description: "Briefly describe the action in the user's language without claiming success.",
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
required: ["name", "input"],
|
|
19
|
+
additionalProperties: false,
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
export function arkError(message) {
|
|
23
|
+
return new AgentModelError("MODEL_REQUEST_FAILED", message);
|
|
24
|
+
}
|
|
25
|
+
class ArkHttpError extends AgentModelError {
|
|
26
|
+
status;
|
|
27
|
+
constructor(status) {
|
|
28
|
+
super("MODEL_REQUEST_FAILED", `Ark request failed (HTTP ${status}).`);
|
|
29
|
+
this.status = status;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function record(value) {
|
|
33
|
+
if (value && typeof value === "object" && !Array.isArray(value))
|
|
34
|
+
return value;
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
function event(value) {
|
|
38
|
+
const item = record(value);
|
|
39
|
+
if (!item || typeof item.id !== "string" || !item.id || typeof item.type !== "string")
|
|
40
|
+
throw arkError("Ark returned an invalid session event.");
|
|
41
|
+
return item;
|
|
42
|
+
}
|
|
43
|
+
function textOf(content) {
|
|
44
|
+
if (typeof content === "string")
|
|
45
|
+
return content;
|
|
46
|
+
if (!Array.isArray(content))
|
|
47
|
+
return "";
|
|
48
|
+
return content
|
|
49
|
+
.map((part) => {
|
|
50
|
+
const block = record(part);
|
|
51
|
+
return block?.type === "text" && typeof block.text === "string" ? block.text : "";
|
|
52
|
+
})
|
|
53
|
+
.join("");
|
|
54
|
+
}
|
|
55
|
+
async function* frames(response) {
|
|
56
|
+
const reader = response.body?.getReader();
|
|
57
|
+
if (!reader)
|
|
58
|
+
throw arkError("Ark returned an empty event stream.");
|
|
59
|
+
const decoder = new TextDecoder();
|
|
60
|
+
let buffer = "";
|
|
61
|
+
try {
|
|
62
|
+
for (;;) {
|
|
63
|
+
const { done, value } = await reader.read();
|
|
64
|
+
if (done)
|
|
65
|
+
return;
|
|
66
|
+
buffer += decoder.decode(value, { stream: true });
|
|
67
|
+
// Ark can send the ready comment with a single newline.
|
|
68
|
+
const frameBoundary = /^:[^\r\n]*\r?\n|^\r?\n|\r?\n\r?\n/;
|
|
69
|
+
let separator = frameBoundary.exec(buffer);
|
|
70
|
+
while (separator) {
|
|
71
|
+
const frame = separator[0].startsWith(":")
|
|
72
|
+
? separator[0].trimEnd()
|
|
73
|
+
: buffer.slice(0, separator.index);
|
|
74
|
+
buffer = buffer.slice(separator.index + separator[0].length);
|
|
75
|
+
yield frame;
|
|
76
|
+
separator = frameBoundary.exec(buffer);
|
|
77
|
+
}
|
|
78
|
+
if (buffer.length > 4_000_000)
|
|
79
|
+
throw arkError("Ark event frame is too large.");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
void reader.cancel().catch(() => undefined);
|
|
84
|
+
reader.releaseLock();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function frameData(frame) {
|
|
88
|
+
return frame
|
|
89
|
+
.split(/\r?\n/)
|
|
90
|
+
.filter((line) => line.startsWith("data:"))
|
|
91
|
+
.map((line) => line.slice(5).replace(/^ /, ""))
|
|
92
|
+
.join("\n");
|
|
93
|
+
}
|
|
94
|
+
function matchesSubmission(observed, submitted) {
|
|
95
|
+
if (observed.type !== submitted.type || textOf(observed.content) !== textOf(submitted.content))
|
|
96
|
+
return false;
|
|
97
|
+
return (submitted.type === "user.message" ||
|
|
98
|
+
(observed.custom_tool_use_id === submitted.custom_tool_use_id &&
|
|
99
|
+
(observed.is_error === true) === submitted.is_error));
|
|
100
|
+
}
|
|
101
|
+
const activeContinuations = new Set();
|
|
102
|
+
export async function runArkTurn(options) {
|
|
103
|
+
const sessionId = options.checkpoint?.sessionId;
|
|
104
|
+
if (!sessionId)
|
|
105
|
+
return runArkTurnInSession(options);
|
|
106
|
+
if (activeContinuations.has(sessionId))
|
|
107
|
+
throw arkError("This Ark session already has a continuation in progress.");
|
|
108
|
+
activeContinuations.add(sessionId);
|
|
109
|
+
try {
|
|
110
|
+
return await runArkTurnInSession(options);
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
activeContinuations.delete(sessionId);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function runArkTurnInSession(options) {
|
|
117
|
+
const { signal } = options;
|
|
118
|
+
const previous = options.checkpoint;
|
|
119
|
+
const headers = { Authorization: `Bearer ${options.apiKey}` };
|
|
120
|
+
async function request(path, body, requestSignal = signal) {
|
|
121
|
+
const response = await fetch(baseUrl + path, {
|
|
122
|
+
method: body === undefined ? "GET" : "POST",
|
|
123
|
+
headers: {
|
|
124
|
+
...headers,
|
|
125
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
126
|
+
},
|
|
127
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
128
|
+
redirect: "error",
|
|
129
|
+
signal: requestSignal,
|
|
130
|
+
});
|
|
131
|
+
if (!response.ok) {
|
|
132
|
+
void response.body?.cancel().catch(() => undefined);
|
|
133
|
+
throw new ArkHttpError(response.status);
|
|
134
|
+
}
|
|
135
|
+
return response;
|
|
136
|
+
}
|
|
137
|
+
async function createSession() {
|
|
138
|
+
const response = await request(`/agents/${encodeURIComponent(options.agentId)}`);
|
|
139
|
+
const agent = record(await response.json());
|
|
140
|
+
if (!agent || (agent.tools !== undefined && !Array.isArray(agent.tools)))
|
|
141
|
+
throw arkError("Ark returned an invalid agent tool list.");
|
|
142
|
+
const tools = agent.tools ?? [];
|
|
143
|
+
const session = await request("/sessions", {
|
|
144
|
+
agent: {
|
|
145
|
+
type: "agent_with_overrides",
|
|
146
|
+
id: options.agentId,
|
|
147
|
+
...(Number.isInteger(agent.version) ? { version: agent.version } : {}),
|
|
148
|
+
tools: [
|
|
149
|
+
...tools.filter((tool) => record(tool)?.name !== pageToolBridge.name),
|
|
150
|
+
pageToolBridge,
|
|
151
|
+
],
|
|
152
|
+
},
|
|
153
|
+
environment_id: options.environmentId,
|
|
154
|
+
});
|
|
155
|
+
return record(await session.json())?.id;
|
|
156
|
+
}
|
|
157
|
+
const createdId = previous?.sessionId ?? (await createSession());
|
|
158
|
+
if (typeof createdId !== "string" || !createdId)
|
|
159
|
+
throw arkError("Ark did not return a session ID.");
|
|
160
|
+
const sessionId = createdId;
|
|
161
|
+
const path = `/sessions/${encodeURIComponent(sessionId)}/events`;
|
|
162
|
+
const submissions = options.submissions.map((item, index) => ({
|
|
163
|
+
...item,
|
|
164
|
+
id: submissionId(sessionId, previous?.stopId ?? "", String(index), canonical(item)),
|
|
165
|
+
}));
|
|
166
|
+
async function historySinceCheckpoint() {
|
|
167
|
+
const results = [];
|
|
168
|
+
const cursors = new Set();
|
|
169
|
+
let page;
|
|
170
|
+
for (;;) {
|
|
171
|
+
signal.throwIfAborted();
|
|
172
|
+
const query = new URLSearchParams({ limit: "100", order: "desc" });
|
|
173
|
+
if (page)
|
|
174
|
+
query.set("page", page);
|
|
175
|
+
const envelope = record(await (await request(`${path}?${query}`)).json());
|
|
176
|
+
if (!Array.isArray(envelope?.data))
|
|
177
|
+
throw arkError("Ark returned invalid session history.");
|
|
178
|
+
for (const value of envelope.data) {
|
|
179
|
+
const item = event(value);
|
|
180
|
+
if (item.id === previous?.stopId)
|
|
181
|
+
return results.reverse();
|
|
182
|
+
results.push(item);
|
|
183
|
+
}
|
|
184
|
+
const cursor = envelope.next_page;
|
|
185
|
+
if (cursor == null || cursor === "") {
|
|
186
|
+
if (previous)
|
|
187
|
+
throw arkError("Ark session checkpoint is unavailable. Start a new chat.");
|
|
188
|
+
return results.reverse();
|
|
189
|
+
}
|
|
190
|
+
if (typeof cursor !== "string" || cursors.has(cursor))
|
|
191
|
+
throw arkError("Ark returned an invalid history cursor.");
|
|
192
|
+
cursors.add(cursor);
|
|
193
|
+
page = cursor;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async function connect() {
|
|
197
|
+
const response = await fetch(baseUrl + path + "/stream", {
|
|
198
|
+
headers: { ...headers, Accept: "text/event-stream" },
|
|
199
|
+
signal,
|
|
200
|
+
redirect: "error",
|
|
201
|
+
});
|
|
202
|
+
if (!response.ok || !response.headers.get("content-type")?.includes("text/event-stream")) {
|
|
203
|
+
void response.body?.cancel().catch(() => undefined);
|
|
204
|
+
throw arkError(`Ark event stream failed (HTTP ${response.status}).`);
|
|
205
|
+
}
|
|
206
|
+
const stream = frames(response);
|
|
207
|
+
try {
|
|
208
|
+
for (;;) {
|
|
209
|
+
const next = await stream.next();
|
|
210
|
+
if (next.done)
|
|
211
|
+
throw arkError("Ark event stream closed before it was ready.");
|
|
212
|
+
if (next.value.split(/\r?\n/).some((line) => line.trim() === ": ready"))
|
|
213
|
+
return stream;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
await stream.return(undefined);
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
let stream = await connect();
|
|
222
|
+
let submitted = false;
|
|
223
|
+
let finished = false;
|
|
224
|
+
const seen = new Set();
|
|
225
|
+
const pending = new Map();
|
|
226
|
+
const replies = [];
|
|
227
|
+
let acceptedIds = [];
|
|
228
|
+
let started = false;
|
|
229
|
+
function consume(item) {
|
|
230
|
+
if (seen.has(item.id))
|
|
231
|
+
return;
|
|
232
|
+
seen.add(item.id);
|
|
233
|
+
if (acceptedIds.includes(item.id) || item.type === "session.status_running")
|
|
234
|
+
started = true;
|
|
235
|
+
if (item.type === "session.status_terminated" || item.type === "session.deleted")
|
|
236
|
+
throw arkError("Ark session ended. Start a new chat.");
|
|
237
|
+
if (item.type === "session.error" &&
|
|
238
|
+
record(record(item.error)?.retry_status)?.type === "terminal")
|
|
239
|
+
throw arkError("Ark reported a terminal session error.");
|
|
240
|
+
if (item.type === "agent.message") {
|
|
241
|
+
started = true;
|
|
242
|
+
const text = textOf(item.content);
|
|
243
|
+
if (text) {
|
|
244
|
+
options.onTextDelta?.(replies.length ? `\n\n${text}` : text);
|
|
245
|
+
replies.push(text);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (item.type === "agent.custom_tool_use") {
|
|
249
|
+
started = true;
|
|
250
|
+
const name = item.name;
|
|
251
|
+
if (typeof name !== "string")
|
|
252
|
+
throw arkError("Ark returned an invalid custom tool name.");
|
|
253
|
+
let input = item.input;
|
|
254
|
+
if (typeof input === "string") {
|
|
255
|
+
try {
|
|
256
|
+
input = JSON.parse(input);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
// The Agent reports malformed arguments as a failed tool result.
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
pending.set(item.id, { id: item.id, name, input });
|
|
263
|
+
}
|
|
264
|
+
if (!started || item.type !== "session.status_idle")
|
|
265
|
+
return;
|
|
266
|
+
const reason = record(item.stop_reason);
|
|
267
|
+
const checkpoint = { sessionId, stopId: item.id, pendingIds: [] };
|
|
268
|
+
if (reason?.type === "requires_action") {
|
|
269
|
+
if (!Array.isArray(reason.event_ids) || !reason.event_ids.length)
|
|
270
|
+
throw arkError("Ark did not identify the pending custom tool calls.");
|
|
271
|
+
const calls = reason.event_ids.map((id) => pending.get(id));
|
|
272
|
+
if (new Set(reason.event_ids).size !== calls.length || calls.some((call) => !call))
|
|
273
|
+
throw arkError("Ark is waiting for an unsupported or invalid tool action.");
|
|
274
|
+
checkpoint.pendingIds = calls.map((call) => call.id);
|
|
275
|
+
return { checkpoint, calls: calls, text: replies.join("\n\n") };
|
|
276
|
+
}
|
|
277
|
+
if (reason?.type !== "end_turn" || !replies.length)
|
|
278
|
+
throw arkError("Ark ended the turn without a final text response.");
|
|
279
|
+
return { checkpoint, calls: [], text: replies.join("\n\n") };
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
if (previous) {
|
|
283
|
+
const newer = await historySinceCheckpoint();
|
|
284
|
+
if (newer.some(({ type }) => type.startsWith("user.") ||
|
|
285
|
+
type === "session.status_running" ||
|
|
286
|
+
type === "session.status_idle" ||
|
|
287
|
+
type === "session.deleted" ||
|
|
288
|
+
type === "session.status_terminated"))
|
|
289
|
+
throw arkError("This Ark continuation has already advanced. Start a new chat.");
|
|
290
|
+
for (const { id } of newer)
|
|
291
|
+
seen.add(id);
|
|
292
|
+
}
|
|
293
|
+
submitted = true;
|
|
294
|
+
let recovered = [];
|
|
295
|
+
try {
|
|
296
|
+
const response = await request(path, { events: submissions });
|
|
297
|
+
const data = record(await response.json())?.data;
|
|
298
|
+
if (!Array.isArray(data) || data.length !== submissions.length)
|
|
299
|
+
throw new TypeError("Missing Ark event acknowledgements.");
|
|
300
|
+
acceptedIds = data.map((item, index) => {
|
|
301
|
+
const accepted = record(item);
|
|
302
|
+
const expected = submissions[index];
|
|
303
|
+
if (accepted?.id !== expected.id || accepted.type !== expected.type)
|
|
304
|
+
throw new TypeError("Ark did not echo the submitted event identity.");
|
|
305
|
+
return expected.id;
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
signal.throwIfAborted();
|
|
310
|
+
if (error instanceof ArkHttpError && error.status < 500)
|
|
311
|
+
throw error;
|
|
312
|
+
recovered = await historySinceCheckpoint();
|
|
313
|
+
const matches = submissions.map((submission) => recovered.filter((item) => item.id === submission.id && matchesSubmission(item, submission)));
|
|
314
|
+
if (matches.some((items) => items.length !== 1))
|
|
315
|
+
throw arkError("Ark could not confirm the submission. Check the action results before retrying.");
|
|
316
|
+
acceptedIds = matches.map(([item]) => item.id);
|
|
317
|
+
}
|
|
318
|
+
for (let reconnects = 0;; reconnects++) {
|
|
319
|
+
if (reconnects) {
|
|
320
|
+
await stream.return(undefined);
|
|
321
|
+
try {
|
|
322
|
+
stream = await connect();
|
|
323
|
+
recovered = await historySinceCheckpoint();
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
signal.throwIfAborted();
|
|
327
|
+
if (reconnects >= 2 || (error instanceof ArkHttpError && error.status < 500))
|
|
328
|
+
throw error;
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// Historical events and the live stream can overlap after reconnection.
|
|
333
|
+
for (const item of recovered) {
|
|
334
|
+
const result = consume(item);
|
|
335
|
+
if (result) {
|
|
336
|
+
finished = true;
|
|
337
|
+
return result;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
for (;;) {
|
|
341
|
+
let next;
|
|
342
|
+
try {
|
|
343
|
+
next = await stream.next();
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
signal.throwIfAborted();
|
|
347
|
+
break;
|
|
348
|
+
}
|
|
349
|
+
if (next.done)
|
|
350
|
+
break;
|
|
351
|
+
const data = frameData(next.value);
|
|
352
|
+
if (data === "[DONE]")
|
|
353
|
+
break;
|
|
354
|
+
if (!data)
|
|
355
|
+
continue;
|
|
356
|
+
const item = event(JSON.parse(data));
|
|
357
|
+
const result = consume(item);
|
|
358
|
+
if (result) {
|
|
359
|
+
finished = true;
|
|
360
|
+
return result;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (reconnects >= 2)
|
|
364
|
+
throw arkError("Ark event stream disconnected. Check the action results before retrying.");
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
await stream.return(undefined);
|
|
369
|
+
if (submitted && !finished && signal.aborted) {
|
|
370
|
+
try {
|
|
371
|
+
const response = await request(path, { events: [{ type: "user.interrupt" }] }, AbortSignal.timeout(2_000));
|
|
372
|
+
void response.body?.cancel().catch(() => undefined);
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
// Cancellation of the hosted run is best effort after the local request ends.
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
export function toolSubmission(id, receipt) {
|
|
381
|
+
const payload = record(JSON.parse(receipt.content));
|
|
382
|
+
if (!payload)
|
|
383
|
+
throw arkError("The Nexface tool receipt is invalid.");
|
|
384
|
+
const result = record(payload.result);
|
|
385
|
+
const native = receipt.name === "nxf_getSnapshot" || receipt.name === "nxf_executeAction";
|
|
386
|
+
const nativeFailure = native && result?.ok === false;
|
|
387
|
+
const toolError = record(payload.error);
|
|
388
|
+
const error = toolError ?? (nativeFailure ? record(result.error) : undefined);
|
|
389
|
+
if (error?.code === "EXECUTION_OUTCOME_UNKNOWN" || error?.code === "TOOL_CANCELLED")
|
|
390
|
+
throw arkError("The page operation was cancelled or its outcome is unknown. Start a new chat.");
|
|
391
|
+
return {
|
|
392
|
+
type: "user.custom_tool_result",
|
|
393
|
+
custom_tool_use_id: id,
|
|
394
|
+
content: [{ type: "text", text: canonical(toolError ?? payload.result ?? null) }],
|
|
395
|
+
is_error: !!error || nativeFailure,
|
|
396
|
+
};
|
|
397
|
+
}
|
package/dist/ark.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type RunAgentInput } from "@ag-ui/core";
|
|
2
|
+
/**
|
|
3
|
+
* Creates a server-only AG-UI handler for Ark Managed Agents.
|
|
4
|
+
* The caller authenticates the request and supplies a stable principal key.
|
|
5
|
+
* The browser supplies the current page tool catalog.
|
|
6
|
+
* @beta
|
|
7
|
+
*/
|
|
8
|
+
export declare function createArkRunHandler(options: {
|
|
9
|
+
apiKey: string;
|
|
10
|
+
agentId: string;
|
|
11
|
+
environmentId: string;
|
|
12
|
+
continuationSecret: string;
|
|
13
|
+
}): (input: RunAgentInput, runOptions: {
|
|
14
|
+
principalKey: string;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}) => Promise<Response>;
|
package/dist/ark.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { EventType, RunAgentInputSchema } from "@ag-ui/core";
|
|
2
|
+
import { createAgent } from "./agent.js";
|
|
3
|
+
import { arkModel, userText } from "./ark/model.js";
|
|
4
|
+
import { canonical, continuationKey, newConversation, signState, verifyState, } from "./ark/state.js";
|
|
5
|
+
import { decodeRequest, runResponse } from "./request.js";
|
|
6
|
+
function invalidRun(message) {
|
|
7
|
+
const code = message === newConversation ? "CHAT_RECOVERY_UNAVAILABLE" : "INVALID_RUN_INPUT";
|
|
8
|
+
const event = { type: EventType.RUN_ERROR, code, message };
|
|
9
|
+
return new Response(`data: ${JSON.stringify(event)}\n\n`, {
|
|
10
|
+
headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform" },
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Creates a server-only AG-UI handler for Ark Managed Agents.
|
|
15
|
+
* The caller authenticates the request and supplies a stable principal key.
|
|
16
|
+
* The browser supplies the current page tool catalog.
|
|
17
|
+
* @beta
|
|
18
|
+
*/
|
|
19
|
+
export function createArkRunHandler(options) {
|
|
20
|
+
const key = continuationKey(options.continuationSecret);
|
|
21
|
+
const apiKey = options.apiKey?.trim();
|
|
22
|
+
const agentId = options.agentId?.trim();
|
|
23
|
+
const environmentId = options.environmentId?.trim();
|
|
24
|
+
if (!apiKey || !agentId || !environmentId)
|
|
25
|
+
throw new Error("Ark API key, Agent ID and Environment ID are required.");
|
|
26
|
+
return async (value, { principalKey, signal }) => {
|
|
27
|
+
if (typeof principalKey !== "string" || !principalKey.trim())
|
|
28
|
+
return invalidRun("An authenticated principal is required.");
|
|
29
|
+
signal?.throwIfAborted();
|
|
30
|
+
const principal = canonical([principalKey, agentId, environmentId]);
|
|
31
|
+
let input;
|
|
32
|
+
let decoded;
|
|
33
|
+
try {
|
|
34
|
+
input = RunAgentInputSchema.parse(value);
|
|
35
|
+
const state = input.state;
|
|
36
|
+
const hasState = state != null &&
|
|
37
|
+
(typeof state !== "object" || Array.isArray(state) || Object.keys(state).length > 0);
|
|
38
|
+
if (hasState)
|
|
39
|
+
verifyState(key, principal, input.threadId, state, input.messages);
|
|
40
|
+
else if (input.resume || input.messages.length !== 1)
|
|
41
|
+
throw new Error(newConversation);
|
|
42
|
+
decoded = decodeRequest(input);
|
|
43
|
+
if (decoded.resume?.status === "cancelled")
|
|
44
|
+
throw new Error(newConversation);
|
|
45
|
+
if (decoded.resume?.status === "resolved") {
|
|
46
|
+
if (!decoded.toolResult || decoded.newMessages.length || !decoded.continuation?.pending)
|
|
47
|
+
throw new Error("The page tool receipt is invalid. Start a new chat.");
|
|
48
|
+
}
|
|
49
|
+
else if (decoded.newMessages.length !== 1 || !userText(decoded.newMessages[0])) {
|
|
50
|
+
throw new Error("Ark requires one new text user message.");
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
return invalidRun(error instanceof Error ? error.message : "Invalid Ark run request.");
|
|
55
|
+
}
|
|
56
|
+
const model = arkModel({
|
|
57
|
+
apiKey,
|
|
58
|
+
agentId,
|
|
59
|
+
environmentId,
|
|
60
|
+
definitions: decoded.tools,
|
|
61
|
+
contexts: decoded.contexts,
|
|
62
|
+
});
|
|
63
|
+
const agent = createAgent({ model });
|
|
64
|
+
let messages;
|
|
65
|
+
return runResponse(agent.runRequest(input, signal ? { signal } : {}), (event) => {
|
|
66
|
+
if (event.type === EventType.MESSAGES_SNAPSHOT)
|
|
67
|
+
messages = event.messages;
|
|
68
|
+
if (event.type === EventType.RUN_STARTED)
|
|
69
|
+
return {
|
|
70
|
+
...event,
|
|
71
|
+
metadata: {
|
|
72
|
+
...event.metadata,
|
|
73
|
+
nexface: { ...event.metadata?.nexface, appendOnly: true },
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
if (event.type === EventType.STATE_SNAPSHOT && messages) {
|
|
77
|
+
const { nexface } = event.snapshot;
|
|
78
|
+
return { ...event, snapshot: signState(key, principal, input.threadId, nexface, messages) };
|
|
79
|
+
}
|
|
80
|
+
return event;
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
}
|
package/dist/model/binding.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export interface ModelBindingRequest {
|
|
|
8
8
|
agentId: string;
|
|
9
9
|
historySummary?: HistorySummary;
|
|
10
10
|
pageDelegationHistory?: boolean;
|
|
11
|
+
omitRuntimeCatalog?: boolean;
|
|
11
12
|
onTextDelta?(delta: string): void;
|
|
12
13
|
onReasoning?(event: {
|
|
13
14
|
type: "start" | "delta" | "end";
|
|
@@ -16,6 +17,7 @@ export interface ModelBindingRequest {
|
|
|
16
17
|
}
|
|
17
18
|
export interface ModelBinding {
|
|
18
19
|
readonly info: AgentModelInfo;
|
|
20
|
+
readonly managesHistory?: boolean;
|
|
19
21
|
exportReplay?(messages: readonly AgentMessage[]): unknown;
|
|
20
22
|
restoreReplay?(replay: unknown, messages: readonly AgentMessage[]): void;
|
|
21
23
|
complete(request: ModelBindingRequest): Promise<AgentModelResponse>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { JsonSchema } from "@nexface/tools";
|
|
2
|
+
/** Convert only the model-facing schema; Runtime continues validating the original. */
|
|
3
|
+
export declare function strictToolSchema(schema: JsonSchema, path: string): Record<string, unknown>;
|
|
4
|
+
/** Remove only null placeholders introduced for originally optional, non-null fields. */
|
|
5
|
+
export declare function restoreToolArguments(value: unknown, schema: JsonSchema): unknown;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { AgentModelError } from "./error.js";
|
|
2
|
+
/** Convert only the model-facing schema; Runtime continues validating the original. */
|
|
3
|
+
export function strictToolSchema(schema, path) {
|
|
4
|
+
const fail = (reason) => {
|
|
5
|
+
throw new AgentModelError("MODEL_CONFIG_INVALID", `Strict tool schema at ${path}: ${reason}`);
|
|
6
|
+
};
|
|
7
|
+
if (!schema.type)
|
|
8
|
+
fail("an explicit type is required.");
|
|
9
|
+
if (schema.enum?.some((value) => value !== null && typeof value === "object")) {
|
|
10
|
+
fail("object and array enum values are not supported.");
|
|
11
|
+
}
|
|
12
|
+
// Strict providers can reject this keyword even when its value is false.
|
|
13
|
+
// Keep the entire tool non-strict rather than dropping its Runtime constraint.
|
|
14
|
+
if (schema.uniqueItems !== undefined)
|
|
15
|
+
fail("uniqueItems is not supported.");
|
|
16
|
+
const result = { ...schema };
|
|
17
|
+
if (schema.type === "object") {
|
|
18
|
+
if (schema.additionalProperties !== false) {
|
|
19
|
+
fail("objects must set additionalProperties to false.");
|
|
20
|
+
}
|
|
21
|
+
const required = new Set(schema.required ?? []);
|
|
22
|
+
const properties = Object.entries(schema.properties ?? {}).map(([key, child]) => {
|
|
23
|
+
if (!required.has(key) && child.type === "null") {
|
|
24
|
+
fail(`optional null field "${key}" cannot distinguish omission from an explicit null.`);
|
|
25
|
+
}
|
|
26
|
+
const converted = strictToolSchema(child, `${path}.${key}`);
|
|
27
|
+
return [key, required.has(key) ? converted : { anyOf: [converted, { type: "null" }] }];
|
|
28
|
+
});
|
|
29
|
+
result.properties = Object.fromEntries(properties);
|
|
30
|
+
result.required = properties.map(([key]) => key);
|
|
31
|
+
}
|
|
32
|
+
else if (schema.type === "array") {
|
|
33
|
+
if (!schema.items)
|
|
34
|
+
fail("arrays must define items.");
|
|
35
|
+
result.items = strictToolSchema(schema.items, `${path}[]`);
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
/** Remove only null placeholders introduced for originally optional, non-null fields. */
|
|
40
|
+
export function restoreToolArguments(value, schema) {
|
|
41
|
+
if (schema.type === "array" && Array.isArray(value) && schema.items) {
|
|
42
|
+
return value.map((item) => restoreToolArguments(item, schema.items));
|
|
43
|
+
}
|
|
44
|
+
if (schema.type !== "object" || !value || typeof value !== "object" || Array.isArray(value)) {
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
const required = new Set(schema.required ?? []);
|
|
48
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => {
|
|
49
|
+
const child = schema.properties && Object.hasOwn(schema.properties, key)
|
|
50
|
+
? schema.properties[key]
|
|
51
|
+
: undefined;
|
|
52
|
+
if (!child)
|
|
53
|
+
return [[key, entry]];
|
|
54
|
+
if (entry === null && !required.has(key) && child.type !== "null")
|
|
55
|
+
return [];
|
|
56
|
+
return [[key, restoreToolArguments(entry, child)]];
|
|
57
|
+
}));
|
|
58
|
+
}
|