@theokit/sdk 2.0.1 → 2.2.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/a2a/index.cjs +261 -174
  3. package/dist/a2a/index.cjs.map +1 -1
  4. package/dist/a2a/index.js +261 -174
  5. package/dist/a2a/index.js.map +1 -1
  6. package/dist/concurrency.cjs +86 -0
  7. package/dist/concurrency.cjs.map +1 -0
  8. package/dist/concurrency.d.cts +13 -0
  9. package/dist/concurrency.d.ts +13 -0
  10. package/dist/concurrency.js +83 -0
  11. package/dist/concurrency.js.map +1 -0
  12. package/dist/{cron-Bj8-Aq1O.d.ts → cron-Aksw2Hy4.d.ts} +10 -2
  13. package/dist/{cron-DFG9-W17.d.cts → cron-JSPSFczQ.d.cts} +10 -2
  14. package/dist/cron.cjs +244 -172
  15. package/dist/cron.cjs.map +1 -1
  16. package/dist/cron.d.cts +2 -2
  17. package/dist/cron.d.ts +2 -2
  18. package/dist/cron.js +244 -172
  19. package/dist/cron.js.map +1 -1
  20. package/dist/{errors-ChqOmFH1.d.cts → errors-Bcw_Pakm.d.ts} +24 -2
  21. package/dist/{errors-DV9e0rcp.d.ts → errors-Vhg6ZV4o.d.cts} +24 -2
  22. package/dist/errors.cjs +17 -11
  23. package/dist/errors.cjs.map +1 -1
  24. package/dist/errors.d.cts +2 -2
  25. package/dist/errors.d.ts +22 -0
  26. package/dist/errors.js +17 -12
  27. package/dist/errors.js.map +1 -1
  28. package/dist/eval.cjs +244 -172
  29. package/dist/eval.cjs.map +1 -1
  30. package/dist/eval.js +244 -172
  31. package/dist/eval.js.map +1 -1
  32. package/dist/index.cjs +262 -174
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +163 -121
  35. package/dist/index.d.ts +163 -121
  36. package/dist/index.js +262 -176
  37. package/dist/index.js.map +1 -1
  38. package/dist/internal/agent-loop/loop-types.d.ts +6 -0
  39. package/dist/internal/default-retriable.d.ts +1 -0
  40. package/dist/internal/persistence/index.cjs +75 -0
  41. package/dist/internal/persistence/index.cjs.map +1 -1
  42. package/dist/internal/persistence/index.d.cts +2 -0
  43. package/dist/internal/persistence/index.d.ts +2 -0
  44. package/dist/internal/persistence/index.js +74 -1
  45. package/dist/internal/persistence/index.js.map +1 -1
  46. package/dist/internal/persistence/sqlite-open.d.cts +47 -0
  47. package/dist/internal/persistence/sqlite-open.d.ts +47 -0
  48. package/dist/internal/providers/register-plugin-providers.d.ts +22 -0
  49. package/dist/internal/runtime/budget/budget-tracker.d.ts +8 -0
  50. package/dist/internal/runtime/concurrency/map-with-concurrency.d.ts +28 -0
  51. package/dist/internal/runtime/retry/with-retry.d.ts +40 -0
  52. package/dist/internal/security/index.cjs +1 -0
  53. package/dist/internal/security/index.cjs.map +1 -1
  54. package/dist/internal/security/index.js +1 -0
  55. package/dist/internal/security/index.js.map +1 -1
  56. package/dist/path-safety.cjs +15 -0
  57. package/dist/path-safety.cjs.map +1 -1
  58. package/dist/path-safety.d.cts +1 -1
  59. package/dist/path-safety.d.ts +1 -1
  60. package/dist/path-safety.js +15 -1
  61. package/dist/path-safety.js.map +1 -1
  62. package/dist/retry.cjs +85 -0
  63. package/dist/retry.cjs.map +1 -0
  64. package/dist/retry.d.cts +9 -0
  65. package/dist/retry.d.ts +9 -0
  66. package/dist/retry.js +83 -0
  67. package/dist/retry.js.map +1 -0
  68. package/dist/{run-DrwUpFxZ.d.cts → run-ekGKZlmg.d.cts} +20 -0
  69. package/dist/{run-DrwUpFxZ.d.ts → run-ekGKZlmg.d.ts} +20 -0
  70. package/dist/server/errors-envelope.cjs +14 -12
  71. package/dist/server/errors-envelope.cjs.map +1 -1
  72. package/dist/server/errors-envelope.js +14 -12
  73. package/dist/server/errors-envelope.js.map +1 -1
  74. package/dist/subscription/index.cjs.map +1 -1
  75. package/dist/subscription/index.js.map +1 -1
  76. package/dist/task-store.cjs.map +1 -1
  77. package/dist/task-store.js.map +1 -1
  78. package/dist/types/run.d.ts +20 -0
  79. package/dist/workflow.cjs.map +1 -1
  80. package/dist/workflow.js.map +1 -1
  81. package/package.json +21 -1
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var crypto = require('crypto');
3
4
  var fs = require('fs');
