@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/a2a/index.js CHANGED
@@ -129,6 +129,24 @@ var init_agent_builder = __esm({
129
129
  }
130
130
  });
131
131
 
132
+ // src/internal/default-retriable.ts
133
+ function defaultRetriableForCode(code) {
134
+ switch (code) {
135
+ case "rate_limit":
136
+ case "timeout":
137
+ case "server_error":
138
+ case "network":
139
+ case "provider_unreachable":
140
+ return true;
141
+ default:
142
+ return false;
143
+ }
144
+ }
145
+ var init_default_retriable = __esm({
146
+ "src/internal/default-retriable.ts"() {
147
+ }
148
+ });
149
+
132
150
  // src/internal/security/redact.ts
133
151
  function readEnvOnce() {
134
152
  const raw = process.env.THEOKIT_REDACT_SECRETS;
@@ -279,7 +297,8 @@ __export(errors_exports, {
279
297
  UnsupportedBudgetOperationError: () => UnsupportedBudgetOperationError,
280
298
  UnsupportedRunOperationError: () => UnsupportedRunOperationError,
281
299
  UnsupportedTaskOperationError: () => UnsupportedTaskOperationError,
282
- coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode
300
+ coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode,
301
+ isTransientError: () => isTransientError
283
302
  });
284
303
  function coerceToKnownAgentRunErrorCode(code) {
285
304
  if (code !== void 0 && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {
@@ -311,21 +330,13 @@ function safeStringify(value) {
311
330
  return String(value);
312
331
  }
313
332
  }
314
- function defaultRetriableForCode(code) {
315
- switch (code) {
316
- case "rate_limit":
317
- case "timeout":
318
- case "server_error":
319
- case "network":
320
- case "provider_unreachable":
321
- return true;
322
- default:
323
- return false;
324
- }
333
+ function isTransientError(err) {
334
+ return err instanceof TheokitAgentError && err.isRetryable === true;
325
335
  }
326
336
  var KNOWN_AGENT_RUN_ERROR_CODES, TheokitAgentError, AuthenticationError, RateLimitError, ConfigurationError, IntegrationNotConnectedError, NetworkError, UnknownAgentError, AgentRunError, UnsupportedRunOperationError, CredentialPoolExhaustedError, MemoryAdapterError, InvalidTaskIdError, TaskNotFoundError, UnsupportedTaskOperationError, BudgetExceededError, AgentDisposedError, UnsupportedBudgetOperationError;
327
337
  var init_errors = __esm({
328
338
  "src/errors.ts"() {
339
+ init_default_retriable();
329
340
  init_redact();
330
341
  KNOWN_AGENT_RUN_ERROR_CODES = /* @__PURE__ */ new Set([
331
342
  "rate_limit",
@@ -1024,6 +1035,19 @@ function sanitizeIdentifier(input, options) {
1024
1035
  }
1025
1036
  return input.toLowerCase();
1026
1037
  }
1038
+ function safeFilenameForId(id, options) {
1039
+ if (id.length === 0) {
1040
+ throw new ConfigurationError("Filename id must be a non-empty string", {
1041
+ code: "invalid_filename_id"
1042
+ });
1043
+ }
1044
+ const maxLen = options?.maxLen;
1045
+ const lower = id.toLowerCase();
1046
+ if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {
1047
+ return lower;
1048
+ }
1049
+ return `h-${createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
1050
+ }
1027
1051
  var PathTraversalError, IDENTIFIER_PATTERN;
1028
1052
  var init_path_guard = __esm({
1029
1053
  "src/internal/security/path-guard.ts"() {
@@ -1040,10 +1064,10 @@ var init_path_guard = __esm({
1040
1064
  }
1041
1065
  });
1042
1066
 
1043
- // src/internal/runtime/default-model.ts
1067
+ // src/internal/runtime/config/default-model.ts
1044
1068
  var DEFAULT_AGENTIC_MODEL_ID;
1045
1069
  var init_default_model = __esm({
1046
- "src/internal/runtime/default-model.ts"() {
1070
+ "src/internal/runtime/config/default-model.ts"() {
1047
1071
  DEFAULT_AGENTIC_MODEL_ID = "google/gemini-2.0-flash-001";
1048
1072
  }
1049
1073
  });
@@ -1439,7 +1463,7 @@ var init_agent_registry = __esm({
1439
1463
  }
1440
1464
  });
1441
1465
 
1442
- // src/internal/runtime/system-prompt.ts
1466
+ // src/internal/runtime/system-prompt/system-prompt.ts
1443
1467
  async function resolveSystemPrompt(agent, override, ctx) {
1444
1468
  if (override !== void 0) return override;
1445
1469
  if (agent === void 0) return void 0;
@@ -1457,7 +1481,7 @@ async function resolveSystemPromptForSend(agent, override, buildCtx) {
1457
1481
  return resolveSystemPrompt(agent, override, ctx);
1458
1482
  }
1459
1483
  var init_system_prompt = __esm({
1460
- "src/internal/runtime/system-prompt.ts"() {
1484
+ "src/internal/runtime/system-prompt/system-prompt.ts"() {
1461
1485
  }
1462
1486
  });
1463
1487
 
@@ -3111,7 +3135,7 @@ var init_paths = __esm({
3111
3135
  }
3112
3136
  });
3113
3137
 
3114
- // src/internal/runtime/yaml-frontmatter.ts
3138
+ // src/internal/runtime/context/yaml-frontmatter.ts
3115
3139
  function parseSimpleYaml(text) {
3116
3140
  const fields = {};
3117
3141
  for (const line of text.split(/\r?\n/)) {
@@ -3135,7 +3159,7 @@ function coerce(raw) {
3135
3159
  return raw;
3136
3160
  }
3137
3161
  var init_yaml_frontmatter = __esm({
3138
- "src/internal/runtime/yaml-frontmatter.ts"() {
3162
+ "src/internal/runtime/context/yaml-frontmatter.ts"() {
3139
3163
  }
3140
3164
  });
3141
3165
  async function loadMarkdownEntities(opts) {
@@ -4139,7 +4163,7 @@ function spawnAndCollect(options) {
4139
4163
  });
4140
4164
  }
4141
4165
  var init_spawn_collect = __esm({
4142
- "src/internal/runtime/spawn-collect.ts"() {
4166
+ "src/internal/runtime/lifecycle/spawn-collect.ts"() {
4143
4167
  }
4144
4168
  });
4145
4169
 
@@ -4236,41 +4260,11 @@ var init_hooks_executor = __esm({
4236
4260
  };
4237
4261
  }
4238
4262
  });
4239
-
4240
- // src/internal/runtime/memory/memory-path-selector.ts
4241
- function shouldUsePortMemoryPath() {
4242
- const env = globalThis.process?.env;
4243
- if (env === void 0) return false;
4244
- const val = env[PORT_MEMORY_PATH_ENV_VAR];
4245
- return val === "1" || val === "true";
4246
- }
4247
- function resolveMemoryProviderForLoop(consumerSupplied, defaultAdapter, portPathEnabled) {
4248
- if (consumerSupplied !== void 0) return consumerSupplied;
4249
- if (portPathEnabled) return defaultAdapter;
4250
- return void 0;
4251
- }
4252
- function resolveMemoryToolsForLoop(legacyTools, portPathEnabled) {
4253
- if (portPathEnabled) return void 0;
4254
- return legacyTools;
4255
- }
4256
- function resolveActiveMemorySummaryForSend(legacySummary, portPathEnabled) {
4257
- if (portPathEnabled) return void 0;
4258
- return legacySummary;
4259
- }
4260
- var PORT_MEMORY_PATH_ENV_VAR;
4261
- var init_memory_path_selector = __esm({
4262
- "src/internal/runtime/memory/memory-path-selector.ts"() {
4263
- PORT_MEMORY_PATH_ENV_VAR = "THEOKIT_PORT_MEMORY_PATH";
4264
- }
4265
- });
4266
4263
  function sessionsDir(cwd) {
4267
4264
  return join(memoryDir(cwd), "sessions");
4268
4265
  }
4269
4266
  function sessionSummaryPath(cwd, runId) {
4270
- return join(sessionsDir(cwd), `${sanitizeRunId(runId)}.md`);
4271
- }
4272
- function sanitizeRunId(runId) {
4273
- return runId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
4267
+ return join(sessionsDir(cwd), `${safeFilenameForId(runId, { maxLen: 128 })}.md`);
4274
4268
  }
4275
4269
  function truncate(text) {
4276
4270
  if (text.length <= MAX_TURN_CHARS) return text;
@@ -4306,11 +4300,39 @@ var MAX_TURN_CHARS;
4306
4300
  var init_session_summary_writer = __esm({
4307
4301
  "src/internal/memory/storage/session-summary-writer.ts"() {
4308
4302
  init_atomic_write();
4303
+ init_path_guard();
4309
4304
  init_types();
4310
4305
  init_markdown_store();
4311
4306
  MAX_TURN_CHARS = 2e3;
4312
4307
  }
4313
4308
  });
4309
+
4310
+ // src/internal/runtime/memory/memory-path-selector.ts
4311
+ function shouldUsePortMemoryPath() {
4312
+ const env = globalThis.process?.env;
4313
+ if (env === void 0) return false;
4314
+ const val = env[PORT_MEMORY_PATH_ENV_VAR];
4315
+ return val === "1" || val === "true";
4316
+ }
4317
+ function resolveMemoryProviderForLoop(consumerSupplied, defaultAdapter, portPathEnabled) {
4318
+ if (consumerSupplied !== void 0) return consumerSupplied;
4319
+ if (portPathEnabled) return defaultAdapter;
4320
+ return void 0;
4321
+ }
4322
+ function resolveMemoryToolsForLoop(legacyTools, portPathEnabled) {
4323
+ if (portPathEnabled) return void 0;
4324
+ return legacyTools;
4325
+ }
4326
+ function resolveActiveMemorySummaryForSend(legacySummary, portPathEnabled) {
4327
+ if (portPathEnabled) return void 0;
4328
+ return legacySummary;
4329
+ }
4330
+ var PORT_MEMORY_PATH_ENV_VAR;
4331
+ var init_memory_path_selector = __esm({
4332
+ "src/internal/runtime/memory/memory-path-selector.ts"() {
4333
+ PORT_MEMORY_PATH_ENV_VAR = "THEOKIT_PORT_MEMORY_PATH";
4334
+ }
4335
+ });
4314
4336
  function sessionFilePath(cwd, agentId) {
4315
4337
  const safe2 = sanitizeIdentifier(agentId, { maxLen: 128 });
4316
4338
  return safePathJoin(cwd, ".theokit", "agents", safe2, "messages.jsonl");
@@ -4584,7 +4606,7 @@ var init_agent_session = __esm({
4584
4606
  }
4585
4607
  });
4586
4608
 
4587
- // src/internal/runtime/post-run-lifecycle.ts
4609
+ // src/internal/runtime/lifecycle/post-run-lifecycle.ts
4588
4610
  async function runPostRunLifecycle(inputs) {
4589
4611
  const {
4590
4612
  run,
@@ -4645,7 +4667,7 @@ async function runPostRunLifecycle(inputs) {
4645
4667
  await flushSessionWrites();
4646
4668
  }
4647
4669
  var init_post_run_lifecycle = __esm({
4648
- "src/internal/runtime/post-run-lifecycle.ts"() {
4670
+ "src/internal/runtime/lifecycle/post-run-lifecycle.ts"() {
4649
4671
  init_session_summary_writer();
4650
4672
  init_memory_path_selector();
4651
4673
  init_agent_session();
@@ -4837,7 +4859,7 @@ async function readWorkspaceDir(root, errorCode, describe) {
4837
4859
  }
4838
4860
  }
4839
4861
  var init_workspace_dir = __esm({
4840
- "src/internal/runtime/workspace-dir.ts"() {
4862
+ "src/internal/runtime/config/workspace-dir.ts"() {
4841
4863
  init_errors();
4842
4864
  }
4843
4865
  });
@@ -5168,7 +5190,7 @@ var init_pipeline = __esm({
5168
5190
  }
5169
5191
  });
5170
5192
 
5171
- // src/internal/runtime/validate-agent-options.ts
5193
+ // src/internal/runtime/validation/validate-agent-options.ts
5172
5194
  function validateAgentOptions(options) {
5173
5195
  rejectProgrammaticHooks(options);
5174
5196
  ensureRuntimeShape(options);
@@ -5361,12 +5383,82 @@ function validateMemory(options) {
5361
5383
  }
5362
5384
  var TOOL_NAME_PATTERN, RESERVED_TOOL_NAMES;
5363
5385
  var init_validate_agent_options = __esm({
5364
- "src/internal/runtime/validate-agent-options.ts"() {
5386
+ "src/internal/runtime/validation/validate-agent-options.ts"() {
5365
5387
  init_errors();
5366
5388
  TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
5367
5389
  RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set(["shell", "memory_search", "memory_get"]);
5368
5390
  }
5369
5391
  });
5392
+
5393
+ // src/internal/runtime/config/providers-manager.ts
5394
+ function providerFromModel(model) {
5395
+ if (model === void 0) return void 0;
5396
+ const id = model.id;
5397
+ if (id.includes(":")) return id.split(":")[0];
5398
+ return void 0;
5399
+ }
5400
+ function resolveRoute(route, modelProvider, plugins) {
5401
+ if (route.capability === "chat" && modelProvider === route.provider) {
5402
+ const modelName = extractModelName(modelProvider, route);
5403
+ const base = {
5404
+ capability: route.capability,
5405
+ provider: route.provider,
5406
+ reason: "explicit-model-provider"
5407
+ };
5408
+ if (modelName !== void 0) base.model = modelName;
5409
+ return base;
5410
+ }
5411
+ if (plugins?.enabled !== void 0 && plugins.enabled.length > 0) {
5412
+ return {
5413
+ capability: route.capability,
5414
+ provider: route.provider,
5415
+ reason: "first-available-plugin-provider"
5416
+ };
5417
+ }
5418
+ return {
5419
+ capability: route.capability,
5420
+ provider: route.provider,
5421
+ reason: "explicit-route"
5422
+ };
5423
+ }
5424
+ function extractModelName(prefix, route) {
5425
+ if (route.model !== void 0) return route.model;
5426
+ return prefix === route.provider ? defaultModelForProvider(prefix) : void 0;
5427
+ }
5428
+ function defaultModelForProvider(provider) {
5429
+ if (provider === "anthropic") return "claude-3-7-sonnet";
5430
+ return void 0;
5431
+ }
5432
+ var ProvidersManagerImpl;
5433
+ var init_providers_manager = __esm({
5434
+ "src/internal/runtime/config/providers-manager.ts"() {
5435
+ ProvidersManagerImpl = class {
5436
+ constructor(model, providers, plugins) {
5437
+ this.model = model;
5438
+ this.providers = providers;
5439
+ this.plugins = plugins;
5440
+ }
5441
+ model;
5442
+ providers;
5443
+ plugins;
5444
+ routes() {
5445
+ const resolved = [];
5446
+ const modelProvider = providerFromModel(this.model);
5447
+ const seen = /* @__PURE__ */ new Set();
5448
+ if (this.providers?.routes !== void 0) {
5449
+ for (const route of this.providers.routes) {
5450
+ const resolvedRoute = resolveRoute(route, modelProvider, this.plugins);
5451
+ if (!seen.has(route.capability)) {
5452
+ seen.add(route.capability);
5453
+ resolved.push(resolvedRoute);
5454
+ }
5455
+ }
5456
+ }
5457
+ return Promise.resolve(resolved);
5458
+ }
5459
+ };
5460
+ }
5461
+ });
5370
5462
  function truncateWithMarker(content, max) {
5371
5463
  if (content.length <= max) {
5372
5464
  return { truncated: false, finalContent: content };
@@ -6132,8 +6224,8 @@ var init_plugins_manager = __esm({
6132
6224
  init_errors();
6133
6225
  init_markdown_config_loader();
6134
6226
  init_path_guard();
6135
- init_hooks_source();
6136
6227
  init_workspace_dir();
6228
+ init_hooks_source();
6137
6229
  init_plugin_frontmatter();
6138
6230
  PluginsManager = class {
6139
6231
  constructor(cwd, enabled, settingSourcesIncludePlugins, cloud, localPaths) {
@@ -6216,76 +6308,6 @@ var init_plugins_manager = __esm({
6216
6308
  }
6217
6309
  });
6218
6310
 
6219
- // src/internal/runtime/providers-manager.ts
6220
- function providerFromModel(model) {
6221
- if (model === void 0) return void 0;
6222
- const id = model.id;
6223
- if (id.includes(":")) return id.split(":")[0];
6224
- return void 0;
6225
- }
6226
- function resolveRoute(route, modelProvider, plugins) {
6227
- if (route.capability === "chat" && modelProvider === route.provider) {
6228
- const modelName = extractModelName(modelProvider, route);
6229
- const base = {
6230
- capability: route.capability,
6231
- provider: route.provider,
6232
- reason: "explicit-model-provider"
6233
- };
6234
- if (modelName !== void 0) base.model = modelName;
6235
- return base;
6236
- }
6237
- if (plugins?.enabled !== void 0 && plugins.enabled.length > 0) {
6238
- return {
6239
- capability: route.capability,
6240
- provider: route.provider,
6241
- reason: "first-available-plugin-provider"
6242
- };
6243
- }
6244
- return {
6245
- capability: route.capability,
6246
- provider: route.provider,
6247
- reason: "explicit-route"
6248
- };
6249
- }
6250
- function extractModelName(prefix, route) {
6251
- if (route.model !== void 0) return route.model;
6252
- return prefix === route.provider ? defaultModelForProvider(prefix) : void 0;
6253
- }
6254
- function defaultModelForProvider(provider) {
6255
- if (provider === "anthropic") return "claude-3-7-sonnet";
6256
- return void 0;
6257
- }
6258
- var ProvidersManagerImpl;
6259
- var init_providers_manager = __esm({
6260
- "src/internal/runtime/providers-manager.ts"() {
6261
- ProvidersManagerImpl = class {
6262
- constructor(model, providers, plugins) {
6263
- this.model = model;
6264
- this.providers = providers;
6265
- this.plugins = plugins;
6266
- }
6267
- model;
6268
- providers;
6269
- plugins;
6270
- routes() {
6271
- const resolved = [];
6272
- const modelProvider = providerFromModel(this.model);
6273
- const seen = /* @__PURE__ */ new Set();
6274
- if (this.providers?.routes !== void 0) {
6275
- for (const route of this.providers.routes) {
6276
- const resolvedRoute = resolveRoute(route, modelProvider, this.plugins);
6277
- if (!seen.has(route.capability)) {
6278
- seen.add(route.capability);
6279
- resolved.push(resolvedRoute);
6280
- }
6281
- }
6282
- }
6283
- return Promise.resolve(resolved);
6284
- }
6285
- };
6286
- }
6287
- });
6288
-
6289
6311
  // src/internal/runtime/skills/skill-frontmatter.ts
6290
6312
  function asString(v) {
6291
6313
  return typeof v === "string" ? v : void 0;
@@ -6492,9 +6514,9 @@ function bootstrapSubmanagers(args) {
6492
6514
  }
6493
6515
  var init_local_agent_bootstrap = __esm({
6494
6516
  "src/internal/runtime/local-agent/local-agent-bootstrap.ts"() {
6517
+ init_providers_manager();
6495
6518
  init_context_manager();
6496
6519
  init_plugins_manager();
6497
- init_providers_manager();
6498
6520
  init_agent_registry();
6499
6521
  init_skills_manager();
6500
6522
  }
@@ -6668,7 +6690,7 @@ var init_budget = __esm({
6668
6690
  }
6669
6691
  });
6670
6692
 
6671
- // src/internal/runtime/validate-response.ts
6693
+ // src/internal/runtime/validation/validate-response.ts
6672
6694
  function validateResponse(response) {
6673
6695
  const trimmed = response.content.trim();
6674
6696
  const toolCallsArr = Array.isArray(response.toolCalls) ? response.toolCalls : [];
@@ -6681,7 +6703,7 @@ function validateResponse(response) {
6681
6703
  return { ok: true };
6682
6704
  }
6683
6705
  var init_validate_response = __esm({
6684
- "src/internal/runtime/validate-response.ts"() {
6706
+ "src/internal/runtime/validation/validate-response.ts"() {
6685
6707
  }
6686
6708
  });
6687
6709
 
@@ -7104,11 +7126,80 @@ function checkToolWhitelist(toolName) {
7104
7126
  }
7105
7127
  var toolWhitelistStore;
7106
7128
  var init_async_local_storage = __esm({
7107
- "src/internal/runtime/async-local-storage.ts"() {
7129
+ "src/internal/runtime/concurrency/async-local-storage.ts"() {
7108
7130
  toolWhitelistStore = new AsyncLocalStorage();
7109
7131
  }
7110
7132
  });
7111
7133
 
7134
+ // src/internal/runtime/concurrency/async-semaphore.ts
7135
+ function createSemaphore(permits) {
7136
+ if (!Number.isInteger(permits) || permits < 1) {
7137
+ throw new ConfigurationError(
7138
+ `async-semaphore: permits must be a positive integer, got ${permits}`,
7139
+ { code: "invalid_concurrency" }
7140
+ );
7141
+ }
7142
+ let active = 0;
7143
+ const queue = [];
7144
+ function tryGrant() {
7145
+ if (active < permits && queue.length > 0) {
7146
+ const resolve3 = queue.shift();
7147
+ if (resolve3 !== void 0) {
7148
+ active += 1;
7149
+ resolve3();
7150
+ }
7151
+ }
7152
+ }
7153
+ return {
7154
+ inFlight: () => active,
7155
+ pending: () => queue.length + active,
7156
+ async acquire() {
7157
+ await new Promise((resolve3) => {
7158
+ queue.push(resolve3);
7159
+ tryGrant();
7160
+ });
7161
+ let released = false;
7162
+ return () => {
7163
+ if (released) return;
7164
+ released = true;
7165
+ active -= 1;
7166
+ tryGrant();
7167
+ };
7168
+ }
7169
+ };
7170
+ }
7171
+ var init_async_semaphore = __esm({
7172
+ "src/internal/runtime/concurrency/async-semaphore.ts"() {
7173
+ init_errors();
7174
+ }
7175
+ });
7176
+
7177
+ // src/internal/runtime/concurrency/map-with-concurrency.ts
7178
+ async function mapWithConcurrency(items, concurrency, fn, options) {
7179
+ const semaphore = createSemaphore(concurrency);
7180
+ const signal = NEVER_ABORT;
7181
+ return Promise.all(
7182
+ items.map(async (item, index) => {
7183
+ const release = await semaphore.acquire();
7184
+ try {
7185
+ if (signal.aborted) {
7186
+ throw signal.reason instanceof Error ? signal.reason : new Error("mapWithConcurrency: aborted");
7187
+ }
7188
+ return await fn(item, index, signal);
7189
+ } finally {
7190
+ release();
7191
+ }
7192
+ })
7193
+ );
7194
+ }
7195
+ var NEVER_ABORT;
7196
+ var init_map_with_concurrency = __esm({
7197
+ "src/internal/runtime/concurrency/map-with-concurrency.ts"() {
7198
+ init_async_semaphore();
7199
+ NEVER_ABORT = new AbortController().signal;
7200
+ }
7201
+ });
7202
+
7112
7203
  // src/internal/tool-dispatch/repair-middleware.ts
7113
7204
  function repairToolCall(raw, registry) {
7114
7205
  const repairs = [];
@@ -7187,7 +7278,7 @@ var init_repair_middleware = __esm({
7187
7278
  }
7188
7279
  });
7189
7280
 
7190
- // src/internal/runtime/shell-tool.ts
7281
+ // src/internal/runtime/tools/shell-tool.ts
7191
7282
  async function runShell(options) {
7192
7283
  if (options.sandbox === true && isObviouslyUnsafe(options.command)) {
7193
7284
  return {
@@ -7218,7 +7309,7 @@ function isObviouslyUnsafe(command) {
7218
7309
  return false;
7219
7310
  }
7220
7311
  var init_shell_tool = __esm({
7221
- "src/internal/runtime/shell-tool.ts"() {
7312
+ "src/internal/runtime/tools/shell-tool.ts"() {
7222
7313
  init_spawn_collect();
7223
7314
  }
7224
7315
  });
@@ -7298,38 +7389,12 @@ var init_tool_executors = __esm({
7298
7389
  // src/internal/agent-loop/tool-dispatch.ts
7299
7390
  async function dispatchTools(inputs, tools, toolCalls, events) {
7300
7391
  const maxConcurrent = inputs.maxConcurrentTools ?? 4;
7301
- return boundedParallel(
7302
- maxConcurrent,
7392
+ return mapWithConcurrency(
7303
7393
  toolCalls,
7394
+ maxConcurrent,
7304
7395
  (call) => dispatchSingleCall(inputs, tools, call, events)
7305
7396
  );
7306
7397
  }
7307
- async function boundedParallel(max, items, fn) {
7308
- let running = 0;
7309
- const queue = [];
7310
- async function acquire() {
7311
- if (running < max) {
7312
- running++;
7313
- return;
7314
- }
7315
- await new Promise((resolve3) => queue.push(resolve3));
7316
- running++;
7317
- }
7318
- function release() {
7319
- running--;
7320
- if (queue.length > 0) queue.shift()();
7321
- }
7322
- return Promise.all(
7323
- items.map(async (item) => {
7324
- await acquire();
7325
- try {
7326
- return await fn(item);
7327
- } finally {
7328
- release();
7329
- }
7330
- })
7331
- );
7332
- }
7333
7398
  async function dispatchSingleCall(inputs, tools, call, events) {
7334
7399
  const { call: workingCall, repairs } = applyRepairAndExtractCall(tools, call);
7335
7400
  const callId = generateCallId();
@@ -7553,6 +7618,7 @@ var init_tool_dispatch = __esm({
7553
7618
  "src/internal/agent-loop/tool-dispatch.ts"() {
7554
7619
  init_ids();
7555
7620
  init_async_local_storage();
7621
+ init_map_with_concurrency();
7556
7622
  init_repair_middleware();
7557
7623
  init_tool_executors();
7558
7624
  }
@@ -8535,7 +8601,7 @@ var init_providers = __esm({
8535
8601
  }
8536
8602
  });
8537
8603
 
8538
- // src/internal/errors/mappers/shared.ts
8604
+ // src/internal/error-mappers/shared.ts
8539
8605
  function parseRetryAfter(headers) {
8540
8606
  if (headers === void 0) return void 0;
8541
8607
  const raw = headers.get("retry-after");
@@ -8564,13 +8630,13 @@ function buildErrorMetadata(args) {
8564
8630
  }
8565
8631
  var RAW_MAX_BYTES;
8566
8632
  var init_shared = __esm({
8567
- "src/internal/errors/mappers/shared.ts"() {
8633
+ "src/internal/error-mappers/shared.ts"() {
8568
8634
  init_security();
8569
8635
  RAW_MAX_BYTES = 2048;
8570
8636
  }
8571
8637
  });
8572
8638
 
8573
- // src/internal/errors/mappers/anthropic.ts
8639
+ // src/internal/error-mappers/anthropic.ts
8574
8640
  function mapAnthropicError(args) {
8575
8641
  const { status, body, headers, endpoint } = args;
8576
8642
  const code = mapAnthropicStatusToCode(status, body);
@@ -8624,7 +8690,7 @@ function formatMessage(status, code) {
8624
8690
  return `Anthropic API error: ${code} (HTTP ${status})`;
8625
8691
  }
8626
8692
  var init_anthropic2 = __esm({
8627
- "src/internal/errors/mappers/anthropic.ts"() {
8693
+ "src/internal/error-mappers/anthropic.ts"() {
8628
8694
  init_errors();
8629
8695
  init_shared();
8630
8696
  }
@@ -8931,7 +8997,7 @@ var init_anthropic3 = __esm({
8931
8997
  }
8932
8998
  });
8933
8999
 
8934
- // src/internal/errors/mappers/bedrock.ts
9000
+ // src/internal/error-mappers/bedrock.ts
8935
9001
  function classifyBedrockError(args, awsType, message) {
8936
9002
  if (args.status === 429 || awsType.includes("Throttling") || awsType.includes("TooManyRequests")) {
8937
9003
  return "rate_limit";
@@ -8991,7 +9057,7 @@ function parseBody(body) {
8991
9057
  return {};
8992
9058
  }
8993
9059
  var init_bedrock2 = __esm({
8994
- "src/internal/errors/mappers/bedrock.ts"() {
9060
+ "src/internal/error-mappers/bedrock.ts"() {
8995
9061
  init_errors();
8996
9062
  init_shared();
8997
9063
  }
@@ -9378,7 +9444,7 @@ var init_credential_pool_context = __esm({
9378
9444
  }
9379
9445
  });
9380
9446
 
9381
- // src/internal/errors/mappers/openai-compatible.ts
9447
+ // src/internal/error-mappers/openai-compatible.ts
9382
9448
  function mapOpenAICompatibleError(args) {
9383
9449
  const { providerId, status, body, headers, endpoint } = args;
9384
9450
  const code = mapOpenAiStatusToCode(status, body);
@@ -9441,7 +9507,7 @@ function formatMessage2(providerId, status, code) {
9441
9507
  return `${providerId} API error: ${code} (HTTP ${status})`;
9442
9508
  }
9443
9509
  var init_openai_compatible = __esm({
9444
- "src/internal/errors/mappers/openai-compatible.ts"() {
9510
+ "src/internal/error-mappers/openai-compatible.ts"() {
9445
9511
  init_errors();
9446
9512
  init_shared();
9447
9513
  }
@@ -9553,7 +9619,7 @@ var init_fault_injection = __esm({
9553
9619
  }
9554
9620
  });
9555
9621
 
9556
- // src/internal/errors/mappers/ollama.ts
9622
+ // src/internal/error-mappers/ollama.ts
9557
9623
  function mapOllamaTransportError(args) {
9558
9624
  if (args.providerId !== "ollama") return void 0;
9559
9625
  const causeCode = extractCauseCode(args.cause);
@@ -9626,7 +9692,7 @@ function extractModelName2(errString) {
9626
9692
  return match?.[1];
9627
9693
  }
9628
9694
  var init_ollama2 = __esm({
9629
- "src/internal/errors/mappers/ollama.ts"() {
9695
+ "src/internal/error-mappers/ollama.ts"() {
9630
9696
  init_errors();
9631
9697
  init_shared();
9632
9698
  }
@@ -10227,7 +10293,7 @@ var init_pool_aware_client = __esm({
10227
10293
  }
10228
10294
  });
10229
10295
 
10230
- // src/internal/errors/mappers/vertex.ts
10296
+ // src/internal/error-mappers/vertex.ts
10231
10297
  function classifyVertexError(args, errStatus) {
10232
10298
  for (const rule of VERTEX_RULES) {
10233
10299
  if (rule.test(args.status, errStatus)) return rule.code;
@@ -10264,7 +10330,7 @@ function parseBody2(body) {
10264
10330
  }
10265
10331
  var VERTEX_RULES, VERTEX_ERROR_BUILDERS;
10266
10332
  var init_vertex2 = __esm({
10267
- "src/internal/errors/mappers/vertex.ts"() {
10333
+ "src/internal/error-mappers/vertex.ts"() {
10268
10334
  init_errors();
10269
10335
  init_shared();
10270
10336
  VERTEX_RULES = [
@@ -10824,6 +10890,21 @@ var init_client = __esm({
10824
10890
  }
10825
10891
  });
10826
10892
 
10893
+ // src/internal/providers/register-plugin-providers.ts
10894
+ function registerPluginProviderProfiles(entries) {
10895
+ let registered4 = 0;
10896
+ for (const entry of entries) {
10897
+ registerProvider(entry.profile);
10898
+ registered4 += 1;
10899
+ }
10900
+ return registered4;
10901
+ }
10902
+ var init_register_plugin_providers = __esm({
10903
+ "src/internal/providers/register-plugin-providers.ts"() {
10904
+ init_registry();
10905
+ }
10906
+ });
10907
+
10827
10908
  // src/internal/tool-registry/personality-filter.ts
10828
10909
  function applyPersonalityFilter(exposedTools, whitelist, opts) {
10829
10910
  if (whitelist === void 0) return exposedTools;
@@ -10904,12 +10985,26 @@ function createRealLocalRun(options) {
10904
10985
  registerRun(handle);
10905
10986
  return handle;
10906
10987
  }
10907
- function buildLoopInputs(options, runId, userText) {
10988
+ function resolveRunProvider(options) {
10908
10989
  registerBuiltins();
10990
+ const profiles = options.pluginManager?.aggregated.providerProfiles ?? [];
10991
+ const registered4 = registerPluginProviderProfiles(profiles);
10992
+ if (registered4 > 0 && !pluginProvidersAnnounced) {
10993
+ pluginProvidersAnnounced = true;
10994
+ const names = profiles.map((e) => e.profile.name).join(", ");
10995
+ process.stderr.write(
10996
+ `[theokit-sdk] registered ${registered4} plugin provider profile(s): ${names}
10997
+ `
10998
+ );
10999
+ }
10909
11000
  const parsedModel = parseModelId(options.model?.id);
10910
11001
  const inferredProvider = parsedModel.provider !== void 0 && getProviderProfile(parsedModel.provider) !== void 0 ? parsedModel.provider : void 0;
10911
11002
  const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? inferredProvider ?? detectPrimaryProvider();
10912
11003
  const effectiveModelId = inferredProvider !== void 0 ? parsedModel.name : options.model?.id ?? "claude-sonnet-4-6";
11004
+ return { primary, effectiveModelId };
11005
+ }
11006
+ function buildLoopInputs(options, runId, userText) {
11007
+ const { primary, effectiveModelId } = resolveRunProvider(options);
10913
11008
  const fallback = options.agentOptions.providers?.fallback;
10914
11009
  const apiKeys = options.agentOptions.providers?.apiKeys;
10915
11010
  const credentialPoolStrategy = options.agentOptions.providers?.credentialPoolStrategy;
@@ -11003,7 +11098,7 @@ function buildMcpMap(options) {
11003
11098
  }
11004
11099
  return map;
11005
11100
  }
11006
- var RealLocalRun;
11101
+ var pluginProvidersAnnounced, RealLocalRun;
11007
11102
  var init_real_local_run = __esm({
11008
11103
  "src/internal/runtime/local-agent/real-local-run.ts"() {
11009
11104
  init_loop();
@@ -11012,10 +11107,12 @@ var init_real_local_run = __esm({
11012
11107
  init_router();
11013
11108
  init_client();
11014
11109
  init_providers();
11110
+ init_register_plugin_providers();
11015
11111
  init_tracer();
11016
11112
  init_personality_filter();
11017
11113
  init_fixture_run_base();
11018
11114
  init_run_registry();
11115
+ pluginProvidersAnnounced = false;
11019
11116
  RealLocalRun = class extends FixtureRunBase {
11020
11117
  buildInputs;
11021
11118
  constructor(options, buildInputs) {
@@ -11567,7 +11664,7 @@ async function embedTexts(input) {
11567
11664
  pending
11568
11665
  });
11569
11666
  }
11570
- await runBatches(input, pending, results);
11667
+ await embedInBoundedBatches(input, pending, results);
11571
11668
  return results.map((v) => v ?? new Array(dimension).fill(0));
11572
11669
  }
11573
11670
  function classifyEntry(args) {
@@ -11585,45 +11682,34 @@ function classifyEntry(args) {
11585
11682
  args.stats.cacheMisses += 1;
11586
11683
  args.pending.push({ index: args.index, text: args.text, key });
11587
11684
  }
11588
- async function runBatches(input, pending, results) {
11685
+ async function embedInBoundedBatches(input, pending, results) {
11589
11686
  const batches = [];
11590
11687
  for (let offset = 0; offset < pending.length; offset += MAX_BATCH) {
11591
11688
  batches.push(pending.slice(offset, offset + MAX_BATCH));
11592
11689
  }
11593
- let running = 0;
11594
- const queue = [];
11595
- await Promise.all(batches.map((batch) => processBatch(input, batch, results, acquire, release)));
11596
- async function acquire() {
11597
- if (running >= MAX_CONCURRENT_BATCHES) await new Promise((r) => queue.push(r));
11598
- running++;
11599
- }
11600
- function release() {
11601
- running--;
11602
- if (queue.length > 0) queue.shift()();
11603
- }
11690
+ await mapWithConcurrency(
11691
+ batches,
11692
+ MAX_CONCURRENT_BATCHES,
11693
+ (batch) => processBatch(input, batch, results)
11694
+ );
11604
11695
  }
11605
- async function processBatch(input, batch, results, acquire, release) {
11606
- await acquire();
11607
- try {
11608
- const vectors = await embedBatch({
11609
- apiKey: input.apiKey,
11610
- baseUrl: input.baseUrl,
11611
- embeddingsPath: input.embeddingsPath,
11612
- model: input.model,
11613
- inputs: batch.map((b) => b.text),
11614
- fetchImpl: input.fetchImpl,
11615
- stats: input.stats,
11616
- providerId: input.providerId
11617
- });
11618
- for (let j = 0; j < batch.length; j++) {
11619
- const slot = batch[j];
11620
- const vector = vectors[j];
11621
- if (slot === void 0 || vector === void 0) continue;
11622
- results[slot.index] = vector;
11623
- input.cache.set(slot.key, vector);
11624
- }
11625
- } finally {
11626
- release();
11696
+ async function processBatch(input, batch, results) {
11697
+ const vectors = await embedBatch({
11698
+ apiKey: input.apiKey,
11699
+ baseUrl: input.baseUrl,
11700
+ embeddingsPath: input.embeddingsPath,
11701
+ model: input.model,
11702
+ inputs: batch.map((b) => b.text),
11703
+ fetchImpl: input.fetchImpl,
11704
+ stats: input.stats,
11705
+ providerId: input.providerId
11706
+ });
11707
+ for (let j = 0; j < batch.length; j++) {
11708
+ const slot = batch[j];
11709
+ const vector = vectors[j];
11710
+ if (slot === void 0 || vector === void 0) continue;
11711
+ results[slot.index] = vector;
11712
+ input.cache.set(slot.key, vector);
11627
11713
  }
11628
11714
  }
11629
11715
  async function embedBatch(opts) {
@@ -11697,6 +11783,7 @@ var init_openai_compatible2 = __esm({
11697
11783
  "src/internal/memory/adapters/openai-compatible.ts"() {
11698
11784
  init_errors();
11699
11785
  init_openai_compatible();
11786
+ init_map_with_concurrency();
11700
11787
  init_embedding_cache();
11701
11788
  MAX_BATCH = 100;
11702
11789
  MAX_RETRIES = 2;
@@ -12181,6 +12268,61 @@ var init_sqlite_wal = __esm({
12181
12268
  warnedLabels = /* @__PURE__ */ new Set();
12182
12269
  }
12183
12270
  });
12271
+ async function openSqliteResilient(options) {
12272
+ await mkdir(dirname(options.filePath), { recursive: true });
12273
+ try {
12274
+ return await openConcrete(options);
12275
+ } catch (cause) {
12276
+ if (options.recoverCorrupt !== false && isCorruptionError(cause)) {
12277
+ await renameAside(options.filePath, options.label ?? "sqlite");
12278
+ return await openConcrete(options);
12279
+ }
12280
+ throw cause;
12281
+ }
12282
+ }
12283
+ async function openConcrete(options) {
12284
+ const db = await loadDriver(options.filePath);
12285
+ applyWalWithFallback(db, options.label ?? "sqlite");
12286
+ await options.onOpen?.(db);
12287
+ return db;
12288
+ }
12289
+ async function loadDriver(filePath) {
12290
+ try {
12291
+ const mod = await import('better-sqlite3');
12292
+ const Ctor = mod.default ?? mod;
12293
+ if (typeof Ctor !== "function") {
12294
+ throw new Error(`better-sqlite3 export is not a constructor (got ${typeof Ctor})`);
12295
+ }
12296
+ return new Ctor(filePath);
12297
+ } catch (cause) {
12298
+ const message = cause instanceof Error ? cause.message : String(cause);
12299
+ throw new ConfigurationError(
12300
+ `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
12301
+ { code: "sqlite_driver_unavailable", cause }
12302
+ );
12303
+ }
12304
+ }
12305
+ function isCorruptionError(cause) {
12306
+ if (!(cause instanceof Error)) return false;
12307
+ const msg = cause.message.toLowerCase();
12308
+ return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
12309
+ }
12310
+ async function renameAside(filePath, label) {
12311
+ const asidePath = `${filePath}.corrupt-${Date.now()}`;
12312
+ await rename(filePath, asidePath).catch(() => void 0);
12313
+ await rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
12314
+ await rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
12315
+ process.stderr.write(
12316
+ `[theokit-sdk] ${label} database corrupt; renamed aside to ${asidePath} and rebuilt schema
12317
+ `
12318
+ );
12319
+ }
12320
+ var init_sqlite_open = __esm({
12321
+ "src/internal/persistence/sqlite-open.ts"() {
12322
+ init_errors();
12323
+ init_sqlite_wal();
12324
+ }
12325
+ });
12184
12326
 
12185
12327
  // src/internal/memory/index-schema.ts
12186
12328
  var SCHEMA_STATEMENTS, PRAGMA_STATEMENTS;
@@ -12228,60 +12370,22 @@ var init_index_schema = __esm({
12228
12370
  }
12229
12371
  });
12230
12372
  async function openMemoryDb(opts) {
12231
- await mkdir(dirname(opts.filePath), { recursive: true });
12232
- try {
12233
- return await openConcrete(opts.filePath);
12234
- } catch (cause) {
12235
- if (opts.recoverCorrupt !== false && isCorruptionError(cause)) {
12236
- await renameAside(opts.filePath);
12237
- return await openConcrete(opts.filePath);
12373
+ return openSqliteResilient({
12374
+ filePath: opts.filePath,
12375
+ label: "memory-index",
12376
+ recoverCorrupt: opts.recoverCorrupt,
12377
+ onOpen: (db) => {
12378
+ for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
12379
+ for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
12238
12380
  }
12239
- throw cause;
12240
- }
12241
- }
12242
- async function openConcrete(filePath) {
12243
- const db = await loadDriver(filePath);
12244
- applyWalWithFallback(db, "memory-index");
12245
- for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
12246
- for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
12247
- return db;
12248
- }
12249
- async function loadDriver(filePath) {
12250
- try {
12251
- const mod = await import('better-sqlite3');
12252
- const Ctor = mod.default ?? mod;
12253
- const db = new Ctor(filePath);
12254
- return db;
12255
- } catch (cause) {
12256
- const message = cause instanceof Error ? cause.message : String(cause);
12257
- throw new ConfigurationError(
12258
- `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
12259
- { code: "sqlite_driver_unavailable", cause }
12260
- );
12261
- }
12262
- }
12263
- function isCorruptionError(cause) {
12264
- if (!(cause instanceof Error)) return false;
12265
- const msg = cause.message.toLowerCase();
12266
- return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
12267
- }
12268
- async function renameAside(filePath) {
12269
- const asidePath = `${filePath}.corrupt-${Date.now()}`;
12270
- await rename(filePath, asidePath).catch(() => void 0);
12271
- await rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
12272
- await rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
12273
- process.stderr.write(
12274
- `[theokit-sdk] memory index corrupt; renamed aside to ${asidePath} and rebuilt schema
12275
- `
12276
- );
12381
+ });
12277
12382
  }
12278
12383
  function defaultIndexPath(cwd) {
12279
12384
  return join(cwd, ".theokit", "memory", ".index", "memory.sqlite");
12280
12385
  }
12281
12386
  var init_index_db = __esm({
12282
12387
  "src/internal/memory/index-db.ts"() {
12283
- init_errors();
12284
- init_sqlite_wal();
12388
+ init_sqlite_open();
12285
12389
  init_index_schema();
12286
12390
  }
12287
12391
  });
@@ -13833,7 +13937,7 @@ var init_local_agent_plugins = __esm({
13833
13937
  }
13834
13938
  });
13835
13939
 
13836
- // src/internal/runtime/run-until.ts
13940
+ // src/internal/runtime/lifecycle/run-until.ts
13837
13941
  var run_until_exports = {};
13838
13942
  __export(run_until_exports, {
13839
13943
  composeContinuation: () => composeContinuation,
@@ -13926,7 +14030,7 @@ Your last response was:
13926
14030
  ${lastResponse.slice(0, 1e3)}`;
13927
14031
  }
13928
14032
  var init_run_until = __esm({
13929
- "src/internal/runtime/run-until.ts"() {
14033
+ "src/internal/runtime/lifecycle/run-until.ts"() {
13930
14034
  }
13931
14035
  });
13932
14036
 
@@ -14037,16 +14141,16 @@ var init_judge_call = __esm({
14037
14141
  // src/internal/runtime/registry/agent-factory-registry.ts
14038
14142
  var agent_factory_registry_exports = {};
14039
14143
  __export(agent_factory_registry_exports, {
14040
- getAgentCreate: () => getAgentCreate,
14041
- setAgentCreate: () => setAgentCreate
14144
+ getAgentFacade: () => getAgentFacade,
14145
+ setAgentFacade: () => setAgentFacade
14042
14146
  });
14043
- function setAgentCreate(fn) {
14044
- registered3 = fn;
14147
+ function setAgentFacade(facade) {
14148
+ registered3 = facade;
14045
14149
  }
14046
- function getAgentCreate() {
14150
+ function getAgentFacade() {
14047
14151
  if (registered3 === void 0) {
14048
14152
  throw new Error(
14049
- "internal: Agent.create not registered. The `agent.ts` module must be loaded before LocalAgent.runUntil/fork are invoked."
14153
+ "internal: Agent facade not registered. The `agent.ts` module must be loaded before internal subsystems (LocalAgent.runUntil/fork, eval, scorers, cron) invoke it."
14050
14154
  );
14051
14155
  }
14052
14156
  return registered3;
@@ -14057,7 +14161,7 @@ var init_agent_factory_registry = __esm({
14057
14161
  }
14058
14162
  });
14059
14163
 
14060
- // src/internal/runtime/fork-agent.ts
14164
+ // src/internal/runtime/lifecycle/fork-agent.ts
14061
14165
  var fork_agent_exports = {};
14062
14166
  __export(fork_agent_exports, {
14063
14167
  filterMemoryPlugins: () => filterMemoryPlugins,
@@ -14117,7 +14221,7 @@ function extractUsage(result) {
14117
14221
  };
14118
14222
  }
14119
14223
  var init_fork_agent = __esm({
14120
- "src/internal/runtime/fork-agent.ts"() {
14224
+ "src/internal/runtime/lifecycle/fork-agent.ts"() {
14121
14225
  init_async_local_storage();
14122
14226
  init_local_agent_plugins();
14123
14227
  }
@@ -14128,8 +14232,8 @@ function localAgentRunUntil(agent, goal, options) {
14128
14232
  async function* wrap() {
14129
14233
  const { runUntilImpl: runUntilImpl2 } = await Promise.resolve().then(() => (init_run_until(), run_until_exports));
14130
14234
  const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
14131
- const { getAgentCreate: getAgentCreate2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14132
- const create = getAgentCreate2();
14235
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14236
+ const create = getAgentFacade2().create;
14133
14237
  const deps = {
14134
14238
  judge: async (ctx, opts) => judgeCallImpl2(ctx, opts, { create })
14135
14239
  };
@@ -14139,9 +14243,9 @@ function localAgentRunUntil(agent, goal, options) {
14139
14243
  }
14140
14244
  async function localAgentFork(parent, options) {
14141
14245
  const { forkAgentImpl: forkAgentImpl2 } = await Promise.resolve().then(() => (init_fork_agent(), fork_agent_exports));
14142
- const { getAgentCreate: getAgentCreate2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14246
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14143
14247
  const { withPersonalityContext: withPersonalityContext2 } = await Promise.resolve().then(() => (init_context2(), context_exports));
14144
- const create = getAgentCreate2();
14248
+ const create = getAgentFacade2().create;
14145
14249
  return withPersonalityContext2(
14146
14250
  { slug: parent.personalitySlugSnapshot, isFork: true },
14147
14251
  () => forkAgentImpl2(parent, options, { create })
@@ -14165,7 +14269,7 @@ var init_local_agent_runtime_extensions = __esm({
14165
14269
  }
14166
14270
  });
14167
14271
 
14168
- // src/internal/runtime/abort-utils.ts
14272
+ // src/internal/runtime/concurrency/abort-utils.ts
14169
14273
  function anySignal(signals) {
14170
14274
  const filtered = signals.filter((s) => s !== void 0);
14171
14275
  if (filtered.length === 0) {
@@ -14191,7 +14295,7 @@ function ponyfillAny(signals) {
14191
14295
  return ctrl.signal;
14192
14296
  }
14193
14297
  var init_abort_utils = __esm({
14194
- "src/internal/runtime/abort-utils.ts"() {
14298
+ "src/internal/runtime/concurrency/abort-utils.ts"() {
14195
14299
  }
14196
14300
  });
14197
14301
 
@@ -14344,49 +14448,6 @@ var init_task = __esm({
14344
14448
  }
14345
14449
  });
14346
14450
 
14347
- // src/internal/runtime/async-semaphore.ts
14348
- function createSemaphore(permits) {
14349
- if (!Number.isInteger(permits) || permits < 1) {
14350
- throw new ConfigurationError(
14351
- `async-semaphore: permits must be a positive integer, got ${permits}`,
14352
- { code: "invalid_concurrency" }
14353
- );
14354
- }
14355
- let active = 0;
14356
- const queue = [];
14357
- function tryGrant() {
14358
- if (active < permits && queue.length > 0) {
14359
- const resolve3 = queue.shift();
14360
- if (resolve3 !== void 0) {
14361
- active += 1;
14362
- resolve3();
14363
- }
14364
- }
14365
- }
14366
- return {
14367
- inFlight: () => active,
14368
- pending: () => queue.length + active,
14369
- async acquire() {
14370
- await new Promise((resolve3) => {
14371
- queue.push(resolve3);
14372
- tryGrant();
14373
- });
14374
- let released = false;
14375
- return () => {
14376
- if (released) return;
14377
- released = true;
14378
- active -= 1;
14379
- tryGrant();
14380
- };
14381
- }
14382
- };
14383
- }
14384
- var init_async_semaphore = __esm({
14385
- "src/internal/runtime/async-semaphore.ts"() {
14386
- init_errors();
14387
- }
14388
- });
14389
-
14390
14451
  // src/internal/task/ring-buffer.ts
14391
14452
  var RingBuffer;
14392
14453
  var init_ring_buffer = __esm({
@@ -14949,8 +15010,8 @@ var init_local_agent = __esm({
14949
15010
  init_span_names();
14950
15011
  init_tracer();
14951
15012
  init_hooks_executor();
14952
- init_memory_path_selector();
14953
15013
  init_post_run_lifecycle();
15014
+ init_memory_path_selector();
14954
15015
  init_agent_registry();
14955
15016
  init_live_agent_registry();
14956
15017
  init_agent_session();
@@ -16419,7 +16480,13 @@ var init_agent = __esm({
16419
16480
  await flushRegistrySaves();
16420
16481
  }
16421
16482
  };
16422
- setAgentCreate((options) => Agent.create(options));
16483
+ setAgentFacade({
16484
+ create: (options) => Agent.create(options),
16485
+ prompt: (message, options) => Agent.prompt(message, options),
16486
+ get: (agentId) => Agent.get(agentId),
16487
+ resume: (agentId, options) => Agent.resume(agentId, options),
16488
+ batch: (prompts, options) => Agent.batch(prompts, options)
16489
+ });
16423
16490
  }
16424
16491
  });
16425
16492