@nexface/agent 0.1.20-alpha.3 → 0.1.21-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.js CHANGED
@@ -1803,9 +1803,17 @@ class Nexface {
1803
1803
  ]),
1804
1804
  }
1805
1805
  : options;
1806
- // A request without registered server tools can execute tools only via client handoffs.
1806
+ const clientToolExecutionOnly = this.#registered.size === 0 && !this.#toolRuntime;
1807
+ const serverToolExecutionReadOnly = !this.#toolRuntime &&
1808
+ this.#registered.size > 0 &&
1809
+ [...this.#registered.values()].every(({ definition }) => definition.effect === "read");
1807
1810
  const startMetadata = this.#requestIdentity
1808
- ? { nexface: { clientToolExecutionOnly: this.#registered.size === 0 && !this.#toolRuntime } }
1811
+ ? {
1812
+ nexface: {
1813
+ clientToolExecutionOnly,
1814
+ ...(serverToolExecutionReadOnly ? { serverToolExecutionReadOnly: true } : {}),
1815
+ },
1816
+ }
1809
1817
  : undefined;
1810
1818
  return new AgentRunStream(id, this.#requestIdentity?.threadId ?? this.id, runOptions, async (emit, signal) => {
1811
1819
  const onAbort = () => operation?.abort.abort(signal.reason);
@@ -2094,6 +2102,8 @@ class Nexface {
2094
2102
  text.finish(response.content);
2095
2103
  const call = response.toolCalls[0];
2096
2104
  const output = response.content?.trim() ?? "";
2105
+ if (response.stopped && !call && !output)
2106
+ return { outcome: { type: "success" }, output };
2097
2107
  if (!call && !output) {
2098
2108
  throw new AgentError("INVALID_MODEL_RESPONSE", "Model returned neither a message nor a tool call.");
2099
2109
  }
@@ -7,4 +7,5 @@ export declare function arkModel(options: {
7
7
  environmentId: string;
8
8
  definitions: readonly AgentToolDefinition[];
9
9
  contexts: readonly AgentContextEntry[];
10
+ stopSignal: AbortSignal;
10
11
  }): import("../index.js").AgentModelConfig;
package/dist/ark/model.js CHANGED
@@ -37,6 +37,7 @@ export function arkModel(options) {
37
37
  sessionId: state.sessionId,
38
38
  stopId: state.stopId,
39
39
  pendingIds: state.pendingIds,
40
+ ...(state.interruptedWhileIdle === true ? { interruptedWhileIdle: true } : {}),
40
41
  };
41
42
  browserSkillSent = state.browserSkillSent === true;
42
43
  },
@@ -85,11 +86,12 @@ export function arkModel(options) {
85
86
  environmentId: options.environmentId,
86
87
  submissions,
87
88
  signal,
89
+ stopSignal: options.stopSignal,
88
90
  ...(checkpoint ? { checkpoint } : {}),
89
91
  ...(onTextDelta ? { onTextDelta } : {}),
90
92
  });
91
93
  checkpoint = turn.checkpoint;
92
- browserSkillSent ||= sendBrowserSkill;
94
+ browserSkillSent ||= sendBrowserSkill && turn.submitted !== false;
93
95
  const toolCalls = turn.calls.map(({ id, name: arkName, input: arkInput }) => {
94
96
  const envelope = arkName === pageToolBridge.name ? record(arkInput) : undefined;
95
97
  const { name, input, progressLabel } = envelope ?? {};
@@ -105,7 +107,11 @@ export function arkModel(options) {
105
107
  arguments: JSON.stringify({ name, input, progressLabel }),
106
108
  };
107
109
  });
108
- return { content: turn.text || null, toolCalls };
110
+ return {
111
+ content: turn.text || null,
112
+ toolCalls,
113
+ ...(turn.stopped ? { stopped: true } : {}),
114
+ };
109
115
  },
110
116
  };
111
117
  },
@@ -43,14 +43,18 @@ export interface ArkCheckpoint {
43
43
  sessionId: string;
44
44
  stopId: string;
45
45
  pendingIds: string[];
46
+ interruptedWhileIdle?: true;
46
47
  }
