@theokit/sdk 2.0.0 → 2.1.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 (107) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/a2a/index.cjs +384 -317
  3. package/dist/a2a/index.cjs.map +1 -1
  4. package/dist/a2a/index.js +384 -317
  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-Bse1MbaE.d.cts → cron-CSTqNZp9.d.cts} +2 -2
  13. package/dist/{cron-Ci_NUkUj.d.ts → cron-Da6vF_2y.d.ts} +2 -2
  14. package/dist/cron.cjs +346 -295
  15. package/dist/cron.cjs.map +1 -1
  16. package/dist/cron.d.cts +1 -1
  17. package/dist/cron.d.ts +1 -1
  18. package/dist/cron.js +349 -298
  19. package/dist/cron.js.map +1 -1
  20. package/dist/{errors-DV9e0rcp.d.ts → errors--VP2qrGc.d.ts} +23 -1
  21. package/dist/{errors-ChqOmFH1.d.cts → errors-C9xkhNEF.d.cts} +23 -1
  22. package/dist/errors.cjs +17 -11
  23. package/dist/errors.cjs.map +1 -1
  24. package/dist/errors.d.cts +1 -1
  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 +345 -291
  29. package/dist/eval.cjs.map +1 -1
  30. package/dist/eval.d.cts +1 -0
  31. package/dist/eval.d.ts +1 -0
  32. package/dist/eval.js +348 -294
  33. package/dist/eval.js.map +1 -1
  34. package/dist/index.cjs +342 -275
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +161 -119
  37. package/dist/index.d.ts +161 -119
  38. package/dist/index.js +342 -277
  39. package/dist/index.js.map +1 -1
  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/concurrency/map-with-concurrency.d.ts +28 -0
  50. package/dist/internal/runtime/{fork-agent.d.ts → lifecycle/fork-agent.d.ts} +1 -1
  51. package/dist/internal/runtime/{run-until.d.ts → lifecycle/run-until.d.ts} +3 -3
  52. package/dist/internal/runtime/local-agent/local-agent-bootstrap.d.ts +1 -1
  53. package/dist/internal/runtime/registry/agent-factory-registry.d.ts +12 -9
  54. package/dist/internal/runtime/retry/with-retry.d.ts +40 -0
  55. package/dist/internal/runtime/validation/validate-agent-options.d.ts +1 -0
  56. package/dist/internal/scorers/llm-judge.d.ts +4 -4
  57. package/dist/internal/security/index.cjs +1 -0
  58. package/dist/internal/security/index.cjs.map +1 -1
  59. package/dist/internal/security/index.d.cts +1 -1
  60. package/dist/internal/security/index.d.ts +1 -1
  61. package/dist/internal/security/index.js +1 -0
  62. package/dist/internal/security/index.js.map +1 -1
  63. package/dist/path-safety.cjs +15 -0
  64. package/dist/path-safety.cjs.map +1 -1
  65. package/dist/path-safety.d.cts +1 -1
  66. package/dist/path-safety.d.ts +1 -1
  67. package/dist/path-safety.js +15 -1
  68. package/dist/path-safety.js.map +1 -1
  69. package/dist/retry.cjs +85 -0
  70. package/dist/retry.cjs.map +1 -0
  71. package/dist/retry.d.cts +9 -0
  72. package/dist/retry.d.ts +9 -0
  73. package/dist/retry.js +83 -0
  74. package/dist/retry.js.map +1 -0
  75. package/dist/server/errors-envelope.cjs +14 -12
  76. package/dist/server/errors-envelope.cjs.map +1 -1
  77. package/dist/server/errors-envelope.js +14 -12
  78. package/dist/server/errors-envelope.js.map +1 -1
  79. package/dist/subscription/index.cjs.map +1 -1
  80. package/dist/subscription/index.js.map +1 -1
  81. package/dist/task-store.cjs.map +1 -1
  82. package/dist/task-store.js.map +1 -1
  83. package/dist/types/fork.d.ts +1 -1
  84. package/dist/workflow.cjs +2 -2
  85. package/dist/workflow.cjs.map +1 -1
  86. package/dist/workflow.js +2 -2
  87. package/dist/workflow.js.map +1 -1
  88. package/package.json +26 -2
  89. /package/dist/internal/{runtime/default-model.d.ts → default-retriable.d.ts} +0 -0
  90. /package/dist/internal/{errors/mappers → error-mappers}/anthropic.d.ts +0 -0
  91. /package/dist/internal/{errors/mappers → error-mappers}/bedrock.d.ts +0 -0
  92. /package/dist/internal/{errors/mappers → error-mappers}/ollama.d.ts +0 -0
  93. /package/dist/internal/{errors/mappers → error-mappers}/openai-compatible.d.ts +0 -0
  94. /package/dist/internal/{errors/mappers → error-mappers}/shared.d.ts +0 -0
  95. /package/dist/internal/{errors/mappers → error-mappers}/vertex.d.ts +0 -0
  96. /package/dist/internal/runtime/{abort-utils.d.ts → concurrency/abort-utils.d.ts} +0 -0
  97. /package/dist/internal/runtime/{async-local-storage.d.ts → concurrency/async-local-storage.d.ts} +0 -0
  98. /package/dist/internal/runtime/{async-semaphore.d.ts → concurrency/async-semaphore.d.ts} +0 -0
  99. /package/dist/internal/runtime/{post-run-lifecycle.d.ts → config/default-model.d.ts} +0 -0
  100. /package/dist/internal/runtime/{providers-manager.d.ts → config/providers-manager.d.ts} +0 -0
  101. /package/dist/internal/runtime/{workspace-dir.d.ts → config/workspace-dir.d.ts} +0 -0
  102. /package/dist/internal/runtime/{yaml-frontmatter.d.ts → context/yaml-frontmatter.d.ts} +0 -0
  103. /package/dist/internal/runtime/{system-prompt.d.ts → lifecycle/post-run-lifecycle.d.ts} +0 -0
  104. /package/dist/internal/runtime/{spawn-collect.d.ts → lifecycle/spawn-collect.d.ts} +0 -0
  105. /package/dist/internal/runtime/{validate-agent-options.d.ts → system-prompt/system-prompt.d.ts} +0 -0
  106. /package/dist/internal/runtime/{shell-tool.d.ts → tools/shell-tool.d.ts} +0 -0
  107. /package/dist/internal/runtime/{validate-response.d.ts → validation/validate-response.d.ts} +0 -0