4
5
  var path = require('path');
5
- var crypto = require('crypto');
6
6
  var promises = require('fs/promises');
7
7
  var zod = require('zod');
8
8
  var async_hooks = require('async_hooks');
@@ -23,6 +23,24 @@ var __export = (target, all) => {
23
23
  __defProp(target, name, { get: all[name], enumerable: true });
24
24
  };
25
25
 
26
+ // src/internal/default-retriable.ts
27
+ function defaultRetriableForCode(code) {
28
+ switch (code) {
29
+ case "rate_limit":
30
+ case "timeout":
31
+ case "server_error":
32
+ case "network":
33
+ case "provider_unreachable":
34
+ return true;
35
+ default:
36
+ return false;
37
+ }
38
+ }
39
+ var init_default_retriable = __esm({
40
+ "src/internal/default-retriable.ts"() {
41
+ }
42
+ });
43
+
26
44
  // src/internal/security/redact.ts
27
45
  function readEnvOnce() {
28
46
  const raw = process.env.THEOKIT_REDACT_SECRETS;
@@ -179,7 +197,8 @@ __export(errors_exports, {
179
197
  UnsupportedBudgetOperationError: () => exports.UnsupportedBudgetOperationError,
180
198
  UnsupportedRunOperationError: () => exports.UnsupportedRunOperationError,
181
199
  UnsupportedTaskOperationError: () => exports.UnsupportedTaskOperationError,
182
- coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode
200
+ coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode,
201
+ isTransientError: () => isTransientError
183
202
  });
184
203
  function coerceToKnownAgentRunErrorCode(code) {
185
204
  if (code !== void 0 && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {
@@ -211,21 +230,13 @@ function safeStringify(value) {
211
230
  return String(value);
212
231
  }
213
232
  }
214
- function defaultRetriableForCode(code) {
215
- switch (code) {
216
- case "rate_limit":
217
- case "timeout":
218
- case "server_error":
219
- case "network":
220
- case "provider_unreachable":
221
- return true;
222
- default:
223
- return false;
224
- }
233
+ function isTransientError(err) {
234
+ return err instanceof exports.TheokitAgentError && err.isRetryable === true;
225
235
  }
226
236
  var KNOWN_AGENT_RUN_ERROR_CODES; exports.TheokitAgentError = void 0; exports.AuthenticationError = void 0; exports.RateLimitError = void 0; exports.ConfigurationError = void 0; exports.IntegrationNotConnectedError = void 0; exports.NetworkError = void 0; exports.UnknownAgentError = void 0; exports.AgentRunError = void 0; exports.UnsupportedRunOperationError = void 0; var CredentialPoolExhaustedError; exports.MemoryAdapterError = void 0; exports.InvalidTaskIdError = void 0; exports.TaskNotFoundError = void 0; exports.UnsupportedTaskOperationError = void 0; exports.BudgetExceededError = void 0; exports.AgentDisposedError = void 0; exports.UnsupportedBudgetOperationError = void 0;
227
237
  var init_errors = __esm({
228
238
  "src/errors.ts"() {
239
+ init_default_retriable();
229
240
  init_redact();
230
241
  KNOWN_AGENT_RUN_ERROR_CODES = /* @__PURE__ */ new Set([
231
242
  "rate_limit",
@@ -649,6 +660,19 @@ function sanitizeIdentifier(input, options) {
649
660
  }
650
661
  return input.toLowerCase();
651
662
  }
663
+ function safeFilenameForId(id, options) {
664
+ if (id.length === 0) {
665
+ throw new exports.ConfigurationError("Filename id must be a non-empty string", {
666
+ code: "invalid_filename_id"
667
+ });
668
+ }
669
+ const maxLen = options?.maxLen;
670
+ const lower = id.toLowerCase();
671
+ if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {
672
+ return lower;
673
+ }
674
+ return `h-${crypto.createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
675
+ }
652
676
  var PathTraversalError, IDENTIFIER_PATTERN;
653
677
  var init_path_guard = __esm({
654
678
  "src/internal/security/path-guard.ts"() {
@@ -1051,10 +1075,7 @@ function sessionsDir(cwd) {
1051
1075
  return path.join(memoryDir(cwd), "sessions");
1052
1076
  }
1053
1077
  function sessionSummaryPath(cwd, runId) {
1054
- return path.join(sessionsDir(cwd), `${sanitizeRunId(runId)}.md`);
1055
- }
1056
- function sanitizeRunId(runId) {
1057
- return runId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
1078
+ return path.join(sessionsDir(cwd), `${safeFilenameForId(runId, { maxLen: 128 })}.md`);
1058
1079
  }
1059
1080
  function truncate(text) {
1060
1081
  if (text.length <= MAX_TURN_CHARS) return text;
@@ -1090,6 +1111,7 @@ var MAX_TURN_CHARS;
1090
1111
  var init_session_summary_writer = __esm({
1091
1112
  "src/internal/memory/storage/session-summary-writer.ts"() {
1092
1113
  init_atomic_write();
1114
+ init_path_guard();
1093
1115
  init_types();
1094
1116
  init_markdown_store();
1095
1117
  MAX_TURN_CHARS = 2e3;
@@ -1119,6 +1141,49 @@ var init_async_local_storage = __esm({
1119
1141
  }
1120
1142
  });
1121
1143
 
1144
+ // src/internal/runtime/concurrency/async-semaphore.ts
1145
+ function createSemaphore(permits) {
1146
+ if (!Number.isInteger(permits) || permits < 1) {
1147
+ throw new exports.ConfigurationError(
1148
+ `async-semaphore: permits must be a positive integer, got ${permits}`,
1149
+ { code: "invalid_concurrency" }
1150
+ );
1151
+ }
1152
+ let active = 0;
1153
+ const queue = [];
1154
+ function tryGrant() {
1155
+ if (active < permits && queue.length > 0) {
1156
+ const resolve3 = queue.shift();
1157
+ if (resolve3 !== void 0) {
1158
+ active += 1;
1159
+ resolve3();
1160
+ }
1161
+ }
1162
+ }
1163
+ return {
1164
+ inFlight: () => active,
1165
+ pending: () => queue.length + active,
1166
+ async acquire() {
1167
+ await new Promise((resolve3) => {
1168
+ queue.push(resolve3);
1169
+ tryGrant();
1170
+ });
1171
+ let released = false;
1172
+ return () => {
1173
+ if (released) return;
1174
+ released = true;
1175
+ active -= 1;
1176
+ tryGrant();
1177
+ };
1178
+ }
1179
+ };
1180
+ }
1181
+ var init_async_semaphore = __esm({
1182
+ "src/internal/runtime/concurrency/async-semaphore.ts"() {
1183
+ init_errors();
1184
+ }
1185
+ });
1186
+
1122
1187
  // src/internal/llm/credential-pool-types.ts
1123
1188
  var COOLDOWN_MS, DEFAULT_COOLDOWN_MS;
1124
1189
  var init_credential_pool_types = __esm({
@@ -1500,6 +1565,61 @@ var init_sqlite_wal = __esm({
1500
1565
  warnedLabels = /* @__PURE__ */ new Set();
1501
1566
  }
1502
1567
  });
1568
+ async function openSqliteResilient(options) {
1569
+ await promises.mkdir(path.dirname(options.filePath), { recursive: true });
1570
+ try {
1571
+ return await openConcrete(options);
1572
+ } catch (cause) {
1573
+ if (options.recoverCorrupt !== false && isCorruptionError(cause)) {
1574
+ await renameAside(options.filePath, options.label ?? "sqlite");
1575
+ return await openConcrete(options);
1576
+ }
1577
+ throw cause;
1578
+ }
1579
+ }
1580
+ async function openConcrete(options) {
1581
+ const db = await loadDriver(options.filePath);
1582
+ applyWalWithFallback(db, options.label ?? "sqlite");
1583
+ await options.onOpen?.(db);
1584
+ return db;
1585
+ }
1586
+ async function loadDriver(filePath) {
1587
+ try {
1588
+ const mod = await import('better-sqlite3');
1589
+ const Ctor = mod.default ?? mod;
1590
+ if (typeof Ctor !== "function") {
1591
+ throw new Error(`better-sqlite3 export is not a constructor (got ${typeof Ctor})`);
1592
+ }
1593
+ return new Ctor(filePath);
1594
+ } catch (cause) {
1595
+ const message = cause instanceof Error ? cause.message : String(cause);
1596
+ throw new exports.ConfigurationError(
1597
+ `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
1598
+ { code: "sqlite_driver_unavailable", cause }
1599
+ );
1600
+ }
1601
+ }
1602
+ function isCorruptionError(cause) {
1603
+ if (!(cause instanceof Error)) return false;
1604
+ const msg = cause.message.toLowerCase();
1605
+ return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
1606
+ }
1607
+ async function renameAside(filePath, label) {
1608
+ const asidePath = `${filePath}.corrupt-${Date.now()}`;
1609
+ await promises.rename(filePath, asidePath).catch(() => void 0);
1610
+ await promises.rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
1611
+ await promises.rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
1612
+ process.stderr.write(
1613
+ `[theokit-sdk] ${label} database corrupt; renamed aside to ${asidePath} and rebuilt schema
1614
+ `
1615
+ );
1616
+ }
1617
+ var init_sqlite_open = __esm({
1618
+ "src/internal/persistence/sqlite-open.ts"() {
1619
+ init_errors();
1620
+ init_sqlite_wal();
1621
+ }
1622
+ });
1503
1623
 
1504
1624
  // src/internal/memory/index-schema.ts
1505
1625
  var SCHEMA_STATEMENTS, PRAGMA_STATEMENTS;
@@ -1547,60 +1667,22 @@ var init_index_schema = __esm({
1547
1667
  }
1548
1668
  });
1549
1669
  async function openMemoryDb(opts) {
1550
- await promises.mkdir(path.dirname(opts.filePath), { recursive: true });
1551
- try {
1552
- return await openConcrete(opts.filePath);
1553
- } catch (cause) {
1554
- if (opts.recoverCorrupt !== false && isCorruptionError(cause)) {
1555
- await renameAside(opts.filePath);
1556
- return await openConcrete(opts.filePath);
1670
+ return openSqliteResilient({
1671
+ filePath: opts.filePath,
1672
+ label: "memory-index",
1673
+ recoverCorrupt: opts.recoverCorrupt,
1674
+ onOpen: (db) => {
1675
+ for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
1676
+ for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
1557
1677
  }
1558
- throw cause;
1559
- }
1560
- }
1561
- async function openConcrete(filePath) {
1562
- const db = await loadDriver(filePath);
1563
- applyWalWithFallback(db, "memory-index");
1564
- for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
1565
- for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
1566
- return db;
1567
- }
1568
- async function loadDriver(filePath) {
1569
- try {
1570
- const mod = await import('better-sqlite3');
1571
- const Ctor = mod.default ?? mod;
1572
- const db = new Ctor(filePath);
1573
- return db;
1574
- } catch (cause) {
1575
- const message = cause instanceof Error ? cause.message : String(cause);
1576
- throw new exports.ConfigurationError(
1577
- `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
1578
- { code: "sqlite_driver_unavailable", cause }
1579
- );
1580
- }
1581
- }
1582
- function isCorruptionError(cause) {
1583
- if (!(cause instanceof Error)) return false;
1584
- const msg = cause.message.toLowerCase();
1585
- return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
1586
- }
1587
- async function renameAside(filePath) {
1588
- const asidePath = `${filePath}.corrupt-${Date.now()}`;
1589
- await promises.rename(filePath, asidePath).catch(() => void 0);
1590
- await promises.rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
1591
- await promises.rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
1592
- process.stderr.write(
1593
- `[theokit-sdk] memory index corrupt; renamed aside to ${asidePath} and rebuilt schema
1594
- `
1595
- );
1678
+ });
1596
1679
  }
1597
1680
  function defaultIndexPath(cwd) {
1598
1681
  return path.join(cwd, ".theokit", "memory", ".index", "memory.sqlite");
1599
1682
  }
1600
1683
  var init_index_db = __esm({
1601
1684
  "src/internal/memory/index-db.ts"() {
1602
- init_errors();
1603
- init_sqlite_wal();
1685
+ init_sqlite_open();
1604
1686
  init_index_schema();
1605
1687
  }
1606
1688
  });
@@ -2800,49 +2882,6 @@ var init_task = __esm({
2800
2882
  }
2801
2883
  });
2802
2884
 
2803
- // src/internal/runtime/concurrency/async-semaphore.ts
2804
- function createSemaphore(permits) {
2805
- if (!Number.isInteger(permits) || permits < 1) {
2806
- throw new exports.ConfigurationError(
2807
- `async-semaphore: permits must be a positive integer, got ${permits}`,
2808
- { code: "invalid_concurrency" }
2809
- );
2810
- }
2811
- let active = 0;
2812
- const queue = [];
2813
- function tryGrant() {
2814
- if (active < permits && queue.length > 0) {
2815
- const resolve3 = queue.shift();
2816
- if (resolve3 !== void 0) {
2817
- active += 1;
2818
- resolve3();
2819
- }
2820
- }
2821
- }
2822
- return {
2823
- inFlight: () => active,
2824
- pending: () => queue.length + active,
2825
- async acquire() {
2826
- await new Promise((resolve3) => {
2827
- queue.push(resolve3);
2828
- tryGrant();
2829
- });
2830
- let released = false;
2831
- return () => {
2832
- if (released) return;
2833
- released = true;
2834
- active -= 1;
2835
- tryGrant();
2836
- };
2837
- }
2838
- };
2839
- }
2840
- var init_async_semaphore = __esm({
2841
- "src/internal/runtime/concurrency/async-semaphore.ts"() {
2842
- init_errors();
2843
- }
2844
- });
2845
-
2846
2885
  // src/internal/task/ring-buffer.ts
2847
2886
  var RingBuffer;
2848
2887
  var init_ring_buffer = __esm({
@@ -6768,8 +6807,7 @@ var FixtureRunBase = class {
6768
6807
  if (status === "error" && this.script.errorDetail !== void 0) {
6769
6808
  base.error = this.script.errorDetail;
6770
6809
  }
6771
- if (this.script.usage !== void 0) base.usage = this.script.usage;
6772
- if (this.script.cost !== void 0) base.cost = this.script.cost;
6810
+ applyScriptMetrics(base, this.script);
6773
6811
  return this.extendRunResult(applyExtraRunFields(base, this.script));
6774
6812
  }
6775
6813
  /** Subclasses override to attach runtime-specific fields (e.g. cloud git info). */
@@ -6803,6 +6841,11 @@ function makeNotifier() {
6803
6841
  });
6804
6842
  return { promise, resolve: resolve3 };
6805
6843
  }
6844
+ function applyScriptMetrics(base, script) {
6845
+ if (script.usage !== void 0) base.usage = script.usage;
6846
+ if (script.cost !== void 0) base.cost = script.cost;
6847
+ if (script.stoppedAtIterationLimit === true) base.stoppedAtIterationLimit = true;
6848
+ }
6806
6849
 
6807
6850
  // src/internal/runtime/cloud/cloud-run.ts
6808
6851
  function createCloudRun(options) {
@@ -10405,6 +10448,9 @@ var LocalRun = class extends FixtureRunBase {
10405
10448
  }
10406
10449
  };
10407
10450
 
10451
+ // src/internal/runtime/local-agent/real-local-run.ts
10452
+ init_errors();
10453
+
10408
10454
  // src/internal/runtime/budget/budget.ts
10409
10455
  var IterationBudget = class {
10410
10456
  #remaining;
@@ -10858,6 +10904,27 @@ async function emitTextDeltaCallback(inputs, text) {
10858
10904
  // src/internal/agent-loop/tool-dispatch.ts
10859
10905
  init_async_local_storage();
10860
10906
 
10907
+ // src/internal/runtime/concurrency/map-with-concurrency.ts
10908
+ init_async_semaphore();
10909
+ var NEVER_ABORT = new AbortController().signal;
10910
+ async function mapWithConcurrency(items, concurrency, fn, options) {
10911
+ const semaphore = createSemaphore(concurrency);
10912
+ const signal = NEVER_ABORT;
10913
+ return Promise.all(
10914
+ items.map(async (item, index) => {
10915
+ const release = await semaphore.acquire();
10916
+ try {
10917
+ if (signal.aborted) {
10918
+ throw signal.reason instanceof Error ? signal.reason : new Error("mapWithConcurrency: aborted");
10919
+ }
10920
+ return await fn(item, index, signal);
10921
+ } finally {
10922
+ release();
10923
+ }
10924
+ })
10925
+ );
10926
+ }
10927
+
10861
10928
  // src/internal/tool-dispatch/repair-middleware.ts
10862
10929
  var DECIMAL_RE = /^-?\d+(\.\d+)?$/;
10863
10930
  function repairToolCall(raw, registry3) {
@@ -11032,38 +11099,12 @@ ${result.stderr}`.trim();
11032
11099
  // src/internal/agent-loop/tool-dispatch.ts
11033
11100
  async function dispatchTools(inputs, tools, toolCalls, events) {
11034
11101
  const maxConcurrent = inputs.maxConcurrentTools ?? 4;
11035
- return boundedParallel(
11036
- maxConcurrent,
11102
+ return mapWithConcurrency(
11037
11103
  toolCalls,
11104
+ maxConcurrent,
11038
11105
  (call) => dispatchSingleCall(inputs, tools, call, events)
11039
11106
  );
11040
11107
  }
11041
- async function boundedParallel(max, items, fn) {
11042
- let running = 0;
11043
- const queue = [];
11044
- async function acquire() {
11045
- if (running < max) {
11046
- running++;
11047
- return;
11048
- }
11049
- await new Promise((resolve3) => queue.push(resolve3));
11050
- running++;
11051
- }
11052
- function release() {
11053
- running--;
11054
- if (queue.length > 0) queue.shift()();
11055
- }
11056
- return Promise.all(
11057
- items.map(async (item) => {
11058
- await acquire();
11059
- try {
11060
- return await fn(item);
11061
- } finally {
11062
- release();
11063
- }
11064
- })
11065
- );
11066
- }
11067
11108
  async function dispatchSingleCall(inputs, tools, call, events) {
11068
11109
  const { call: workingCall, repairs } = applyRepairAndExtractCall(tools, call);
11069
11110
  const callId = generateCallId();
@@ -11634,6 +11675,7 @@ async function runAgentLoop(inputs) {
11634
11675
  const ctx = await initLoopContext(inputs);
11635
11676
  ctxRef = ctx;
11636
11677
  const budget = inputs.budget ?? new IterationBudget({ maxIterations: inputs.maxIterations ?? 8 });
11678
+ let lastTurnDecision;
11637
11679
  while (budget.shouldContinue()) {
11638
11680
  if (inputs.budgetTracker !== void 0) {
11639
11681
  const decision2 = evaluateBudgetGate(inputs.budgetTracker);
@@ -11642,18 +11684,26 @@ async function runAgentLoop(inputs) {
11642
11684
  if (decision2.detail !== void 0) {
11643
11685
  ctx.error = { message: decision2.detail, code: decision2.reason ?? "budget" };
11644
11686
  }
11687
+ if (decision2.reason === "iteration_limit") {
11688
+ ctx.stoppedAtIterationLimit = true;
11689
+ }
11645
11690
  break;
11646
11691
  }
11647
11692
  }
11648
11693
  const usingGrace = budget.remaining <= 0 && !budget.graceCallUsed;
11649
11694
  if (usingGrace) budget.useGraceCall();
11650
11695
  const decision = await runIteration(inputs, ctx);
11696
+ lastTurnDecision = decision;
11651
11697
  if (decision === "done") break;
11652
11698
  if (decision === "error") {
11653
11699
  ctx.finalStatus = "error";
11654
11700
  break;
11655
11701
  }
11656
11702
  budget.consume();
11703
+ inputs.budgetTracker?.nextIteration?.();
11704
+ }
11705
+ if (lastTurnDecision === "continue" && budget.shouldContinue() === false) {
11706
+ ctx.stoppedAtIterationLimit = true;
11657
11707
  }
11658
11708
  if (budget.shouldContinue() === false && ctx.finalStatus === "finished" && ctx.finalText === "") {
11659
11709
  ctx.finalStatus = "error";
@@ -11684,7 +11734,8 @@ async function runAgentLoop(inputs) {
11684
11734
  conversation: ctx.conversation,
11685
11735
  ...usage !== void 0 ? { usage } : {},
11686
11736
  ...cost !== void 0 ? { cost } : {},
11687
- ...ctx.error !== void 0 ? { error: ctx.error } : {}
11737
+ ...ctx.error !== void 0 ? { error: ctx.error } : {},
11738
+ ...ctx.stoppedAtIterationLimit === true ? { stoppedAtIterationLimit: true } : {}
11688
11739
  };
11689
11740
  } finally {
11690
11741
  if (ctxRef !== void 0 && ctxRef.memoryProviderHandle !== void 0 && inputs.memoryProvider !== void 0) {
@@ -14013,6 +14064,16 @@ function resolveMcpCwd(configCwd) {
14013
14064
  return safePathJoin(process.cwd(), configCwd);
14014
14065
  }
14015
14066
 
14067
+ // src/internal/providers/register-plugin-providers.ts
14068
+ function registerPluginProviderProfiles(entries) {
14069
+ let registered4 = 0;
14070
+ for (const entry of entries) {
14071
+ registerProvider(entry.profile);
14072
+ registered4 += 1;
14073
+ }
14074
+ return registered4;
14075
+ }
14076
+
14016
14077
  // src/internal/tool-registry/personality-filter.ts
14017
14078
  init_hooks_source();
14018
14079
  function applyPersonalityFilter(exposedTools, whitelist, opts) {
@@ -14089,12 +14150,34 @@ function createRealLocalRun(options) {
14089
14150
  registerRun(handle);
14090
14151
  return handle;
14091
14152
  }
14092
- function buildLoopInputs(options, runId, userText) {
14153
+ var pluginProvidersAnnounced = false;
14154
+ function resolveRunProvider(options) {
14093
14155
  registerBuiltins();
14156
+ const profiles = options.pluginManager?.aggregated.providerProfiles ?? [];
14157
+ const registered4 = registerPluginProviderProfiles(profiles);
14158
+ if (registered4 > 0 && !pluginProvidersAnnounced) {
14159
+ pluginProvidersAnnounced = true;
14160
+ const names = profiles.map((e) => e.profile.name).join(", ");
14161
+ process.stderr.write(
14162
+ `[theokit-sdk] registered ${registered4} plugin provider profile(s): ${names}
14163
+ `
14164
+ );
14165
+ }
14094
14166
  const parsedModel = parseModelId(options.model?.id);
14095
14167
  const inferredProvider = parsedModel.provider !== void 0 && getProviderProfile(parsedModel.provider) !== void 0 ? parsedModel.provider : void 0;
14096
14168
  const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? inferredProvider ?? detectPrimaryProvider();
14097
14169
  const effectiveModelId = inferredProvider !== void 0 ? parsedModel.name : options.model?.id ?? "claude-sonnet-4-6";
14170
+ return { primary, effectiveModelId };
14171
+ }
14172
+ function buildLoopInputs(options, runId, userText) {
14173
+ const maxIterations = options.sendOptions.maxIterations;
14174
+ if (maxIterations !== void 0 && (!Number.isInteger(maxIterations) || maxIterations < 1)) {
14175
+ throw new exports.ConfigurationError(
14176
+ `SendOptions.maxIterations must be a positive integer, got ${maxIterations}`,
14177
+ { code: "invalid_max_iterations" }
14178
+ );
14179
+ }
14180
+ const { primary, effectiveModelId } = resolveRunProvider(options);
14098
14181
  const fallback = options.agentOptions.providers?.fallback;
14099
14182
  const apiKeys = options.agentOptions.providers?.apiKeys;
14100
14183
  const credentialPoolStrategy = options.agentOptions.providers?.credentialPoolStrategy;
@@ -14132,6 +14215,9 @@ function buildLoopInputs(options, runId, userText) {
14132
14215
  // D318 — forward SendOptions.signal to the agent loop so streamLlmTurn
14133
14216
  // can attach it to the LLM `fetch({ signal })` call.
14134
14217
  ...options.sendOptions.signal !== void 0 ? { signal: options.sendOptions.signal } : {},
14218
+ // M1-2: per-send iteration ceiling (validated above). The loop reads
14219
+ // inputs.maxIterations (default 8 when unset).
14220
+ ...maxIterations !== void 0 ? { maxIterations } : {},
14135
14221
  // D315-D317 — tool lifecycle hooks (cost tracking + audit + retry/alert)
14136
14222
  ...options.agentOptions.onToolStart !== void 0 ? { onToolStart: options.agentOptions.onToolStart } : {},
14137
14223
  ...options.agentOptions.onToolEnd !== void 0 ? { onToolEnd: options.agentOptions.onToolEnd } : {},
@@ -14263,6 +14349,7 @@ var RealLocalRun = class extends FixtureRunBase {
14263
14349
  if (output.result.length > 0) this.script.result = output.result;
14264
14350
  if (output.usage !== void 0) this.script.usage = output.usage;
14265
14351
  if (output.cost !== void 0) this.script.cost = output.cost;
14352
+ if (output.stoppedAtIterationLimit === true) this.script.stoppedAtIterationLimit = true;
14266
14353
  if (output.error !== void 0 && this.script.errorDetail === void 0) {
14267
14354
  this.script.errorDetail = {
14268
14355
  message: output.error.message,
@@ -14684,7 +14771,7 @@ async function embedTexts(input) {
14684
14771
  pending
14685
14772
  });
14686
14773
  }
14687
- await runBatches(input, pending, results);
14774
+ await embedInBoundedBatches(input, pending, results);
14688
14775
  return results.map((v) => v ?? new Array(dimension).fill(0));
14689
14776
  }
14690
14777
  function classifyEntry(args) {
@@ -14703,45 +14790,34 @@ function classifyEntry(args) {
14703
14790
  args.pending.push({ index: args.index, text: args.text, key: key2 });
14704
14791
  }
14705
14792
  var MAX_CONCURRENT_BATCHES = 3;
14706
- async function runBatches(input, pending, results) {
14793
+ async function embedInBoundedBatches(input, pending, results) {
14707
14794
  const batches = [];
14708
14795
  for (let offset = 0; offset < pending.length; offset += MAX_BATCH) {
14709
14796
  batches.push(pending.slice(offset, offset + MAX_BATCH));
14710
14797
  }
14711
- let running = 0;
14712
- const queue = [];
14713
- await Promise.all(batches.map((batch) => processBatch(input, batch, results, acquire, release)));
14714
- async function acquire() {
14715
- if (running >= MAX_CONCURRENT_BATCHES) await new Promise((r) => queue.push(r));
14716
- running++;
14717
- }
14718
- function release() {
14719
- running--;
14720
- if (queue.length > 0) queue.shift()();
14721
- }
14798
+ await mapWithConcurrency(
14799
+ batches,
14800
+ MAX_CONCURRENT_BATCHES,
14801
+ (batch) => processBatch(input, batch, results)
14802
+ );
14722
14803
  }
14723
- async function processBatch(input, batch, results, acquire, release) {
14724
- await acquire();
14725
- try {
14726
- const vectors = await embedBatch({
14727
- apiKey: input.apiKey,
14728
- baseUrl: input.baseUrl,
14729
- embeddingsPath: input.embeddingsPath,
14730
- model: input.model,
14731
- inputs: batch.map((b) => b.text),
14732
- fetchImpl: input.fetchImpl,
14733
- stats: input.stats,
14734
- providerId: input.providerId
14735
- });
14736
- for (let j = 0; j < batch.length; j++) {
14737
- const slot = batch[j];
14738
- const vector = vectors[j];
14739
- if (slot === void 0 || vector === void 0) continue;
14740
- results[slot.index] = vector;
14741
- input.cache.set(slot.key, vector);
14742
- }
14743
- } finally {
14744
- release();
14804
+ async function processBatch(input, batch, results) {
14805
+ const vectors = await embedBatch({
14806
+ apiKey: input.apiKey,
14807
+ baseUrl: input.baseUrl,
14808
+ embeddingsPath: input.embeddingsPath,
14809
+ model: input.model,
14810
+ inputs: batch.map((b) => b.text),
14811
+ fetchImpl: input.fetchImpl,
14812
+ stats: input.stats,
14813
+ providerId: input.providerId
14814
+ });
14815
+ for (let j = 0; j < batch.length; j++) {
14816
+ const slot = batch[j];
14817
+ const vector = vectors[j];
14818
+ if (slot === void 0 || vector === void 0) continue;
14819
+ results[slot.index] = vector;
14820
+ input.cache.set(slot.key, vector);
14745
14821
  }
14746
14822
  }
14747
14823
  async function embedBatch(opts) {
@@ -17702,6 +17778,16 @@ async function updateJobStatus(jobId, enabled) {
17702
17778
  return updated;
17703
17779
  }
17704
17780
 
17781
+ // src/define-provider.ts
17782
+ function defineProvider(profile, opts) {
17783
+ return {
17784
+ name: profile.name,
17785
+ version: opts?.version ?? "1.0.0",
17786
+ kind: "model-provider",
17787
+ profile
17788
+ };
17789
+ }
17790
+
17705
17791
  // src/define-tool.ts
17706
17792
  init_to_json_schema();
17707
17793
  function defineTool(spec) {
@@ -19232,10 +19318,12 @@ exports.createCounterBudgetTracker = createCounterBudgetTracker;
19232
19318
  exports.createNoopMemoryProvider = createNoopMemoryProvider;
19233
19319
  exports.createSquad = createSquad;
19234
19320
  exports.definePlugin = definePlugin;
19321
+ exports.defineProvider = defineProvider;
19235
19322
  exports.defineTool = defineTool;
19236
19323
  exports.extractRawId = extractRawId;
19237
19324
  exports.getPricingEntry = getPricingEntry;
19238
19325
  exports.inferApiMode = inferApiMode;
19326
+ exports.isTransientError = isTransientError;
19239
19327
  exports.migrateSqliteToLance = migrateSqliteToLance2;
19240
19328
  exports.mkMemoryId = mkMemoryId;
19241
19329
  exports.normalizeUsage = normalizeUsage;