47
- export declare function arkError(message: string): AgentModelError;
48
- export declare function record(value: unknown): Record<string, unknown> | undefined;
49
- export declare function runArkTurn(options: Parameters<typeof runArkTurnInSession>[0]): Promise<{
50
- checkpoint: ArkCheckpoint;
48
+ type ArkTurn = {
49
+ checkpoint?: ArkCheckpoint;
51
50
  calls: ArkToolCall[];
52
51
  text: string;
53
- }>;
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>;
54
58
  declare function runArkTurnInSession(options: {
55
59
  apiKey: string;
56
60
  agentId: string;
@@ -58,12 +62,10 @@ declare function runArkTurnInSession(options: {
58
62
  checkpoint?: ArkCheckpoint;
59
63
  submissions: Submission[];
60
64
  signal: AbortSignal;
65
+ stopSignal: AbortSignal;
66
+ stopDeadline: AbortSignal;
61
67
  onTextDelta?: (text: string) => void;
62
- }): Promise<{
63
- checkpoint: ArkCheckpoint;
64
- calls: ArkToolCall[];
65
- text: string;
66
- }>;
68
+ }): Promise<ArkTurn>;
67
69
  export declare function toolSubmission(id: string, receipt: {
68
70
  content: string;
69
71
  name?: string;
@@ -19,6 +19,20 @@ export const pageToolBridge = {
19
19
  additionalProperties: false,
20
20
  },
21
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
+ }
22
36
  export function arkError(message) {
23
37
  return new AgentModelError("MODEL_REQUEST_FAILED", message);
24
38
  }
@@ -52,13 +66,16 @@ function textOf(content) {
52
66
  })
53
67
  .join("");
54
68
  }
55
- async function* frames(response) {
69
+ async function* frames(response, signal) {
56
70
  const reader = response.body?.getReader();
57
71
  if (!reader)
58
72
  throw arkError("Ark returned an empty event stream.");
59
73
  const decoder = new TextDecoder();
60
74
  let buffer = "";
75
+ const cancel = () => void reader.cancel().catch(() => undefined);
76
+ signal.addEventListener("abort", cancel, { once: true });
61
77
  try {
78
+ signal.throwIfAborted();
62
79
  for (;;) {
63
80
  const { done, value } = await reader.read();
64
81
  if (done)
@@ -80,7 +97,8 @@ async function* frames(response) {
80
97
  }
81
98
  }
82
99
  finally {
83
- void reader.cancel().catch(() => undefined);
100
+ signal.removeEventListener("abort", cancel);
101
+ cancel();
84
102
  reader.releaseLock();
85
103
  }
86
104
  }
@@ -99,23 +117,49 @@ function matchesSubmission(observed, submitted) {
99
117
  (observed.is_error === true) === submitted.is_error));
100
118
  }
101
119
  const activeContinuations = new Set();
120
+ const stopTimeoutMs = 8_000;
102
121
  export async function runArkTurn(options) {
103
122
  const sessionId = options.checkpoint?.sessionId;
104
- if (!sessionId)
105
- return runArkTurnInSession(options);
106
- if (activeContinuations.has(sessionId))
123
+ if (sessionId && activeContinuations.has(sessionId))
107
124
  throw arkError("This Ark session already has a continuation in progress.");
108
- activeContinuations.add(sessionId);
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 });
109
136
  try {
110
- return await runArkTurnInSession(options);
137
+ return await runArkTurnInSession({ ...options, stopDeadline: deadline.signal });
111
138
  }
112
139
  finally {
113
- activeContinuations.delete(sessionId);
140
+ clearTimeout(timer);
141
+ options.stopSignal.removeEventListener("abort", startDeadline);
142
+ if (sessionId)
143
+ activeContinuations.delete(sessionId);
114
144
  }
115
145
  }