package/dist/eval.js CHANGED
@@ -1,8 +1,8 @@
1
- import { randomUUID, createHash, randomBytes } from 'crypto';
2
- import { stat, readFile, rename, mkdir, rm, readdir, open, unlink, appendFile, statfs, access } from 'fs/promises';
1
+ import { randomUUID, randomBytes, createHash } from 'crypto';
2
+ import { readFile, unlink, mkdir, open, rename, statfs, stat, rm, readdir, appendFile, access } from 'fs/promises';
3
3
  import { join, dirname, resolve, sep, relative, isAbsolute } from 'path';
4
4
  import { z, toJSONSchema } from 'zod';
5
- import { existsSync, realpathSync, lstatSync, readlinkSync, mkdirSync, readFileSync, readdirSync } from 'fs';
5
+ import { mkdirSync, readdirSync, existsSync, realpathSync, lstatSync, readlinkSync, readFileSync } from 'fs';
6
6
  import { AsyncLocalStorage } from 'async_hooks';
7
7
  import { createRequire } from 'module';
8
8
  import { homedir } from 'os';
@@ -19,6 +19,24 @@ var __export = (target, all) => {
19
19
  __defProp(target, name, { get: all[name], enumerable: true });
20
20
  };
21
21
 
22
+ // src/internal/default-retriable.ts
23
+ function defaultRetriableForCode(code) {
24
+ switch (code) {
25
+ case "rate_limit":
26
+ case "timeout":
27
+ case "server_error":
28
+ case "network":
29
+ case "provider_unreachable":
30
+ return true;
31
+ default:
32
+ return false;
33
+ }
34
+ }
35
+ var init_default_retriable = __esm({
36
+ "src/internal/default-retriable.ts"() {
37
+ }
38
+ });
39
+
22
40
  // src/internal/security/redact.ts
