@dudousxd/nestjs-agent-core 0.37.0 → 0.38.1

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/index.cjs CHANGED
@@ -91,6 +91,7 @@ __export(src_exports, {
91
91
  SCHEMA_EXTENSION: () => SCHEMA_EXTENSION,
92
92
  SKILL_TOOL_DESCRIPTION: () => SKILL_TOOL_DESCRIPTION,
93
93
  SKILL_TOOL_NAME: () => SKILL_TOOL_NAME,
94
+ SqlTokenStreamSink: () => SqlTokenStreamSink,
94
95
  StructuredOutputError: () => StructuredOutputError,
95
96
  THREAD_DETAIL_CONTENT_CHARS: () => THREAD_DETAIL_CONTENT_CHARS,
96
97
  ToolDisabledError: () => ToolDisabledError,
@@ -321,7 +322,7 @@ __name(decodeStreamEvent, "decodeStreamEvent");
321
322
 
322
323
  // src/turn-frames.ts
323
324
  function observeTurnFrames(writer, now = Date.now) {
324
- const decoder2 = new TextDecoder();
325
+ const decoder3 = new TextDecoder();
325
326
  let pending = "";
326
327
  let reasoning = "";
327
328
  let reasoningMs = 0;
@@ -361,7 +362,7 @@ function observeTurnFrames(writer, now = Date.now) {
361
362
  }
362
363
  __name(observeLine, "observeLine");
363
364
  function observe(chunk) {
364
- pending += decoder2.decode(chunk, {
365
+ pending += decoder3.decode(chunk, {
365
366
  stream: true
366
367
  });
367
368
  let newline = pending.indexOf("\n");
@@ -2744,7 +2745,8 @@ function detachedUnsettled(args) {
2744
2745
  __name(detachedUnsettled, "detachedUnsettled");
2745
2746
  async function settleUnsettledDelegation(args) {
2746
2747
  const { store, delivery, agent, runId, status } = args;
2747
- if (await store.getThread(delivery.threadId) === null) {
2748
+ const thread = await store.getThread(delivery.threadId);
2749
+ if (thread === null || thread.messages.some((message) => message.runId === runId)) {
2748
2750
  return;
2749
2751
  }
2750
2752
  await store.appendMessage({
@@ -5674,7 +5676,8 @@ var InMemoryAgentStore = class {
5674
5676
  }
5675
5677
  }
5676
5678
  /**
5677
- * Of `mediaIds`, the ones a surviving message in one of this actor's threads still carries.
5679
+ * Of `mediaIds`, the ones a surviving message — or a message waiting in the queue — in one of
5680
+ * this actor's threads still carries.
5678
5681
  * Re-derived from the messages each call, so a media whose message was truncated away reads as
5679
5682
  * unreferenced again.
5680
5683
  */
@@ -5688,7 +5691,11 @@ var InMemoryAgentStore = class {
5688
5691
  if (thread.actorRef !== actorRef) {
5689
5692
  continue;
5690
5693
  }
5691
- for (const message of thread.messages) {
5694
+ const queued = this.queues.get(thread.id) ?? [];
5695
+ for (const message of [
5696
+ ...thread.messages,
5697
+ ...queued
5698
+ ]) {
5692
5699
  for (const attachment of message.attachments ?? []) {
5693
5700
  if (wanted.has(attachment.mediaId)) {
5694
5701
  found.add(attachment.mediaId);
@@ -6330,6 +6337,245 @@ function defineConfirmedTool(options, steps) {
6330
6337
  };
6331
6338
  }
6332
6339
  __name(defineConfirmedTool, "defineConfirmedTool");
6340
+
6341
+ // src/sql-token-stream-sink.ts
6342
+ var DEFAULT_TTL_SECONDS = 3600;
6343
+ var DEFAULT_POLL_INTERVAL_MS = 250;
6344
+ var DEFAULT_IDLE_POLL_INTERVAL_MS = 1e3;
6345
+ var IDLE_AFTER_MS = 5e3;
6346
+ var DEFAULT_FLUSH_MS = 50;
6347
+ var READ_PAGE = 500;
6348
+ var PURGE_CHUNK = 200;
6349
+ var AUTO_PURGE_EVERY_MS = 6e4;
6350
+ var APPEND_ATTEMPTS = 8;
6351
+ var decoder2 = new TextDecoder();
6352
+ var encoder2 = new TextEncoder();
6353
+ var sleep = /* @__PURE__ */ __name((ms) => new Promise((resolve) => setTimeout(resolve, ms)), "sleep");
6354
+ function textOf(line) {
6355
+ if (!line.startsWith('{"kind":"text"')) return null;
6356
+ try {
6357
+ const parsed = JSON.parse(line);
6358
+ if (typeof parsed === "object" && parsed !== null && Object.keys(parsed).length === 2 && parsed.kind === "text" && typeof parsed.text === "string") {
6359
+ return parsed.text;
6360
+ }
6361
+ } catch {
6362
+ }
6363
+ return null;
6364
+ }
6365
+ __name(textOf, "textOf");
6366
+ var SqlTokenStreamSink = class {
6367
+ static {
6368
+ __name(this, "SqlTokenStreamSink");
6369
+ }
6370
+ table;
6371
+ pollIntervalMs;
6372
+ idlePollIntervalMs;
6373
+ flushMs;
6374
+ ttlSeconds;
6375
+ autoPurge;
6376
+ writes = /* @__PURE__ */ new Map();
6377
+ lastAutoPurge = 0;
6378
+ constructor(table, options = {}) {
6379
+ this.table = table;
6380
+ this.pollIntervalMs = Math.max(1, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
6381
+ this.idlePollIntervalMs = Math.max(this.pollIntervalMs, options.idlePollIntervalMs ?? DEFAULT_IDLE_POLL_INTERVAL_MS);
6382
+ this.flushMs = Math.max(0, options.flushMs ?? DEFAULT_FLUSH_MS);
6383
+ this.ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;
6384
+ this.autoPurge = options.autoPurge ?? true;
6385
+ }
6386
+ runWrites(runId) {
6387
+ let state = this.writes.get(runId);
6388
+ if (state === void 0) {
6389
+ state = {
6390
+ text: null,
6391
+ timer: void 0,
6392
+ tail: Promise.resolve(),
6393
+ pending: 0,
6394
+ failure: void 0
6395
+ };
6396
+ this.writes.set(runId, state);
6397
+ }
6398
+ return state;
6399
+ }
6400
+ /** Forget a run's write state once nothing is gathered, queued or left to report. */
6401
+ release(runId, state) {
6402
+ if (state.pending === 0 && state.text === null && state.failure === void 0 && this.writes.get(runId) === state) {
6403
+ this.writes.delete(runId);
6404
+ }
6405
+ }
6406
+ /** Queue `work` behind every write already queued for the run, so rows land in call order. */
6407
+ enqueue(runId, state, work) {
6408
+ state.pending += 1;
6409
+ const next = state.tail.then(work);
6410
+ state.tail = next.then(() => void 0, () => void 0).then(() => {
6411
+ state.pending -= 1;
6412
+ this.release(runId, state);
6413
+ });
6414
+ return next;
6415
+ }
6416
+ /** Queue the gathered text (if any) as one `text` row. */
6417
+ flushText(runId, state) {
6418
+ if (state.timer !== void 0) {
6419
+ clearTimeout(state.timer);
6420
+ state.timer = void 0;
6421
+ }
6422
+ if (state.text === null) return Promise.resolve();
6423
+ const line = decoder2.decode(encodeStreamEvent({
6424
+ kind: "text",
6425
+ text: state.text
6426
+ }));
6427
+ state.text = null;
6428
+ return this.enqueue(runId, state, () => this.append(runId, line, null));
6429
+ }
6430
+ /** Raise, once, a gathered write that failed with nobody awaiting it. */
6431
+ raiseFailure(state) {
6432
+ const failure = state.failure;
6433
+ if (failure !== void 0) {
6434
+ state.failure = void 0;
6435
+ throw failure.error;
6436
+ }
6437
+ }
6438
+ /** Append one row — a frame, or the terminal row (`frame: null`, with `error` on a failure). */
6439
+ async append(runId, frame, error) {
6440
+ for (let attempt = 1; ; attempt += 1) {
6441
+ try {
6442
+ await this.table.append(runId, {
6443
+ frame,
6444
+ error,
6445
+ createdAt: Date.now()
6446
+ });
6447
+ return;
6448
+ } catch (caught) {
6449
+ if (attempt >= APPEND_ATTEMPTS || !this.table.isUniqueViolation(caught)) throw caught;
6450
+ }
6451
+ }
6452
+ }
6453
+ /** Write out what is gathered, then a terminal row; raise a failure nobody saw. */
6454
+ async terminate(runId, error) {
6455
+ const state = this.runWrites(runId);
6456
+ const flushed = this.flushText(runId, state);
6457
+ const ended = this.enqueue(runId, state, () => this.append(runId, null, error));
6458
+ await Promise.all([
6459
+ flushed,
6460
+ ended
6461
+ ]);
6462
+ this.raiseFailure(state);
6463
+ this.release(runId, state);
6464
+ this.purgeInBackground();
6465
+ }
6466
+ /**
6467
+ * The run's writer. Writers opened for the same run in one process share what they are gathering,
6468
+ * so a delegated run's text (forwarded through a child writer) and its parent's next frame keep
6469
+ * the order they were written in.
6470
+ */
6471
+ open(runId) {
6472
+ return {
6473
+ write: /* @__PURE__ */ __name(async (chunk) => {
6474
+ const state = this.runWrites(runId);
6475
+ this.raiseFailure(state);
6476
+ const line = decoder2.decode(chunk);
6477
+ const text = this.flushMs > 0 ? textOf(line.trimEnd()) : null;
6478
+ if (text !== null) {
6479
+ state.text = (state.text ?? "") + text;
6480
+ if (state.timer === void 0) {
6481
+ state.timer = setTimeout(() => {
6482
+ state.timer = void 0;
6483
+ this.flushText(runId, state).catch((error) => {
6484
+ state.failure = {
6485
+ error
6486
+ };
6487
+ });
6488
+ }, this.flushMs);
6489
+ }
6490
+ return;
6491
+ }
6492
+ const flushed = this.flushText(runId, state);
6493
+ const appended = this.enqueue(runId, state, () => this.append(runId, line, null));
6494
+ await Promise.all([
6495
+ flushed,
6496
+ appended
6497
+ ]);
6498
+ }, "write"),
6499
+ flush: /* @__PURE__ */ __name(async () => {
6500
+ const state = this.runWrites(runId);
6501
+ const flushed = this.flushText(runId, state);
6502
+ await Promise.all([
6503
+ flushed,
6504
+ state.tail
6505
+ ]);
6506
+ this.raiseFailure(state);
6507
+ this.release(runId, state);
6508
+ }, "flush"),
6509
+ end: /* @__PURE__ */ __name(() => this.terminate(runId, null), "end"),
6510
+ fail: /* @__PURE__ */ __name((error) => this.terminate(runId, JSON.stringify({
6511
+ code: error.code,
6512
+ message: error.message
6513
+ })), "fail")
6514
+ };
6515
+ }
6516
+ async *subscribe(runId) {
6517
+ let cursor = 0;
6518
+ let quietSince = Date.now();
6519
+ while (true) {
6520
+ const rows = await this.table.read(runId, cursor, READ_PAGE);
6521
+ for (const row of rows) {
6522
+ cursor = row.seq;
6523
+ if (row.frame === null) {
6524
+ if (row.error !== null) {
6525
+ throw new AgentStreamError(JSON.parse(row.error));
6526
+ }
6527
+ return;
6528
+ }
6529
+ yield encoder2.encode(row.frame);
6530
+ }
6531
+ if (rows.length > 0) {
6532
+ quietSince = Date.now();
6533
+ if (rows.length >= READ_PAGE) continue;
6534
+ }
6535
+ await sleep(Date.now() - quietSince >= IDLE_AFTER_MS ? this.idlePollIntervalMs : this.pollIntervalMs);
6536
+ }
6537
+ }
6538
+ /** Does the table hold anything for the run — a frame, or its end? */
6539
+ has(runId) {
6540
+ return this.table.has(runId);
6541
+ }
6542
+ async close(runId) {
6543
+ const state = this.writes.get(runId);
6544
+ if (state !== void 0) {
6545
+ if (state.timer !== void 0) clearTimeout(state.timer);
6546
+ state.timer = void 0;
6547
+ state.text = null;
6548
+ state.failure = void 0;
6549
+ await state.tail;
6550
+ this.writes.delete(runId);
6551
+ }
6552
+ await this.table.remove([
6553
+ runId
6554
+ ]);
6555
+ }
6556
+ /**
6557
+ * Delete every run whose last write is older than `ttlSeconds` at `now` (epoch-ms) — ended runs
6558
+ * past their replay window and runs that crashed without ending alike. Returns how many runs went.
6559
+ * Safe from any replica, and from several at once. A no-op under `ttlSeconds: 0`.
6560
+ */
6561
+ async purgeExpired(now = Date.now()) {
6562
+ if (this.ttlSeconds <= 0) return 0;
6563
+ const lapsed = await this.table.lapsedRuns(now - this.ttlSeconds * 1e3);
6564
+ for (let index = 0; index < lapsed.length; index += PURGE_CHUNK) {
6565
+ await this.table.remove(lapsed.slice(index, index + PURGE_CHUNK));
6566
+ }
6567
+ return lapsed.length;
6568
+ }
6569
+ /** {@link purgeExpired}, unawaited and at most once a minute. Its failure is not the run's. */
6570
+ purgeInBackground() {
6571
+ if (!this.autoPurge || this.ttlSeconds <= 0) return;
6572
+ const now = Date.now();
6573
+ if (now - this.lastAutoPurge < AUTO_PURGE_EVERY_MS) return;
6574
+ this.lastAutoPurge = now;
6575
+ this.purgeExpired(now).catch(() => {
6576
+ });
6577
+ }
6578
+ };
6333
6579
  // Annotate the CommonJS export names for ESM import in node:
6334
6580
  0 && (module.exports = {
6335
6581
  AGENT_ACTOR_DIRECTORY,
@@ -6402,6 +6648,7 @@ __name(defineConfirmedTool, "defineConfirmedTool");
6402
6648
  SCHEMA_EXTENSION,
6403
6649
  SKILL_TOOL_DESCRIPTION,
6404
6650
  SKILL_TOOL_NAME,
6651
+ SqlTokenStreamSink,
6405
6652
  StructuredOutputError,
6406
6653
  THREAD_DETAIL_CONTENT_CHARS,
6407
6654
  ToolDisabledError,