116
146
  async function runArkTurnInSession(options) {
117
- const { signal } = options;
147
+ const signal = AbortSignal.any([options.signal, options.stopDeadline]);
118
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();
119
163
  const headers = { Authorization: `Bearer ${options.apiKey}` };
120
164
  async function request(path, body, requestSignal = signal) {
121
165
  const response = await fetch(baseUrl + path, {
@@ -135,10 +179,12 @@ async function runArkTurnInSession(options) {
135
179
  return response;
136
180
  }
137
181
  async function createSession() {
138
- const response = await request(`/agents/${encodeURIComponent(options.agentId)}`);
182
+ const response = await request(`/agents/${encodeURIComponent(options.agentId)}`, undefined, streamSignal);
139
183
  const agent = record(await response.json());
140
184
  if (!agent || (agent.tools !== undefined && !Array.isArray(agent.tools)))
141
185
  throw arkError("Ark returned an invalid agent tool list.");
186
+ if (options.stopSignal.aborted)
187
+ return;
142
188
  const tools = agent.tools ?? [];
143
189
  const session = await request("/sessions", {
144
190
  agent: {
@@ -151,10 +197,21 @@ async function runArkTurnInSession(options) {
151
197
  ],
152
198
  },
153
199
  environment_id: options.environmentId,
154
- });
200
+ }, streamSignal);
155
201
  return record(await session.json())?.id;
156
202
  }
157
- const createdId = previous?.sessionId ?? (await createSession());
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();
158
215
  if (typeof createdId !== "string" || !createdId)
159
216
  throw arkError("Ark did not return a session ID.");
160
217
  const sessionId = createdId;
@@ -163,16 +220,16 @@ async function runArkTurnInSession(options) {
163
220
  ...item,
164
221
  id: submissionId(sessionId, previous?.stopId ?? "", String(index), canonical(item)),
165
222
  }));