23
41
  function readEnvOnce() {
24
42
  const raw = process.env.THEOKIT_REDACT_SECRETS;
@@ -169,7 +187,8 @@ __export(errors_exports, {
169
187
  UnsupportedBudgetOperationError: () => UnsupportedBudgetOperationError,
170
188
  UnsupportedRunOperationError: () => UnsupportedRunOperationError,
171
189
  UnsupportedTaskOperationError: () => UnsupportedTaskOperationError,
172
- coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode
190
+ coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode,
191
+ isTransientError: () => isTransientError
173
192
  });
174
193
  function coerceToKnownAgentRunErrorCode(code) {
175
194
  if (code !== void 0 && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {
@@ -201,21 +220,13 @@ function safeStringify(value) {
201
220
  return String(value);
202
221
  }
203
222
  }
204
- function defaultRetriableForCode(code) {
205
- switch (code) {
206
- case "rate_limit":
207
- case "timeout":
208
- case "server_error":
209
- case "network":
210
- case "provider_unreachable":
211
- return true;
212
- default:
213
- return false;
214
- }
223
+ function isTransientError(err) {
224
+ return err instanceof TheokitAgentError && err.isRetryable === true;
215
225
  }
216
226
  var KNOWN_AGENT_RUN_ERROR_CODES, TheokitAgentError, AuthenticationError, RateLimitError, ConfigurationError, IntegrationNotConnectedError, NetworkError, UnknownAgentError, AgentRunError, UnsupportedRunOperationError, CredentialPoolExhaustedError, MemoryAdapterError, InvalidTaskIdError, TaskNotFoundError, UnsupportedTaskOperationError, BudgetExceededError, AgentDisposedError, UnsupportedBudgetOperationError;
217
227
  var init_errors = __esm({
218
228
  "src/errors.ts"() {
229
+ init_default_retriable();
219
230
  init_redact();
220
231
  KNOWN_AGENT_RUN_ERROR_CODES = /* @__PURE__ */ new Set([
221
232
  "rate_limit",
@@ -582,7 +593,7 @@ var init_atomic_write = __esm({
582
593
  }
583
594
  });
584
595
 
585
- // src/internal/runtime/yaml-frontmatter.ts
596
+ // src/internal/runtime/context/yaml-frontmatter.ts
586
597
  function parseSimpleYaml(text) {
587
598
  const fields = {};
588
599
  for (const line of text.split(/\r?\n/)) {
@@ -606,7 +617,7 @@ function coerce(raw) {
606
617
  return raw;
607
618
  }
608
619
  var init_yaml_frontmatter = __esm({
609
- "src/internal/runtime/yaml-frontmatter.ts"() {
620
+ "src/internal/runtime/context/yaml-frontmatter.ts"() {
610
621
  }
611
622
  });
612
623
  async function loadMarkdownEntities(opts) {
@@ -809,11 +820,54 @@ function checkToolWhitelist(toolName) {
809
820
  }
810
821
  var toolWhitelistStore;
811
822
  var init_async_local_storage = __esm({
812
- "src/internal/runtime/async-local-storage.ts"() {
823
+ "src/internal/runtime/concurrency/async-local-storage.ts"() {
813
824
  toolWhitelistStore = new AsyncLocalStorage();
814
825
  }
815
826
  });
816
827
 
828
+ // src/internal/runtime/concurrency/async-semaphore.ts
829
+ function createSemaphore(permits) {
830
+ if (!Number.isInteger(permits) || permits < 1) {
831
+ throw new ConfigurationError(
832
+ `async-semaphore: permits must be a positive integer, got ${permits}`,
833
+ { code: "invalid_concurrency" }
834
+ );
835
+ }
836
+ let active = 0;
837
+ const queue = [];
838
+ function tryGrant() {
839
+ if (active < permits && queue.length > 0) {
840
+ const resolve3 = queue.shift();
841
+ if (resolve3 !== void 0) {
842
+ active += 1;
843
+ resolve3();
844
+ }
845
+ }
846
+ }
847
+ return {
848
+ inFlight: () => active,
849
+ pending: () => queue.length + active,
850
+ async acquire() {
851
+ await new Promise((resolve3) => {
852
+ queue.push(resolve3);
853
+ tryGrant();
854
+ });
855
+ let released = false;
856
+ return () => {
857
+ if (released) return;
858
+ released = true;
859
+ active -= 1;
860
+ tryGrant();
861
+ };
862
+ }
863
+ };
864
+ }
865
+ var init_async_semaphore = __esm({
866
+ "src/internal/runtime/concurrency/async-semaphore.ts"() {
867
+ init_errors();
868
+ }
869
+ });
870
+
817
871
  // src/internal/llm/credential-pool-types.ts
818
872
  var COOLDOWN_MS, DEFAULT_COOLDOWN_MS;
819
873
  var init_credential_pool_types = __esm({
@@ -1158,7 +1212,7 @@ var init_local_agent_plugins = __esm({
1158
1212
  }
1159
1213
  });
1160
1214
 
1161
- // src/internal/runtime/run-until.ts
1215
+ // src/internal/runtime/lifecycle/run-until.ts
1162
1216
  var run_until_exports = {};
1163
1217
  __export(run_until_exports, {
1164
1218
  composeContinuation: () => composeContinuation,
@@ -1251,7 +1305,7 @@ Your last response was:
1251
1305
  ${lastResponse.slice(0, 1e3)}`;
1252
1306
  }
1253
1307
  var init_run_until = __esm({
1254
- "src/internal/runtime/run-until.ts"() {
1308
+ "src/internal/runtime/lifecycle/run-until.ts"() {
1255
1309
  }
1256
1310
  });
1257
1311
 
@@ -1362,16 +1416,16 @@ var init_judge_call = __esm({
1362
1416
  // src/internal/runtime/registry/agent-factory-registry.ts
1363
1417
  var agent_factory_registry_exports = {};
1364
1418
  __export(agent_factory_registry_exports, {
1365
- getAgentCreate: () => getAgentCreate,
1366
- setAgentCreate: () => setAgentCreate
1419
+ getAgentFacade: () => getAgentFacade,
1420
+ setAgentFacade: () => setAgentFacade
1367
1421
  });
1368
- function setAgentCreate(fn) {
1369
- registered3 = fn;
1422
+ function setAgentFacade(facade) {
1423
+ registered3 = facade;
1370
1424
  }
1371
- function getAgentCreate() {
1425
+ function getAgentFacade() {
1372
1426
  if (registered3 === void 0) {
1373
1427
  throw new Error(
1374
- "internal: Agent.create not registered. The `agent.ts` module must be loaded before LocalAgent.runUntil/fork are invoked."
1428
+ "internal: Agent facade not registered. The `agent.ts` module must be loaded before internal subsystems (LocalAgent.runUntil/fork, eval, scorers, cron) invoke it."
1375
1429
  );
1376
1430
  }
1377
1431
  return registered3;
@@ -1382,7 +1436,7 @@ var init_agent_factory_registry = __esm({
1382
1436
  }
1383
1437
  });
1384
1438
 
1385
- // src/internal/runtime/fork-agent.ts
1439
+ // src/internal/runtime/lifecycle/fork-agent.ts
1386
1440
  var fork_agent_exports = {};
1387
1441
  __export(fork_agent_exports, {
1388
1442
  filterMemoryPlugins: () => filterMemoryPlugins,
@@ -1442,7 +1496,7 @@ function extractUsage(result) {
1442
1496
  };
1443
1497
  }
1444
1498
  var init_fork_agent = __esm({
1445
- "src/internal/runtime/fork-agent.ts"() {
1499
+ "src/internal/runtime/lifecycle/fork-agent.ts"() {
1446
1500
  init_async_local_storage();
1447
1501
  init_local_agent_plugins();
1448
1502
  }
@@ -1465,49 +1519,6 @@ var init_task = __esm({
1465
1519
  }
1466
1520
  });
1467
1521
 
1468
- // src/internal/runtime/async-semaphore.ts
1469
- function createSemaphore(permits) {
1470
- if (!Number.isInteger(permits) || permits < 1) {
1471
- throw new ConfigurationError(
1472
- `async-semaphore: permits must be a positive integer, got ${permits}`,
1473
- { code: "invalid_concurrency" }
1474
- );
1475
- }
1476
- let active = 0;
1477
- const queue = [];
1478
- function tryGrant() {
1479
- if (active < permits && queue.length > 0) {
1480
- const resolve3 = queue.shift();
1481
- if (resolve3 !== void 0) {
1482
- active += 1;
1483
- resolve3();
1484
- }
1485
- }
1486
- }
1487
- return {
1488
- inFlight: () => active,
1489
- pending: () => queue.length + active,
1490
- async acquire() {
1491
- await new Promise((resolve3) => {
1492
- queue.push(resolve3);
1493
- tryGrant();
1494
- });
1495
- let released = false;
1496
- return () => {
1497
- if (released) return;
1498
- released = true;
1499
- active -= 1;
1500
- tryGrant();
1501
- };
1502
- }
1503
- };
1504
- }
1505
- var init_async_semaphore = __esm({
1506
- "src/internal/runtime/async-semaphore.ts"() {
1507
- init_errors();
1508
- }
1509
- });
1510
-
1511
1522
  // src/internal/task/ring-buffer.ts
1512
1523
  var RingBuffer;
1513
1524
  var init_ring_buffer = __esm({
@@ -3079,8 +3090,21 @@ function sanitizeIdentifier(input, options) {
3079
3090
  }
3080
3091
  return input.toLowerCase();
3081
3092
  }
3093
+ function safeFilenameForId(id, options) {
3094
+ if (id.length === 0) {
3095
+ throw new ConfigurationError("Filename id must be a non-empty string", {
3096
+ code: "invalid_filename_id"
3097
+ });
3098
+ }
3099
+ const maxLen = options?.maxLen;
3100
+ const lower = id.toLowerCase();
3101
+ if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {
3102
+ return lower;
3103
+ }
3104
+ return `h-${createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
3105
+ }
3082
3106
 
3083
- // src/internal/runtime/default-model.ts
3107
+ // src/internal/runtime/config/default-model.ts
3084
3108
  var DEFAULT_AGENTIC_MODEL_ID = "google/gemini-2.0-flash-001";
3085
3109
 
3086
3110
  // src/internal/runtime/registry/agent-registry-store.ts
@@ -3401,7 +3425,7 @@ async function flushRegistrySaves(cwd) {
3401
3425
  }
3402
3426
  }
3403
3427
 
3404
- // src/internal/runtime/system-prompt.ts
3428
+ // src/internal/runtime/system-prompt/system-prompt.ts
3405
3429
  async function resolveSystemPrompt(agent, override, ctx) {
3406
3430
  if (override !== void 0) return override;
3407
3431
  if (agent === void 0) return void 0;
@@ -5784,28 +5808,6 @@ function parseDecisionFromStdout(stdout) {
5784
5808
  return { decision: "allow" };
5785
5809
  }
5786
5810
 
5787
- // src/internal/runtime/memory/memory-path-selector.ts
5788
- var PORT_MEMORY_PATH_ENV_VAR = "THEOKIT_PORT_MEMORY_PATH";
5789
- function shouldUsePortMemoryPath() {
5790
- const env = globalThis.process?.env;
5791
- if (env === void 0) return false;
5792
- const val = env[PORT_MEMORY_PATH_ENV_VAR];
5793
- return val === "1" || val === "true";
5794
- }
5795
- function resolveMemoryProviderForLoop(consumerSupplied, defaultAdapter, portPathEnabled) {
5796
- if (consumerSupplied !== void 0) return consumerSupplied;
5797
- if (portPathEnabled) return defaultAdapter;
5798
- return void 0;
5799
- }
5800
- function resolveMemoryToolsForLoop(legacyTools, portPathEnabled) {
5801
- if (portPathEnabled) return void 0;
5802
- return legacyTools;
5803
- }
5804
- function resolveActiveMemorySummaryForSend(legacySummary, portPathEnabled) {
5805
- if (portPathEnabled) return void 0;
5806
- return legacySummary;
5807
- }
5808
-
5809
5811
  // src/internal/memory/storage/session-summary-writer.ts
5810
5812
  init_atomic_write();
5811
5813
  var MAX_TURN_CHARS = 2e3;
@@ -5813,10 +5815,7 @@ function sessionsDir(cwd) {
5813
5815
  return join(memoryDir(cwd), "sessions");
5814
5816
  }
5815
5817
  function sessionSummaryPath(cwd, runId) {
5816
- return join(sessionsDir(cwd), `${sanitizeRunId(runId)}.md`);
5817
- }
5818
- function sanitizeRunId(runId) {
5819
- return runId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
5818
+ return join(sessionsDir(cwd), `${safeFilenameForId(runId, { maxLen: 128 })}.md`);
5820
5819
  }
5821
5820
  function truncate(text) {
5822
5821
  if (text.length <= MAX_TURN_CHARS) return text;
@@ -5849,6 +5848,28 @@ async function writeSessionSummary(input) {
5849
5848
  await replaceFileAtomic(path, body);
5850
5849
  }
5851
5850
 
5851
+ // src/internal/runtime/memory/memory-path-selector.ts
5852
+ var PORT_MEMORY_PATH_ENV_VAR = "THEOKIT_PORT_MEMORY_PATH";
5853
+ function shouldUsePortMemoryPath() {
5854
+ const env = globalThis.process?.env;
5855
+ if (env === void 0) return false;
5856
+ const val = env[PORT_MEMORY_PATH_ENV_VAR];
5857
+ return val === "1" || val === "true";
5858
+ }
5859
+ function resolveMemoryProviderForLoop(consumerSupplied, defaultAdapter, portPathEnabled) {
5860
+ if (consumerSupplied !== void 0) return consumerSupplied;
5861
+ if (portPathEnabled) return defaultAdapter;
5862
+ return void 0;
5863
+ }
5864
+ function resolveMemoryToolsForLoop(legacyTools, portPathEnabled) {
5865
+ if (portPathEnabled) return void 0;
5866
+ return legacyTools;
5867
+ }
5868
+ function resolveActiveMemorySummaryForSend(legacySummary, portPathEnabled) {
5869
+ if (portPathEnabled) return void 0;
5870
+ return legacySummary;
5871
+ }
5872
+
5852
5873
  // src/internal/runtime/session/agent-session-store.ts
5853
5874
  init_atomic_write();
5854
5875
  var VALID_ROLES = /* @__PURE__ */ new Set([
@@ -6105,7 +6126,7 @@ function clearSession(agentId) {
6105
6126
  sessions.delete(agentId);
6106
6127
  }
6107
6128
 
6108
- // src/internal/runtime/post-run-lifecycle.ts
6129
+ // src/internal/runtime/lifecycle/post-run-lifecycle.ts
6109
6130
  async function runPostRunLifecycle(inputs) {
6110
6131
  const {
6111
6132
  run,
@@ -6337,7 +6358,7 @@ var liveAgentRegistry = new LiveAgentRegistry();
6337
6358
  // src/internal/runtime/skills/subagents-loader.ts
6338
6359
  init_errors();
6339
6360
 
6340
- // src/internal/runtime/workspace-dir.ts
6361
+ // src/internal/runtime/config/workspace-dir.ts
6341
6362
  init_errors();
6342
6363
  async function readWorkspaceDir(root, errorCode, describe) {
6343
6364
  try {
@@ -6623,7 +6644,7 @@ var SystemPromptPipeline = class _SystemPromptPipeline {
6623
6644
  }
6624
6645
  };
6625
6646
 
6626
- // src/internal/runtime/validate-agent-options.ts
6647
+ // src/internal/runtime/validation/validate-agent-options.ts
6627
6648
  init_errors();
6628
6649
  function validateAgentOptions(options) {
6629
6650
  rejectProgrammaticHooks(options);
@@ -6818,6 +6839,71 @@ function validateMemory(options) {
6818
6839
  }
6819
6840
  }
6820
6841
 
6842
+ // src/internal/runtime/config/providers-manager.ts
6843
+ var ProvidersManagerImpl = class {
6844
+ constructor(model, providers, plugins) {
6845
+ this.model = model;
6846
+ this.providers = providers;
6847
+ this.plugins = plugins;
6848
+ }
6849
+ model;
6850
+ providers;
6851
+ plugins;
6852
+ routes() {
6853
+ const resolved = [];
6854
+ const modelProvider = providerFromModel(this.model);
6855
+ const seen = /* @__PURE__ */ new Set();
6856
+ if (this.providers?.routes !== void 0) {
6857
+ for (const route of this.providers.routes) {
6858
+ const resolvedRoute = resolveRoute(route, modelProvider, this.plugins);
6859
+ if (!seen.has(route.capability)) {
6860
+ seen.add(route.capability);
6861
+ resolved.push(resolvedRoute);
6862
+ }
6863
+ }
6864
+ }
6865
+ return Promise.resolve(resolved);
6866
+ }
6867
+ };
6868
+ function providerFromModel(model) {
6869
+ if (model === void 0) return void 0;
6870
+ const id = model.id;
6871
+ if (id.includes(":")) return id.split(":")[0];
6872
+ return void 0;
6873
+ }
6874
+ function resolveRoute(route, modelProvider, plugins) {
6875
+ if (route.capability === "chat" && modelProvider === route.provider) {
6876
+ const modelName = extractModelName(modelProvider, route);
6877
+ const base = {
6878
+ capability: route.capability,
6879
+ provider: route.provider,
6880
+ reason: "explicit-model-provider"
6881
+ };
6882
+ if (modelName !== void 0) base.model = modelName;
6883
+ return base;
6884
+ }
6885
+ if (plugins?.enabled !== void 0 && plugins.enabled.length > 0) {
6886
+ return {
6887
+ capability: route.capability,
6888
+ provider: route.provider,
6889
+ reason: "first-available-plugin-provider"
6890
+ };
6891
+ }
6892
+ return {
6893
+ capability: route.capability,
6894
+ provider: route.provider,
6895
+ reason: "explicit-route"
6896
+ };
6897
+ }
6898
+ function extractModelName(prefix, route) {
6899
+ if (route.model !== void 0) return route.model;
6900
+ return prefix === route.provider ? defaultModelForProvider(prefix) : void 0;
6901
+ }
6902
+ function defaultModelForProvider(provider) {
6903
+ if (provider === "anthropic") return "claude-3-7-sonnet";
6904
+ return void 0;
6905
+ }
6906
+
6821
6907
  // src/internal/runtime/context/context-manager.ts
6822
6908
  init_errors();
6823
6909
  init_markdown_config_loader();
@@ -7614,71 +7700,6 @@ async function loadPluginManifestFromMarkdown(pluginsRoot, folderName) {
7614
7700
  return metadata;
7615
7701
  }
7616
7702
 
7617
- // src/internal/runtime/providers-manager.ts
7618
- var ProvidersManagerImpl = class {
7619
- constructor(model, providers, plugins) {
7620
- this.model = model;
7621
- this.providers = providers;
7622
- this.plugins = plugins;
7623
- }
7624
- model;
7625
- providers;
7626
- plugins;
7627
- routes() {
7628
- const resolved = [];
7629
- const modelProvider = providerFromModel(this.model);
7630
- const seen = /* @__PURE__ */ new Set();
7631
- if (this.providers?.routes !== void 0) {
7632
- for (const route of this.providers.routes) {
7633
- const resolvedRoute = resolveRoute(route, modelProvider, this.plugins);
7634
- if (!seen.has(route.capability)) {
7635
- seen.add(route.capability);
7636
- resolved.push(resolvedRoute);
7637
- }
7638
- }
7639
- }
7640
- return Promise.resolve(resolved);
7641
- }
7642
- };
7643
- function providerFromModel(model) {
7644
- if (model === void 0) return void 0;
7645
- const id = model.id;
7646
- if (id.includes(":")) return id.split(":")[0];
7647
- return void 0;
7648
- }
7649
- function resolveRoute(route, modelProvider, plugins) {
7650
- if (route.capability === "chat" && modelProvider === route.provider) {
7651
- const modelName = extractModelName(modelProvider, route);
7652
- const base = {
7653
- capability: route.capability,
7654
- provider: route.provider,
7655
- reason: "explicit-model-provider"
7656
- };
7657
- if (modelName !== void 0) base.model = modelName;
7658
- return base;
7659
- }
7660
- if (plugins?.enabled !== void 0 && plugins.enabled.length > 0) {
7661
- return {
7662
- capability: route.capability,
7663
- provider: route.provider,
7664
- reason: "first-available-plugin-provider"
7665
- };
7666
- }
7667
- return {
7668
- capability: route.capability,
7669
- provider: route.provider,
7670
- reason: "explicit-route"
7671
- };
7672
- }
7673
- function extractModelName(prefix, route) {
7674
- if (route.model !== void 0) return route.model;
7675
- return prefix === route.provider ? defaultModelForProvider(prefix) : void 0;
7676
- }
7677
- function defaultModelForProvider(provider) {
7678
- if (provider === "anthropic") return "claude-3-7-sonnet";
7679
- return void 0;
7680
- }
7681
-
7682
7703
  // src/internal/runtime/skills/skills-manager.ts
7683
7704
  init_errors();
7684
7705
 
@@ -8025,7 +8046,7 @@ var IterationBudget = class {
8025
8046
  }
8026
8047
  };
8027
8048
 
8028
- // src/internal/runtime/validate-response.ts
8049
+ // src/internal/runtime/validation/validate-response.ts
8029
8050
  function validateResponse(response) {
8030
8051
  const trimmed = response.content.trim();
8031
8052
  const toolCallsArr = Array.isArray(response.toolCalls) ? response.toolCalls : [];
@@ -8411,6 +8432,27 @@ async function emitTextDeltaCallback(inputs, text) {
8411
8432
  // src/internal/agent-loop/tool-dispatch.ts
8412
8433
  init_async_local_storage();
8413
8434
 
8435
+ // src/internal/runtime/concurrency/map-with-concurrency.ts
8436
+ init_async_semaphore();
8437
+ var NEVER_ABORT = new AbortController().signal;
8438
+ async function mapWithConcurrency(items, concurrency, fn, options) {
8439
+ const semaphore = createSemaphore(concurrency);
8440
+ const signal = NEVER_ABORT;
8441
+ return Promise.all(
8442
+ items.map(async (item, index) => {
8443
+ const release = await semaphore.acquire();
8444
+ try {
8445
+ if (signal.aborted) {
8446
+ throw signal.reason instanceof Error ? signal.reason : new Error("mapWithConcurrency: aborted");
8447
+ }
8448
+ return await fn(item, index, signal);
8449
+ } finally {
8450
+ release();
8451
+ }
8452
+ })
8453
+ );
8454
+ }
8455
+
8414
8456
  // src/internal/tool-dispatch/repair-middleware.ts
8415
8457
  var DECIMAL_RE = /^-?\d+(\.\d+)?$/;
8416
8458
  function repairToolCall(raw, registry) {
@@ -8484,7 +8526,7 @@ function coerceArgsToSchema(args, schema) {
8484
8526
  return { value: out, changed };
8485
8527
  }
8486
8528
 
8487
- // src/internal/runtime/shell-tool.ts
8529
+ // src/internal/runtime/tools/shell-tool.ts
8488
8530
  async function runShell(options) {
8489
8531
  if (options.sandbox === true && isObviouslyUnsafe(options.command)) {
8490
8532
  return {
@@ -8585,38 +8627,12 @@ ${result.stderr}`.trim();
8585
8627
  // src/internal/agent-loop/tool-dispatch.ts
8586
8628
  async function dispatchTools(inputs, tools, toolCalls, events) {
8587
8629
  const maxConcurrent = inputs.maxConcurrentTools ?? 4;
8588
- return boundedParallel(
8589
- maxConcurrent,
8630
+ return mapWithConcurrency(
8590
8631
  toolCalls,
8632
+ maxConcurrent,
8591
8633
  (call) => dispatchSingleCall(inputs, tools, call, events)
8592
8634
  );
8593
8635
  }
8594
- async function boundedParallel(max, items, fn) {
8595
- let running = 0;
8596
- const queue = [];
8597
- async function acquire() {
8598
- if (running < max) {
8599
- running++;
8600
- return;
8601
- }
8602
- await new Promise((resolve3) => queue.push(resolve3));
8603
- running++;
8604
- }
8605
- function release() {
8606
- running--;
8607
- if (queue.length > 0) queue.shift()();
8608
- }
8609
- return Promise.all(
8610
- items.map(async (item) => {
8611
- await acquire();
8612
- try {
8613
- return await fn(item);
8614
- } finally {
8615
- release();
8616
- }
8617
- })
8618
- );
8619
- }
8620
8636
  async function dispatchSingleCall(inputs, tools, call, events) {
8621
8637
  const { call: workingCall, repairs } = applyRepairAndExtractCall(tools, call);
8622
8638
  const callId = generateCallId();
@@ -9685,10 +9701,10 @@ function registerBuiltins() {
9685
9701
  registerCatalogProviders();
9686
9702
  }
9687
9703
 
9688
- // src/internal/errors/mappers/anthropic.ts
9704
+ // src/internal/error-mappers/anthropic.ts
9689
9705
  init_errors();
9690
9706
 
9691
- // src/internal/errors/mappers/shared.ts
9707
+ // src/internal/error-mappers/shared.ts
9692
9708
  var RAW_MAX_BYTES = 2048;
9693
9709
  function parseRetryAfter(headers) {
9694
9710
  if (headers === void 0) return void 0;
@@ -9717,7 +9733,7 @@ function buildErrorMetadata(args) {
9717
9733
  };
9718
9734
  }
9719
9735
 
9720
- // src/internal/errors/mappers/anthropic.ts
9736
+ // src/internal/error-mappers/anthropic.ts
9721
9737
  function mapAnthropicError(args) {
9722
9738
  const { status, body, headers, endpoint } = args;
9723
9739
  const code = mapAnthropicStatusToCode(status, body);
@@ -10057,7 +10073,7 @@ function buildAnthropicBody(request) {
10057
10073
  // src/internal/llm/bedrock-anthropic.ts
10058
10074
  init_errors();
10059
10075
 
10060
- // src/internal/errors/mappers/bedrock.ts
10076
+ // src/internal/error-mappers/bedrock.ts
10061
10077
  init_errors();
10062
10078
  function classifyBedrockError(args, awsType, message) {
10063
10079
  if (args.status === 429 || awsType.includes("Throttling") || awsType.includes("TooManyRequests")) {
@@ -10194,7 +10210,7 @@ function buildBedrockBody(request) {
10194
10210
  init_credential_pool();
10195
10211
  init_credential_pool_context();
10196
10212
 
10197
- // src/internal/errors/mappers/openai-compatible.ts
10213
+ // src/internal/error-mappers/openai-compatible.ts
10198
10214
  init_errors();
10199
10215
  function mapOpenAICompatibleError(args) {
10200
10216
  const { providerId, status, body, headers, endpoint } = args;
@@ -10358,7 +10374,7 @@ function readOpenAiContent(body) {
10358
10374
  return void 0;
10359
10375
  }
10360
10376
 
10361
- // src/internal/errors/mappers/ollama.ts
10377
+ // src/internal/error-mappers/ollama.ts
10362
10378
  init_errors();
10363
10379
  function mapOllamaTransportError(args) {
10364
10380
  if (args.providerId !== "ollama") return void 0;
@@ -11008,7 +11024,7 @@ function abortError2(signal) {
11008
11024
  // src/internal/llm/vertex-anthropic.ts
11009
11025
  init_errors();
11010
11026
 
11011
- // src/internal/errors/mappers/vertex.ts
11027
+ // src/internal/error-mappers/vertex.ts
11012
11028
  init_errors();
11013
11029
  var VERTEX_RULES = [
11014
11030
  { test: (s, e) => s === 429 || e === "RESOURCE_EXHAUSTED", code: "rate_limit" },
@@ -11550,6 +11566,16 @@ function resolveMcpCwd(configCwd) {
11550
11566
  return safePathJoin(process.cwd(), configCwd);
11551
11567
  }
11552
11568
 
11569
+ // src/internal/providers/register-plugin-providers.ts
11570
+ function registerPluginProviderProfiles(entries) {
11571
+ let registered4 = 0;
11572
+ for (const entry of entries) {
11573
+ registerProvider(entry.profile);
11574
+ registered4 += 1;
11575
+ }
11576
+ return registered4;
11577
+ }
11578
+
11553
11579
  // src/internal/tool-registry/personality-filter.ts
11554
11580
  init_hooks_source();
11555
11581
  function applyPersonalityFilter(exposedTools, whitelist, opts) {
@@ -11626,12 +11652,27 @@ function createRealLocalRun(options) {
11626
11652
  registerRun(handle);
11627
11653
  return handle;
11628
11654
  }
11629
- function buildLoopInputs(options, runId, userText) {
11655
+ var pluginProvidersAnnounced = false;
11656
+ function resolveRunProvider(options) {
11630
11657
  registerBuiltins();
11658
+ const profiles = options.pluginManager?.aggregated.providerProfiles ?? [];
11659
+ const registered4 = registerPluginProviderProfiles(profiles);
11660
+ if (registered4 > 0 && !pluginProvidersAnnounced) {
11661
+ pluginProvidersAnnounced = true;
11662
+ const names = profiles.map((e) => e.profile.name).join(", ");
11663
+ process.stderr.write(
11664
+ `[theokit-sdk] registered ${registered4} plugin provider profile(s): ${names}
11665
+ `
11666
+ );
11667
+ }
11631
11668
  const parsedModel = parseModelId(options.model?.id);
11632
11669
  const inferredProvider = parsedModel.provider !== void 0 && getProviderProfile(parsedModel.provider) !== void 0 ? parsedModel.provider : void 0;
11633
11670
  const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? inferredProvider ?? detectPrimaryProvider();
11634
11671
  const effectiveModelId = inferredProvider !== void 0 ? parsedModel.name : options.model?.id ?? "claude-sonnet-4-6";
11672
+ return { primary, effectiveModelId };
11673
+ }
11674
+ function buildLoopInputs(options, runId, userText) {
11675
+ const { primary, effectiveModelId } = resolveRunProvider(options);
11635
11676
  const fallback = options.agentOptions.providers?.fallback;
11636
11677
  const apiKeys = options.agentOptions.providers?.apiKeys;
11637
11678
  const credentialPoolStrategy = options.agentOptions.providers?.credentialPoolStrategy;
@@ -12249,7 +12290,7 @@ async function embedTexts(input) {
12249
12290
  pending
12250
12291
  });
12251
12292
  }
12252
- await runBatches(input, pending, results);
12293
+ await embedInBoundedBatches(input, pending, results);
12253
12294
  return results.map((v) => v ?? new Array(dimension).fill(0));
12254
12295
  }
12255
12296
  function classifyEntry(args) {
@@ -12268,45 +12309,34 @@ function classifyEntry(args) {
12268
12309
  args.pending.push({ index: args.index, text: args.text, key });
12269
12310
  }
12270
12311
  var MAX_CONCURRENT_BATCHES = 3;
12271
- async function runBatches(input, pending, results) {
12312
+ async function embedInBoundedBatches(input, pending, results) {
12272
12313
  const batches = [];
12273
12314
  for (let offset = 0; offset < pending.length; offset += MAX_BATCH) {
12274
12315
  batches.push(pending.slice(offset, offset + MAX_BATCH));
12275
12316
  }
12276
- let running = 0;
12277
- const queue = [];
12278
- await Promise.all(batches.map((batch) => processBatch(input, batch, results, acquire, release)));
12279
- async function acquire() {
12280
- if (running >= MAX_CONCURRENT_BATCHES) await new Promise((r) => queue.push(r));
12281
- running++;
12282
- }
12283
- function release() {
12284
- running--;
12285
- if (queue.length > 0) queue.shift()();
12286
- }
12317
+ await mapWithConcurrency(
12318
+ batches,
12319
+ MAX_CONCURRENT_BATCHES,
12320
+ (batch) => processBatch(input, batch, results)
12321
+ );
12287
12322
  }
12288
- async function processBatch(input, batch, results, acquire, release) {
12289
- await acquire();
12290
- try {
12291
- const vectors = await embedBatch({
12292
- apiKey: input.apiKey,
12293
- baseUrl: input.baseUrl,
12294
- embeddingsPath: input.embeddingsPath,
12295
- model: input.model,
12296
- inputs: batch.map((b) => b.text),
12297
- fetchImpl: input.fetchImpl,
12298
- stats: input.stats,
12299
- providerId: input.providerId
12300
- });
12301
- for (let j = 0; j < batch.length; j++) {
12302
- const slot = batch[j];
12303
- const vector = vectors[j];
12304
- if (slot === void 0 || vector === void 0) continue;
12305
- results[slot.index] = vector;
12306
- input.cache.set(slot.key, vector);
12307
- }
12308
- } finally {
12309
- release();
12323
+ async function processBatch(input, batch, results) {
12324
+ const vectors = await embedBatch({
12325
+ apiKey: input.apiKey,
12326
+ baseUrl: input.baseUrl,
12327
+ embeddingsPath: input.embeddingsPath,
12328
+ model: input.model,
12329
+ inputs: batch.map((b) => b.text),
12330
+ fetchImpl: input.fetchImpl,
12331
+ stats: input.stats,
12332
+ providerId: input.providerId
12333
+ });
12334
+ for (let j = 0; j < batch.length; j++) {
12335
+ const slot = batch[j];
12336
+ const vector = vectors[j];
12337
+ if (slot === void 0 || vector === void 0) continue;
12338
+ results[slot.index] = vector;
12339
+ input.cache.set(slot.key, vector);
12310
12340
  }
12311
12341
  }
12312
12342
  async function embedBatch(opts) {
@@ -12739,7 +12769,7 @@ function sanitizeFts5Query(query) {
12739
12769
  return text.trim();
12740
12770
  }
12741
12771
 
12742
- // src/internal/memory/index-db.ts
12772
+ // src/internal/persistence/sqlite-open.ts
12743
12773
  init_errors();
12744
12774
 
12745
12775
  // src/internal/persistence/sqlite-wal.ts
@@ -12767,6 +12797,57 @@ function logFallback(label, reason) {
12767
12797
  );
12768
12798
  }
12769
12799
 
12800
+ // src/internal/persistence/sqlite-open.ts
12801
+ async function openSqliteResilient(options) {
12802
+ await mkdir(dirname(options.filePath), { recursive: true });
12803
+ try {
12804
+ return await openConcrete(options);
12805
+ } catch (cause) {
12806
+ if (options.recoverCorrupt !== false && isCorruptionError(cause)) {
12807
+ await renameAside(options.filePath, options.label ?? "sqlite");
12808
+ return await openConcrete(options);
12809
+ }
12810
+ throw cause;
12811
+ }
12812
+ }
12813
+ async function openConcrete(options) {
12814
+ const db = await loadDriver(options.filePath);
12815
+ applyWalWithFallback(db, options.label ?? "sqlite");
12816
+ await options.onOpen?.(db);
12817
+ return db;
12818
+ }
12819
+ async function loadDriver(filePath) {
12820
+ try {
12821
+ const mod = await import('better-sqlite3');
12822
+ const Ctor = mod.default ?? mod;
12823
+ if (typeof Ctor !== "function") {
12824
+ throw new Error(`better-sqlite3 export is not a constructor (got ${typeof Ctor})`);
12825
+ }
12826
+ return new Ctor(filePath);
12827
+ } catch (cause) {
12828
+ const message = cause instanceof Error ? cause.message : String(cause);
12829
+ throw new ConfigurationError(
12830
+ `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
12831
+ { code: "sqlite_driver_unavailable", cause }
12832
+ );
12833
+ }
12834
+ }
12835
+ function isCorruptionError(cause) {
12836
+ if (!(cause instanceof Error)) return false;
12837
+ const msg = cause.message.toLowerCase();
12838
+ return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
12839
+ }
12840
+ async function renameAside(filePath, label) {
12841
+ const asidePath = `${filePath}.corrupt-${Date.now()}`;
12842
+ await rename(filePath, asidePath).catch(() => void 0);
12843
+ await rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
12844
+ await rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
12845
+ process.stderr.write(
12846
+ `[theokit-sdk] ${label} database corrupt; renamed aside to ${asidePath} and rebuilt schema
12847
+ `
12848
+ );
12849
+ }
12850
+
12770
12851
  // src/internal/memory/index-schema.ts
12771
12852
  var SCHEMA_STATEMENTS = [
12772
12853
  `CREATE TABLE IF NOT EXISTS files (
@@ -12810,52 +12891,15 @@ var PRAGMA_STATEMENTS = [
12810
12891
 
12811
12892
  // src/internal/memory/index-db.ts
12812
12893
  async function openMemoryDb(opts) {
12813
- await mkdir(dirname(opts.filePath), { recursive: true });
12814
- try {
12815
- return await openConcrete(opts.filePath);
12816
- } catch (cause) {
12817
- if (opts.recoverCorrupt !== false && isCorruptionError(cause)) {
12818
- await renameAside(opts.filePath);
12819
- return await openConcrete(opts.filePath);
12894
+ return openSqliteResilient({
12895
+ filePath: opts.filePath,
12896
+ label: "memory-index",
12897
+ recoverCorrupt: opts.recoverCorrupt,
12898
+ onOpen: (db) => {
12899
+ for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
12900
+ for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
12820
12901
  }
12821
- throw cause;
12822
- }
12823
- }
12824
- async function openConcrete(filePath) {
12825
- const db = await loadDriver(filePath);
12826
- applyWalWithFallback(db, "memory-index");
12827
- for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
12828
- for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
12829
- return db;
12830
- }
12831
- async function loadDriver(filePath) {
12832
- try {
12833
- const mod = await import('better-sqlite3');
12834
- const Ctor = mod.default ?? mod;
12835
- const db = new Ctor(filePath);
12836
- return db;
12837
- } catch (cause) {
12838
- const message = cause instanceof Error ? cause.message : String(cause);
12839
- throw new ConfigurationError(
12840
- `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
12841
- { code: "sqlite_driver_unavailable", cause }
12842
- );
12843
- }
12844
- }
12845
- function isCorruptionError(cause) {
12846
- if (!(cause instanceof Error)) return false;
12847
- const msg = cause.message.toLowerCase();
12848
- return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
12849
- }
12850
- async function renameAside(filePath) {
12851
- const asidePath = `${filePath}.corrupt-${Date.now()}`;
12852
- await rename(filePath, asidePath).catch(() => void 0);
12853
- await rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
12854
- await rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
12855
- process.stderr.write(
12856
- `[theokit-sdk] memory index corrupt; renamed aside to ${asidePath} and rebuilt schema
12857
- `
12858
- );
12902
+ });
12859
12903
  }
12860
12904
  function defaultIndexPath(cwd) {
12861
12905
  return join(cwd, ".theokit", "memory", ".index", "memory.sqlite");
@@ -14258,8 +14302,8 @@ function localAgentRunUntil(agent, goal, options) {
14258
14302
  async function* wrap() {
14259
14303
  const { runUntilImpl: runUntilImpl2 } = await Promise.resolve().then(() => (init_run_until(), run_until_exports));
14260
14304
  const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
14261
- const { getAgentCreate: getAgentCreate2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14262
- const create = getAgentCreate2();
14305
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14306
+ const create = getAgentFacade2().create;
14263
14307
  const deps = {
14264
14308
  judge: async (ctx, opts) => judgeCallImpl2(ctx, opts, { create })
14265
14309
  };
@@ -14269,9 +14313,9 @@ function localAgentRunUntil(agent, goal, options) {
14269
14313
  }
14270
14314
  async function localAgentFork(parent, options) {
14271
14315
  const { forkAgentImpl: forkAgentImpl2 } = await Promise.resolve().then(() => (init_fork_agent(), fork_agent_exports));
14272
- const { getAgentCreate: getAgentCreate2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14316
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14273
14317
  const { withPersonalityContext: withPersonalityContext2 } = await Promise.resolve().then(() => (init_context(), context_exports));
14274
- const create = getAgentCreate2();
14318
+ const create = getAgentFacade2().create;
14275
14319
  return withPersonalityContext2(
14276
14320
  { slug: parent.personalitySlugSnapshot, isFork: true },
14277
14321
  () => forkAgentImpl2(parent, options, { create })
@@ -14292,7 +14336,7 @@ async function persistMemoryFactIfWritePrompt(workspaceCwd, memoryConfig, userTe
14292
14336
  // src/internal/runtime/local-agent/local-agent-send.ts
14293
14337
  init_errors();
14294
14338
 
14295
- // src/internal/runtime/abort-utils.ts
14339
+ // src/internal/runtime/concurrency/abort-utils.ts
14296
14340
  function anySignal(signals) {
14297
14341
  const filtered = signals.filter((s) => s !== void 0);
14298
14342
  if (filtered.length === 0) {
@@ -15321,7 +15365,16 @@ async function getOrCreateUncached(agentId, options) {
15321
15365
  throw err;
15322
15366
  }
15323
15367
  }
15324
- setAgentCreate((options) => Agent.create(options));
15368
+ setAgentFacade({
15369
+ create: (options) => Agent.create(options),
15370
+ prompt: (message, options) => Agent.prompt(message, options),
15371
+ get: (agentId) => Agent.get(agentId),
15372
+ resume: (agentId, options) => Agent.resume(agentId, options),
15373
+ batch: (prompts, options) => Agent.batch(prompts, options)
15374
+ });
15375
+
15376
+ // src/internal/eval/runner.ts
15377
+ init_agent_factory_registry();
15325
15378
 
15326
15379
  // src/internal/eval/aggregate.ts
15327
15380
  function percentile(sorted, p) {
@@ -15624,7 +15677,7 @@ async function runRowsViaBatch(entries, agentOptions, scorers, concurrency, sign
15624
15677
  concurrency,
15625
15678
  ...signal !== void 0 ? { signal } : {}
15626
15679
  };
15627
- const batchResults = await Agent.batch(prompts, batchOpts);
15680
+ const batchResults = await getAgentFacade().batch(prompts, batchOpts);
15628
15681
  const rows = [];
15629
15682
  for (let i = 0; i < batchResults.length; i += 1) {
15630
15683
  const entry = entries[i];
@@ -15697,6 +15750,7 @@ async function runEval(options, runOpts) {
15697
15750
  }
15698
15751
 
15699
15752
  // src/internal/scorers/llm-judge.ts
15753
+ init_agent_factory_registry();
15700
15754
  function buildPrompt(subject, criteria, rubric, expected) {
15701
15755
  const scoreHint = rubric === "discrete" ? "between 0 and 1 (use 0 for fail, 1 for pass)" : "between 0.0 and 1.0";
15702
15756
  const expectedBlock = expected !== void 0 ? `EXPECTED (reference): ${JSON.stringify(expected)}
@@ -15721,7 +15775,7 @@ function buildPrompt(subject, criteria, rubric, expected) {
15721
15775
  var SCORE_REGEX = /\{\s*"score"\s*:\s*([0-9]*\.?[0-9]+)\s*,\s*"reason"\s*:\s*"([^"]*)"\s*\}/;
15722
15776
  async function callJudge(message, options) {
15723
15777
  try {
15724
- const result = await Agent.prompt(message, {
15778
+ const result = await getAgentFacade().prompt(message, {
15725
15779
  apiKey: options.apiKey,
15726
15780
  model: options.model,
15727
15781
  local: { cwd: process.cwd(), sandboxOptions: { enabled: false } },