@nexface/agent 0.1.20-alpha.1 → 0.1.21
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 +94 -81
- package/dist/ark/model.d.ts +11 -0
- package/dist/ark/model.js +119 -0
- package/dist/ark/state.d.ts +45 -0
- package/dist/ark/state.js +68 -0
- package/dist/ark/transport.d.ts +73 -0
- package/dist/ark/transport.js +572 -0
- package/dist/ark.d.ts +16 -0
- package/dist/ark.js +101 -0
- package/dist/model/binding.d.ts +6 -1
- 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,73 @@
|
|
|
1
|
+
import { AgentModelError } from "../model/error.js";
|
|
2
|
+
export declare const pageToolBridge: {
|
|
3
|
+
readonly type: "custom";
|
|
4
|
+
readonly name: "nexface_call_page_tool";
|
|
5
|
+
readonly 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.";
|
|
6
|
+
readonly input_schema: {
|
|
7
|
+
readonly type: "object";
|
|
8
|
+
readonly properties: {
|
|
9
|
+
readonly name: {
|
|
10
|
+
readonly type: "string";
|
|
11
|
+
};
|
|
12
|
+
readonly input: {
|
|
13
|
+
readonly type: "object";
|
|
14
|
+
};
|
|
15
|
+
readonly progressLabel: {
|
|
16
|
+
readonly type: "string";
|
|
17
|
+
readonly description: "Briefly describe the action in the user's language without claiming success.";
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
readonly required: readonly ["name", "input"];
|
|
21
|
+
readonly additionalProperties: false;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
type TextBlock = {
|
|
25
|
+
type: "text";
|
|
26
|
+
text: string;
|
|
27
|
+
};
|
|
28
|
+
type Submission = {
|
|
29
|
+
type: "user.message";
|
|
30
|
+
content: TextBlock[];
|
|
31
|
+
} | {
|
|
32
|
+
type: "user.custom_tool_result";
|
|
33
|
+
custom_tool_use_id: string;
|
|
34
|
+
content: TextBlock[];
|
|
35
|
+
is_error: boolean;
|
|
36
|
+
};
|
|
37
|
+
export interface ArkToolCall {
|
|
38
|
+
id: string;
|
|
39
|
+
name: string;
|
|
40
|
+
input: unknown;
|
|
41
|
+
}
|
|
42
|
+
export interface ArkCheckpoint {
|
|
43
|
+
sessionId: string;
|
|
44
|
+
stopId: string;
|
|
45
|
+
pendingIds: string[];
|
|
46
|
+
interruptedWhileIdle?: true;
|
|
47
|
+
}
|
|
48
|
+
type ArkTurn = {
|
|
49
|
+
checkpoint?: ArkCheckpoint;
|
|
50
|
+
calls: ArkToolCall[];
|
|
51
|
+
text: string;
|
|
52
|
+
stopped?: true;
|
|
53
|
+
submitted?: false;
|
|
54
|
+
};
|
|
55
|
+
export declare function arkError(message: string): AgentModelError;
|
|
56
|
+
export declare function record(value: unknown): Record<string, unknown> | undefined;
|
|
57
|
+
export declare function runArkTurn(options: Omit<Parameters<typeof runArkTurnInSession>[0], "stopDeadline">): Promise<ArkTurn>;
|
|
58
|
+
declare function runArkTurnInSession(options: {
|
|
59
|
+
apiKey: string;
|
|
60
|
+
agentId: string;
|
|
61
|
+
environmentId: string;
|
|
62
|
+
checkpoint?: ArkCheckpoint;
|
|
63
|
+
submissions: Submission[];
|
|
64
|
+
signal: AbortSignal;
|
|
65
|
+
stopSignal: AbortSignal;
|
|
66
|
+
stopDeadline: AbortSignal;
|
|
67
|
+
onTextDelta?: (text: string) => void;
|
|
68
|
+
}): Promise<ArkTurn>;
|
|
69
|
+
export declare function toolSubmission(id: string, receipt: {
|
|
70
|
+
content: string;
|
|
71
|
+
name?: string;
|
|
72
|
+
}): Submission;
|
|
73
|
+
export {};
|
|
@@ -0,0 +1,572 @@
|
|
|
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
|
+
function readyIdle(item) {
|
|
23
|
+
const reason = record(item.stop_reason)?.type;
|
|
24
|
+
return (item.type === "session.status_idle" && (reason === "end_turn" || reason === "retries_exhausted"));
|
|
25
|
+
}
|
|
26
|
+
function advancesTurn(item, allowReadyIdle = false) {
|
|
27
|
+
const { type } = item;
|
|
28
|
+
return (type.startsWith("user.") ||
|
|
29
|
+
type === "session.status_running" ||
|
|
30
|
+
type === "session.status_rescheduled" ||
|
|
31
|
+
(type === "session.status_idle" && !(allowReadyIdle && readyIdle(item))) ||
|
|
32
|
+
type === "session.deleted" ||
|
|
33
|
+
type === "session.status_terminated" ||
|
|
34
|
+
(type === "session.error" && record(record(item.error)?.retry_status)?.type === "terminal"));
|
|
35
|
+
}
|
|
36
|
+
export function arkError(message) {
|
|
37
|
+
return new AgentModelError("MODEL_REQUEST_FAILED", message);
|
|
38
|
+
}
|
|
39
|
+
class ArkHttpError extends AgentModelError {
|
|
40
|
+
status;
|
|
41
|
+
constructor(status) {
|
|
42
|
+
super("MODEL_REQUEST_FAILED", `Ark request failed (HTTP ${status}).`);
|
|
43
|
+
this.status = status;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function record(value) {
|
|
47
|
+
if (value && typeof value === "object" && !Array.isArray(value))
|
|
48
|
+
return value;
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
function event(value) {
|
|
52
|
+
const item = record(value);
|
|
53
|
+
if (!item || typeof item.id !== "string" || !item.id || typeof item.type !== "string")
|
|
54
|
+
throw arkError("Ark returned an invalid session event.");
|
|
55
|
+
return item;
|
|
56
|
+
}
|
|
57
|
+
function textOf(content) {
|
|
58
|
+
if (typeof content === "string")
|
|
59
|
+
return content;
|
|
60
|
+
if (!Array.isArray(content))
|
|
61
|
+
return "";
|
|
62
|
+
return content
|
|
63
|
+
.map((part) => {
|
|
64
|
+
const block = record(part);
|
|
65
|
+
return block?.type === "text" && typeof block.text === "string" ? block.text : "";
|
|
66
|
+
})
|
|
67
|
+
.join("");
|
|
68
|
+
}
|
|
69
|
+
async function* frames(response, signal) {
|
|
70
|
+
const reader = response.body?.getReader();
|
|
71
|
+
if (!reader)
|
|
72
|
+
throw arkError("Ark returned an empty event stream.");
|
|
73
|
+
const decoder = new TextDecoder();
|
|
74
|
+
let buffer = "";
|
|
75
|
+
const cancel = () => void reader.cancel().catch(() => undefined);
|
|
76
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
77
|
+
try {
|
|
78
|
+
signal.throwIfAborted();
|
|
79
|
+
for (;;) {
|
|
80
|
+
const { done, value } = await reader.read();
|
|
81
|
+
if (done)
|
|
82
|
+
return;
|
|
83
|
+
buffer += decoder.decode(value, { stream: true });
|
|
84
|
+
// Ark can send the ready comment with a single newline.
|
|
85
|
+
const frameBoundary = /^:[^\r\n]*\r?\n|^\r?\n|\r?\n\r?\n/;
|
|
86
|
+
let separator = frameBoundary.exec(buffer);
|
|
87
|
+
while (separator) {
|
|
88
|
+
const frame = separator[0].startsWith(":")
|
|
89
|
+
? separator[0].trimEnd()
|
|
90
|
+
: buffer.slice(0, separator.index);
|
|
91
|
+
buffer = buffer.slice(separator.index + separator[0].length);
|
|
92
|
+
yield frame;
|
|
93
|
+
separator = frameBoundary.exec(buffer);
|
|
94
|
+
}
|
|
95
|
+
if (buffer.length > 4_000_000)
|
|
96
|
+
throw arkError("Ark event frame is too large.");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
signal.removeEventListener("abort", cancel);
|
|
101
|
+
cancel();
|
|
102
|
+
reader.releaseLock();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function frameData(frame) {
|
|
106
|
+
return frame
|
|
107
|
+
.split(/\r?\n/)
|
|
108
|
+
.filter((line) => line.startsWith("data:"))
|
|
109
|
+
.map((line) => line.slice(5).replace(/^ /, ""))
|
|
110
|
+
.join("\n");
|
|
111
|
+
}
|
|
112
|
+
function matchesSubmission(observed, submitted) {
|
|
113
|
+
if (observed.type !== submitted.type || textOf(observed.content) !== textOf(submitted.content))
|
|
114
|
+
return false;
|
|
115
|
+
return (submitted.type === "user.message" ||
|
|
116
|
+
(observed.custom_tool_use_id === submitted.custom_tool_use_id &&
|
|
117
|
+
(observed.is_error === true) === submitted.is_error));
|
|
118
|
+
}
|
|
119
|
+
const activeContinuations = new Set();
|
|
120
|
+
const stopTimeoutMs = 8_000;
|
|
121
|
+
export async function runArkTurn(options) {
|
|
122
|
+
const sessionId = options.checkpoint?.sessionId;
|
|
123
|
+
if (sessionId && activeContinuations.has(sessionId))
|
|
124
|
+
throw arkError("This Ark session already has a continuation in progress.");
|
|
125
|
+
if (sessionId)
|
|
126
|
+
activeContinuations.add(sessionId);
|
|
127
|
+
const deadline = new AbortController();
|
|
128
|
+
let timer;
|
|
129
|
+
const startDeadline = () => {
|
|
130
|
+
timer = setTimeout(() => deadline.abort(arkError("The Ark stop could not be confirmed before the server deadline.")), stopTimeoutMs);
|
|
131
|
+
};
|
|
132
|
+
if (options.stopSignal.aborted)
|
|
133
|
+
startDeadline();
|
|
134
|
+
else
|
|
135
|
+
options.stopSignal.addEventListener("abort", startDeadline, { once: true });
|
|
136
|
+
try {
|
|
137
|
+
return await runArkTurnInSession({ ...options, stopDeadline: deadline.signal });
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
clearTimeout(timer);
|
|
141
|
+
options.stopSignal.removeEventListener("abort", startDeadline);
|
|
142
|
+
if (sessionId)
|
|
143
|
+
activeContinuations.delete(sessionId);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async function runArkTurnInSession(options) {
|
|
147
|
+
const signal = AbortSignal.any([options.signal, options.stopDeadline]);
|
|
148
|
+
const previous = options.checkpoint;
|
|
149
|
+
const streamSignal = AbortSignal.any([signal, options.stopSignal]);
|
|
150
|
+
const stoppedBeforeSubmission = () => {
|
|
151
|
+
if (previous?.pendingIds.length)
|
|
152
|
+
throw arkError("Ark is still waiting for the pending tool results.");
|
|
153
|
+
return {
|
|
154
|
+
...(previous ? { checkpoint: previous } : {}),
|
|
155
|
+
calls: [],
|
|
156
|
+
text: "",
|
|
157
|
+
stopped: true,
|
|
158
|
+
submitted: false,
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
if (!previous && options.stopSignal.aborted)
|
|
162
|
+
return stoppedBeforeSubmission();
|
|
163
|
+
const headers = { Authorization: `Bearer ${options.apiKey}` };
|
|
164
|
+
async function request(path, body, requestSignal = signal) {
|
|
165
|
+
const response = await fetch(baseUrl + path, {
|
|
166
|
+
method: body === undefined ? "GET" : "POST",
|
|
167
|
+
headers: {
|
|
168
|
+
...headers,
|
|
169
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
170
|
+
},
|
|
171
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
172
|
+
redirect: "error",
|
|
173
|
+
signal: requestSignal,
|
|
174
|
+
});
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
void response.body?.cancel().catch(() => undefined);
|
|
177
|
+
throw new ArkHttpError(response.status);
|
|
178
|
+
}
|
|
179
|
+
return response;
|
|
180
|
+
}
|
|
181
|
+
async function createSession() {
|
|
182
|
+
const response = await request(`/agents/${encodeURIComponent(options.agentId)}`, undefined, streamSignal);
|
|
183
|
+
const agent = record(await response.json());
|
|
184
|
+
if (!agent || (agent.tools !== undefined && !Array.isArray(agent.tools)))
|
|
185
|
+
throw arkError("Ark returned an invalid agent tool list.");
|
|
186
|
+
if (options.stopSignal.aborted)
|
|
187
|
+
return;
|
|
188
|
+
const tools = agent.tools ?? [];
|
|
189
|
+
const session = await request("/sessions", {
|
|
190
|
+
agent: {
|
|
191
|
+
type: "agent_with_overrides",
|
|
192
|
+
id: options.agentId,
|
|
193
|
+
...(Number.isInteger(agent.version) ? { version: agent.version } : {}),
|
|
194
|
+
tools: [
|
|
195
|
+
...tools.filter((tool) => record(tool)?.name !== pageToolBridge.name),
|
|
196
|
+
pageToolBridge,
|
|
197
|
+
],
|
|
198
|
+
},
|
|
199
|
+
environment_id: options.environmentId,
|
|
200
|
+
}, streamSignal);
|
|
201
|
+
return record(await session.json())?.id;
|
|
202
|
+
}
|
|
203
|
+
let createdId;
|
|
204
|
+
try {
|
|
205
|
+
createdId = previous?.sessionId ?? (await createSession());
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
signal.throwIfAborted();
|
|
209
|
+
if (options.stopSignal.aborted)
|
|
210
|
+
return stoppedBeforeSubmission();
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
if (!previous && options.stopSignal.aborted)
|
|
214
|
+
return stoppedBeforeSubmission();
|
|
215
|
+
if (typeof createdId !== "string" || !createdId)
|
|
216
|
+
throw arkError("Ark did not return a session ID.");
|
|
217
|
+
const sessionId = createdId;
|
|
218
|
+
const path = `/sessions/${encodeURIComponent(sessionId)}/events`;
|
|
219
|
+
const submissions = options.submissions.map((item, index) => ({
|
|
220
|
+
...item,
|
|
221
|
+
id: submissionId(sessionId, previous?.stopId ?? "", String(index), canonical(item)),
|
|
222
|
+
}));
|
|
223
|
+
async function historySinceCheckpoint(requestSignal = signal) {
|
|
224
|
+
const results = [];
|
|
225
|
+
const cursors = new Set();
|
|
226
|
+
let page;
|
|
227
|
+
for (;;) {
|
|
228
|
+
requestSignal.throwIfAborted();
|
|
229
|
+
const query = new URLSearchParams({ limit: "100", order: "desc" });
|
|
230
|
+
if (page)
|
|
231
|
+
query.set("page", page);
|
|
232
|
+
const envelope = record(await (await request(`${path}?${query}`, undefined, requestSignal)).json());
|
|
233
|
+
if (!Array.isArray(envelope?.data))
|
|
234
|
+
throw arkError("Ark returned invalid session history.");
|
|
235
|
+
for (const value of envelope.data) {
|
|
236
|
+
const item = event(value);
|
|
237
|
+
if (item.id === previous?.stopId)
|
|
238
|
+
return results.reverse();
|
|
239
|
+
results.push(item);
|
|
240
|
+
}
|
|
241
|
+
const cursor = envelope.next_page;
|
|
242
|
+
if (cursor == null || cursor === "") {
|
|
243
|
+
if (previous)
|
|
244
|
+
throw arkError("Ark session checkpoint is unavailable. Start a new chat.");
|
|
245
|
+
return results.reverse();
|
|
246
|
+
}
|
|
247
|
+
if (typeof cursor !== "string" || cursors.has(cursor))
|
|
248
|
+
throw arkError("Ark returned an invalid history cursor.");
|
|
249
|
+
cursors.add(cursor);
|
|
250
|
+
page = cursor;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async function connect() {
|
|
254
|
+
const response = await fetch(baseUrl + path + "/stream", {
|
|
255
|
+
headers: { ...headers, Accept: "text/event-stream" },
|
|
256
|
+
signal: streamSignal,
|
|
257
|
+
redirect: "error",
|
|
258
|
+
});
|
|
259
|
+
if (!response.ok || !response.headers.get("content-type")?.includes("text/event-stream")) {
|
|
260
|
+
void response.body?.cancel().catch(() => undefined);
|
|
261
|
+
throw arkError(`Ark event stream failed (HTTP ${response.status}).`);
|
|
262
|
+
}
|
|
263
|
+
const stream = frames(response, streamSignal);
|
|
264
|
+
try {
|
|
265
|
+
for (;;) {
|
|
266
|
+
const next = await stream.next();
|
|
267
|
+
if (next.done)
|
|
268
|
+
throw arkError("Ark event stream closed before it was ready.");
|
|
269
|
+
if (next.value.split(/\r?\n/).some((line) => line.trim() === ": ready"))
|
|
270
|
+
return stream;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
catch (error) {
|
|
274
|
+
await stream.return(undefined);
|
|
275
|
+
throw error;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
let stream;
|
|
279
|
+
let submitted = false;
|
|
280
|
+
let finished = false;
|
|
281
|
+
const seen = new Set();
|
|
282
|
+
const pending = new Map();
|
|
283
|
+
const replies = [];
|
|
284
|
+
let acceptedIds = [];
|
|
285
|
+
let started = false;
|
|
286
|
+
const stopId = submissionId(sessionId, "interrupt", ...submissions.map(({ id }) => id));
|
|
287
|
+
const isProcessedStop = (item) => item.id === stopId &&
|
|
288
|
+
item.type === "user.interrupt" &&
|
|
289
|
+
typeof item.processed_at === "string" &&
|
|
290
|
+
item.processed_at.length > 0;
|
|
291
|
+
let stopRequested = false;
|
|
292
|
+
const waitForHistory = () => new Promise((resolve) => setTimeout(resolve, 200));
|
|
293
|
+
function consume(item) {
|
|
294
|
+
if (seen.has(item.id))
|
|
295
|
+
return;
|
|
296
|
+
seen.add(item.id);
|
|
297
|
+
if (acceptedIds.includes(item.id) || item.type === "session.status_running")
|
|
298
|
+
started = true;
|
|
299
|
+
if (item.type === "session.status_terminated" || item.type === "session.deleted")
|
|
300
|
+
throw arkError("Ark session ended. Start a new chat.");
|
|
301
|
+
if (item.type === "session.error" &&
|
|
302
|
+
record(record(item.error)?.retry_status)?.type === "terminal")
|
|
303
|
+
throw arkError("Ark reported a terminal session error.");
|
|
304
|
+
if (item.type === "agent.message") {
|
|
305
|
+
started = true;
|
|
306
|
+
const text = textOf(item.content);
|
|
307
|
+
if (text && !options.stopSignal.aborted) {
|
|
308
|
+
options.onTextDelta?.(replies.length ? `\n\n${text}` : text);
|
|
309
|
+
replies.push(text);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (item.type === "agent.custom_tool_use") {
|
|
313
|
+
started = true;
|
|
314
|
+
const name = item.name;
|
|
315
|
+
if (typeof name !== "string")
|
|
316
|
+
throw arkError("Ark returned an invalid custom tool name.");
|
|
317
|
+
let input = item.input;
|
|
318
|
+
if (typeof input === "string") {
|
|
319
|
+
try {
|
|
320
|
+
input = JSON.parse(input);
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
// The Agent reports malformed arguments as a failed tool result.
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
pending.set(item.id, { id: item.id, name, input });
|
|
327
|
+
}
|
|
328
|
+
if (!started || item.type !== "session.status_idle")
|
|
329
|
+
return;
|
|
330
|
+
const reason = record(item.stop_reason);
|
|
331
|
+
const checkpoint = { sessionId, stopId: item.id, pendingIds: [] };
|
|
332
|
+
if (reason?.type === "requires_action") {
|
|
333
|
+
if (!Array.isArray(reason.event_ids) || !reason.event_ids.length)
|
|
334
|
+
throw arkError("Ark did not identify the pending custom tool calls.");
|
|
335
|
+
const calls = reason.event_ids.map((id) => pending.get(id));
|
|
336
|
+
if (new Set(reason.event_ids).size !== calls.length || calls.some((call) => !call))
|
|
337
|
+
throw arkError("Ark is waiting for an unsupported or invalid tool action.");
|
|
338
|
+
checkpoint.pendingIds = calls.map((call) => call.id);
|
|
339
|
+
return { checkpoint, calls: calls, text: replies.join("\n\n") };
|
|
340
|
+
}
|
|
341
|
+
if (reason?.type !== "end_turn" || !replies.length)
|
|
342
|
+
throw arkError("Ark ended the turn without a final text response.");
|
|
343
|
+
return { checkpoint, calls: [], text: replies.join("\n\n") };
|
|
344
|
+
}
|
|
345
|
+
async function recoverStop() {
|
|
346
|
+
signal.throwIfAborted();
|
|
347
|
+
stopRequested = true;
|
|
348
|
+
try {
|
|
349
|
+
const response = await request(path, { events: [{ id: stopId, type: "user.interrupt" }] }, AbortSignal.any([options.stopDeadline, AbortSignal.timeout(2_000)]));
|
|
350
|
+
void response.body?.cancel().catch(() => undefined);
|
|
351
|
+
}
|
|
352
|
+
catch (error) {
|
|
353
|
+
signal.throwIfAborted();
|
|
354
|
+
if (error instanceof ArkHttpError && error.status < 500)
|
|
355
|
+
throw error;
|
|
356
|
+
}
|
|
357
|
+
for (;;) {
|
|
358
|
+
let history;
|
|
359
|
+
try {
|
|
360
|
+
history = await historySinceCheckpoint();
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
signal.throwIfAborted();
|
|
364
|
+
if (!(error instanceof TypeError || (error instanceof ArkHttpError && error.status >= 500)))
|
|
365
|
+
throw error;
|
|
366
|
+
await waitForHistory();
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
const stop = history.findIndex(isProcessedStop);
|
|
370
|
+
if (stop >= 0) {
|
|
371
|
+
const newer = history.slice(stop + 1);
|
|
372
|
+
if (newer.some(({ type }) => type.startsWith("user.")))
|
|
373
|
+
throw arkError("This Ark continuation has already advanced. Start a new chat.");
|
|
374
|
+
const latest = [...newer].reverse().find((item) => advancesTurn(item));
|
|
375
|
+
const idle = latest ??
|
|
376
|
+
history
|
|
377
|
+
.slice(0, stop)
|
|
378
|
+
.reverse()
|
|
379
|
+
.find((item) => advancesTurn(item));
|
|
380
|
+
if (idle && readyIdle(idle)) {
|
|
381
|
+
finished = true;
|
|
382
|
+
return {
|
|
383
|
+
checkpoint: {
|
|
384
|
+
sessionId,
|
|
385
|
+
stopId: latest ? idle.id : stopId,
|
|
386
|
+
pendingIds: [],
|
|
387
|
+
...(!latest ? { interruptedWhileIdle: true } : {}),
|
|
388
|
+
},
|
|
389
|
+
calls: [],
|
|
390
|
+
text: replies.join("\n\n"),
|
|
391
|
+
stopped: true,
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
if (latest &&
|
|
395
|
+
latest.type !== "session.status_running" &&
|
|
396
|
+
latest.type !== "session.status_rescheduled")
|
|
397
|
+
throw arkError("Ark stopped without confirming that the session can accept new messages.");
|
|
398
|
+
}
|
|
399
|
+
await waitForHistory();
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
try {
|
|
403
|
+
if (previous) {
|
|
404
|
+
const newer = await historySinceCheckpoint();
|
|
405
|
+
if (newer.some((item) => advancesTurn(item, previous.interruptedWhileIdle)))
|
|
406
|
+
throw arkError("This Ark continuation has already advanced. Start a new chat.");
|
|
407
|
+
for (const { id } of newer)
|
|
408
|
+
seen.add(id);
|
|
409
|
+
}
|
|
410
|
+
if (options.stopSignal.aborted)
|
|
411
|
+
return stoppedBeforeSubmission();
|
|
412
|
+
try {
|
|
413
|
+
stream = await connect();
|
|
414
|
+
}
|
|
415
|
+
catch (error) {
|
|
416
|
+
signal.throwIfAborted();
|
|
417
|
+
if (options.stopSignal.aborted)
|
|
418
|
+
return stoppedBeforeSubmission();
|
|
419
|
+
throw error;
|
|
420
|
+
}
|
|
421
|
+
if (options.stopSignal.aborted)
|
|
422
|
+
return stoppedBeforeSubmission();
|
|
423
|
+
submitted = true;
|
|
424
|
+
const submission = new AbortController();
|
|
425
|
+
const submissionSignal = AbortSignal.any([signal, submission.signal]);
|
|
426
|
+
const matchesHistory = (history) => submissions.every((expected) => history.filter((item) => item.id === expected.id && matchesSubmission(item, expected))
|
|
427
|
+
.length === 1);
|
|
428
|
+
const acknowledge = async () => {
|
|
429
|
+
try {
|
|
430
|
+
const response = await request(path, { events: submissions }, submissionSignal);
|
|
431
|
+
const data = record(await response.json())?.data;
|
|
432
|
+
if (!Array.isArray(data) ||
|
|
433
|
+
data.length !== submissions.length ||
|
|
434
|
+
submissions.some(({ id, type }, index) => data[index]?.id !== id || data[index]?.type !== type))
|
|
435
|
+
throw new TypeError("Ark did not echo the submitted event identities.");
|
|
436
|
+
return [];
|
|
437
|
+
}
|
|
438
|
+
catch (error) {
|
|
439
|
+
submissionSignal.throwIfAborted();
|
|
440
|
+
if (error instanceof ArkHttpError && error.status < 500)
|
|
441
|
+
throw error;
|
|
442
|
+
if (options.stopSignal.aborted)
|
|
443
|
+
return verifyWhenStopping;
|
|
444
|
+
try {
|
|
445
|
+
const history = await historySinceCheckpoint(submissionSignal);
|
|
446
|
+
if (matchesHistory(history))
|
|
447
|
+
return history;
|
|
448
|
+
}
|
|
449
|
+
catch (historyError) {
|
|
450
|
+
submissionSignal.throwIfAborted();
|
|
451
|
+
if (!options.stopSignal.aborted)
|
|
452
|
+
throw historyError;
|
|
453
|
+
}
|
|
454
|
+
if (options.stopSignal.aborted)
|
|
455
|
+
return verifyWhenStopping;
|
|
456
|
+
throw arkError("Ark could not confirm the submission. Check the action results before retrying.");
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
let checkOnStop;
|
|
460
|
+
const stopped = new Promise((resolve) => {
|
|
461
|
+
checkOnStop = resolve;
|
|
462
|
+
});
|
|
463
|
+
options.stopSignal.addEventListener("abort", checkOnStop, { once: true });
|
|
464
|
+
if (options.stopSignal.aborted)
|
|
465
|
+
checkOnStop();
|
|
466
|
+
// Ark can accept the submission even while the HTTP acknowledgement is delayed.
|
|
467
|
+
const verifyWhenStopping = stopped.then(async () => {
|
|
468
|
+
for (;;) {
|
|
469
|
+
try {
|
|
470
|
+
const history = await historySinceCheckpoint(submissionSignal);
|
|
471
|
+
if (matchesHistory(history))
|
|
472
|
+
return history;
|
|
473
|
+
}
|
|
474
|
+
catch {
|
|
475
|
+
submissionSignal.throwIfAborted();
|
|
476
|
+
}
|
|
477
|
+
await waitForHistory();
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
let recovered;
|
|
481
|
+
try {
|
|
482
|
+
recovered = await Promise.race([acknowledge(), verifyWhenStopping]);
|
|
483
|
+
acceptedIds = submissions.map(({ id }) => id);
|
|
484
|
+
}
|
|
485
|
+
finally {
|
|
486
|
+
options.stopSignal.removeEventListener("abort", checkOnStop);
|
|
487
|
+
submission.abort();
|
|
488
|
+
}
|
|
489
|
+
for (let reconnects = 0; !options.stopSignal.aborted; reconnects++) {
|
|
490
|
+
if (reconnects) {
|
|
491
|
+
await stream.return(undefined);
|
|
492
|
+
try {
|
|
493
|
+
stream = await connect();
|
|
494
|
+
recovered = await historySinceCheckpoint(streamSignal);
|
|
495
|
+
}
|
|
496
|
+
catch (error) {
|
|
497
|
+
signal.throwIfAborted();
|
|
498
|
+
if (options.stopSignal.aborted)
|
|
499
|
+
break;
|
|
500
|
+
if (reconnects >= 2 || (error instanceof ArkHttpError && error.status < 500))
|
|
501
|
+
throw error;
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
for (const item of recovered) {
|
|
506
|
+
if (options.stopSignal.aborted)
|
|
507
|
+
break;
|
|
508
|
+
const result = consume(item);
|
|
509
|
+
if (result) {
|
|
510
|
+
finished = true;
|
|
511
|
+
return result;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
while (!options.stopSignal.aborted) {
|
|
515
|
+
let next;
|
|
516
|
+
try {
|
|
517
|
+
next = await stream.next();
|
|
518
|
+
}
|
|
519
|
+
catch {
|
|
520
|
+
signal.throwIfAborted();
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
if (next.done || options.stopSignal.aborted)
|
|
524
|
+
break;
|
|
525
|
+
const data = frameData(next.value);
|
|
526
|
+
if (data === "[DONE]")
|
|
527
|
+
break;
|
|
528
|
+
if (!data)
|
|
529
|
+
continue;
|
|
530
|
+
const result = consume(event(JSON.parse(data)));
|
|
531
|
+
if (result) {
|
|
532
|
+
finished = true;
|
|
533
|
+
return result;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
signal.throwIfAborted();
|
|
537
|
+
if (!options.stopSignal.aborted && reconnects >= 2)
|
|
538
|
+
throw arkError("Ark event stream disconnected. Check the action results before retrying.");
|
|
539
|
+
}
|
|
540
|
+
return await recoverStop();
|
|
541
|
+
}
|
|
542
|
+
finally {
|
|
543
|
+
await stream?.return(undefined);
|
|
544
|
+
if (submitted && !finished && options.signal.aborted && !stopRequested) {
|
|
545
|
+
try {
|
|
546
|
+
const response = await request(path, { events: [{ type: "user.interrupt" }] }, AbortSignal.timeout(2_000));
|
|
547
|
+
void response.body?.cancel().catch(() => undefined);
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
// Cancellation of the hosted run is best effort after the local request ends.
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
export function toolSubmission(id, receipt) {
|
|
556
|
+
const payload = record(JSON.parse(receipt.content));
|
|
557
|
+
if (!payload)
|
|
558
|
+
throw arkError("The Nexface tool receipt is invalid.");
|
|
559
|
+
const result = record(payload.result);
|
|
560
|
+
const native = receipt.name === "nxf_getSnapshot" || receipt.name === "nxf_executeAction";
|
|
561
|
+
const nativeFailure = native && result?.ok === false;
|
|
562
|
+
const toolError = record(payload.error);
|
|
563
|
+
const error = toolError ?? (nativeFailure ? record(result.error) : undefined);
|
|
564
|
+
if (error?.code === "EXECUTION_OUTCOME_UNKNOWN" || error?.code === "TOOL_CANCELLED")
|
|
565
|
+
throw arkError("The page operation was cancelled or its outcome is unknown. Start a new chat.");
|
|
566
|
+
return {
|
|
567
|
+
type: "user.custom_tool_result",
|
|
568
|
+
custom_tool_use_id: id,
|
|
569
|
+
content: [{ type: "text", text: canonical(toolError ?? payload.result ?? null) }],
|
|
570
|
+
is_error: !!error || nativeFailure,
|
|
571
|
+
};
|
|
572
|
+
}
|
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>;
|