166
- async function historySinceCheckpoint() {
223
+ async function historySinceCheckpoint(requestSignal = signal) {
167
224
  const results = [];
168
225
  const cursors = new Set();
169
226
  let page;
170
227
  for (;;) {
171
- signal.throwIfAborted();
228
+ requestSignal.throwIfAborted();
172
229
  const query = new URLSearchParams({ limit: "100", order: "desc" });
173
230
  if (page)
174
231
  query.set("page", page);
175
- const envelope = record(await (await request(`${path}?${query}`)).json());
232
+ const envelope = record(await (await request(`${path}?${query}`, undefined, requestSignal)).json());
176
233
  if (!Array.isArray(envelope?.data))
177
234
  throw arkError("Ark returned invalid session history.");
178
235
  for (const value of envelope.data) {
@@ -196,14 +253,14 @@ async function runArkTurnInSession(options) {
196
253
  async function connect() {
197
254
  const response = await fetch(baseUrl + path + "/stream", {
198
255
  headers: { ...headers, Accept: "text/event-stream" },
199
- signal,
256
+ signal: streamSignal,
200
257
  redirect: "error",
201
258
  });
202
259
  if (!response.ok || !response.headers.get("content-type")?.includes("text/event-stream")) {
203
260
  void response.body?.cancel().catch(() => undefined);
204
261
  throw arkError(`Ark event stream failed (HTTP ${response.status}).`);
205
262
  }
206
- const stream = frames(response);
263
+ const stream = frames(response, streamSignal);
207
264
  try {
208
265
  for (;;) {
209
266
  const next = await stream.next();
@@ -218,7 +275,7 @@ async function runArkTurnInSession(options) {
218
275
  throw error;
219
276
  }
220
277
  }
221
- let stream = await connect();
278
+ let stream;
222
279
  let submitted = false;
223
280
  let finished = false;
224
281
  const seen = new Set();
@@ -226,6 +283,13 @@ async function runArkTurnInSession(options) {
226
283
  const replies = [];
227
284
  let acceptedIds = [];
228
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));
229
293
  function consume(item) {
230
294
  if (seen.has(item.id))
231
295
  return;
@@ -240,7 +304,7 @@ async function runArkTurnInSession(options) {
240
304
  if (item.type === "agent.message") {
241
305
  started = true;
242
306
  const text = textOf(item.content);
243
- if (text) {
307
+ if (text && !options.stopSignal.aborted) {
244
308
  options.onTextDelta?.(replies.length ? `\n\n${text}` : text);
245
309
  replies.push(text);
246
310
  }
@@ -278,66 +342,176 @@ async function runArkTurnInSession(options) {
278
342
  throw arkError("Ark ended the turn without a final text response.");
279
343
  return { checkpoint, calls: [], text: replies.join("\n\n") };
280
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
+ }
281
402
  try {
282
403
  if (previous) {
283
404
  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"))
405
+ if (newer.some((item) => advancesTurn(item, previous.interruptedWhileIdle)))
289
406
  throw arkError("This Ark continuation has already advanced. Start a new chat.");
290
407
  for (const { id } of newer)
291
408
  seen.add(id);
292
409
  }
293
- submitted = true;
294
- let recovered = [];
410
+ if (options.stopSignal.aborted)
411
+ return stoppedBeforeSubmission();
295
412
  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
- });
413
+ stream = await connect();
307
414
  }
308
415
  catch (error) {
309
416
  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))
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;
315
456
  throw arkError("Ark could not confirm the submission. Check the action results before retrying.");
316
- acceptedIds = matches.map(([item]) => item.id);
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);
317
484
  }
318
- for (let reconnects = 0;; reconnects++) {
485
+ finally {
486
+ options.stopSignal.removeEventListener("abort", checkOnStop);
487
+ submission.abort();
488
+ }
489
+ for (let reconnects = 0; !options.stopSignal.aborted; reconnects++) {
319
490
  if (reconnects) {
320
491
  await stream.return(undefined);
321
492
  try {
322
493
  stream = await connect();
323
- recovered = await historySinceCheckpoint();
494
+ recovered = await historySinceCheckpoint(streamSignal);
324
495
  }
325
496
  catch (error) {
326
497
  signal.throwIfAborted();
498
+ if (options.stopSignal.aborted)
499
+ break;
327
500
  if (reconnects >= 2 || (error instanceof ArkHttpError && error.status < 500))
328
501
  throw error;
329
502
  continue;
330
503
  }
331
504
  }
332
- // Historical events and the live stream can overlap after reconnection.
333
505
  for (const item of recovered) {
506
+ if (options.stopSignal.aborted)
507
+ break;
334
508
  const result = consume(item);
335
509
  if (result) {
336
510
  finished = true;
337
511
  return result;
338
512
  }
339
513
  }
340
- for (;;) {
514
+ while (!options.stopSignal.aborted) {
341
515
  let next;
342
516
  try {
343
517
  next = await stream.next();
@@ -346,27 +520,28 @@ async function runArkTurnInSession(options) {
346
520
  signal.throwIfAborted();
347
521
  break;
348
522
  }
349
- if (next.done)
523
+ if (next.done || options.stopSignal.aborted)
350
524
  break;
351
525
  const data = frameData(next.value);
352
526
  if (data === "[DONE]")
353
527
  break;
354
528
  if (!data)
355
529
  continue;
356
- const item = event(JSON.parse(data));
357
- const result = consume(item);
530
+ const result = consume(event(JSON.parse(data)));
358
531
  if (result) {
359
532
  finished = true;
360
533
  return result;
361
534
  }
362
535
  }
363
- if (reconnects >= 2)
536
+ signal.throwIfAborted();
537
+ if (!options.stopSignal.aborted && reconnects >= 2)
364
538
  throw arkError("Ark event stream disconnected. Check the action results before retrying.");
365
539
  }
540
+ return await recoverStop();
366
541
  }
367
542
  finally {
368
- await stream.return(undefined);
369
- if (submitted && !finished && signal.aborted) {
543
+ await stream?.return(undefined);
544
+ if (submitted && !finished && options.signal.aborted && !stopRequested) {
370
545
  try {
371
546
  const response = await request(path, { events: [{ type: "user.interrupt" }] }, AbortSignal.timeout(2_000));
372
547
  void response.body?.cancel().catch(() => undefined);
package/dist/ark.js CHANGED
@@ -23,6 +23,7 @@ export function createArkRunHandler(options) {
23
23
  const environmentId = options.environmentId?.trim();
24
24
  if (!apiKey || !agentId || !environmentId)
25
25
  throw new Error("Ark API key, Agent ID and Environment ID are required.");
26
+ const activeRuns = new Map();
26
27
  return async (value, { principalKey, signal }) => {
27
28
  if (typeof principalKey !== "string" || !principalKey.trim())
28
29
  return invalidRun("An authenticated principal is required.");
@@ -32,6 +33,14 @@ export function createArkRunHandler(options) {
32
33
  let decoded;
33
34
  try {
34
35
  input = RunAgentInputSchema.parse(value);
36
+ const runKey = canonical([principal, input.threadId, input.runId]);
37
+ if (input.forwardedProps?.nexface?.stop === true) {
38
+ const active = activeRuns.get(runKey);
39
+ if (!active)
40
+ return new Response(null, { status: 404 });
41
+ active.abort();
42
+ return new Response(null, { status: 204 });
43
+ }
35
44
  const state = input.state;
36
45
  const hasState = state != null &&
37
46
  (typeof state !== "object" || Array.isArray(state) || Object.keys(state).length > 0);
@@ -53,16 +62,25 @@ export function createArkRunHandler(options) {
53
62
  catch (error) {
54
63
  return invalidRun(error instanceof Error ? error.message : "Invalid Ark run request.");
55
64
  }
65
+ const runKey = canonical([principal, input.threadId, input.runId]);
66
+ if (activeRuns.has(runKey))
67
+ return invalidRun("This Ark run is already active.");
68
+ const stop = new AbortController();
56
69
  const model = arkModel({
57
70
  apiKey,
58
71
  agentId,
59
72
  environmentId,
60
73
  definitions: decoded.tools,
61
74
  contexts: decoded.contexts,
75
+ stopSignal: stop.signal,
62
76
  });
63
77
  const agent = createAgent({ model });
78
+ const run = agent.runRequest(input, signal ? { signal } : {});
79
+ activeRuns.set(runKey, stop);
80
+ const release = () => activeRuns.delete(runKey);
81
+ void run.result.then(release, release);
64
82
  let messages;
65
- return runResponse(agent.runRequest(input, signal ? { signal } : {}), (event) => {
83
+ return runResponse(run, (event) => {
66
84
  if (event.type === EventType.MESSAGES_SNAPSHOT)
67
85
  messages = event.messages;
68
86
  if (event.type === EventType.RUN_STARTED)
@@ -70,7 +88,7 @@ export function createArkRunHandler(options) {
70
88
  ...event,
71
89
  metadata: {
72
90
  ...event.metadata,
73
- nexface: { ...event.metadata?.nexface, appendOnly: true },
91
+ nexface: { ...event.metadata?.nexface, appendOnly: true, cooperativeStop: true },
74
92
  },
75
93
  };
76
94
  if (event.type === EventType.STATE_SNAPSHOT && messages) {
@@ -15,12 +15,15 @@ export interface ModelBindingRequest {
15
15
  delta?: string;
16
16
  }): void;
17
17
  }
18
+ export interface ModelResponse extends AgentModelResponse {
19
+ stopped?: true;
20
+ }
18
21
  export interface ModelBinding {
19
22
  readonly info: AgentModelInfo;
20
23
  readonly managesHistory?: boolean;
21
24
  exportReplay?(messages: readonly AgentMessage[]): unknown;
22
25
  restoreReplay?(replay: unknown, messages: readonly AgentMessage[]): void;
23
- complete(request: ModelBindingRequest): Promise<AgentModelResponse>;
26
+ complete(request: ModelBindingRequest): Promise<ModelResponse>;
24
27
  }
25
28
  interface ModelConfigDefinition {
26
29
  readonly info: AgentModelInfo;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexface/agent",
3
- "version": "0.1.20-alpha.3",
3
+ "version": "0.1.21-alpha.0",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "engines": {
@@ -73,7 +73,7 @@
73
73
  }
74
74
  },
75
75
  "peerDependencies": {
76
- "@nexface/tools": "0.1.20-alpha.3"
76
+ "@nexface/tools": "0.1.21-alpha.0"
77
77
  },
78
78
  "repository": {
79
79
  "type": "git",