@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
@@ -132,6 +132,24 @@ var init_agent_builder = __esm({
132
132
  }
133
133
  });
134
134
 
135
+ // src/internal/default-retriable.ts
136
+ function defaultRetriableForCode(code) {
137
+ switch (code) {
138
+ case "rate_limit":
139
+ case "timeout":
140
+ case "server_error":
141
+ case "network":
142
+ case "provider_unreachable":
143
+ return true;
144
+ default:
145
+ return false;
146
+ }
147
+ }
148
+ var init_default_retriable = __esm({
149
+ "src/internal/default-retriable.ts"() {
150
+ }
151
+ });
152
+
135
153
  // src/internal/security/redact.ts
136
154
  function readEnvOnce() {
137
155
  const raw = process.env.THEOKIT_REDACT_SECRETS;
@@ -282,7 +300,8 @@ __export(errors_exports, {
282
300
  UnsupportedBudgetOperationError: () => UnsupportedBudgetOperationError,
283
301
  UnsupportedRunOperationError: () => UnsupportedRunOperationError,
284
302
  UnsupportedTaskOperationError: () => UnsupportedTaskOperationError,
285
- coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode
303
+ coerceToKnownAgentRunErrorCode: () => coerceToKnownAgentRunErrorCode,
304
+ isTransientError: () => isTransientError
286
305
  });
287
306
  function coerceToKnownAgentRunErrorCode(code) {
288
307
  if (code !== void 0 && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {
@@ -314,21 +333,13 @@ function safeStringify(value) {
314
333
  return String(value);
315
334
  }
316
335
  }
317
- function defaultRetriableForCode(code) {
318
- switch (code) {
319
- case "rate_limit":
320
- case "timeout":
321
- case "server_error":
322
- case "network":
323
- case "provider_unreachable":
324
- return true;
325
- default:
326
- return false;
327
- }
336
+ function isTransientError(err) {
337
+ return err instanceof TheokitAgentError && err.isRetryable === true;
328
338
  }
329
339
  var KNOWN_AGENT_RUN_ERROR_CODES, TheokitAgentError, AuthenticationError, RateLimitError, ConfigurationError, IntegrationNotConnectedError, NetworkError, UnknownAgentError, AgentRunError, UnsupportedRunOperationError, CredentialPoolExhaustedError, MemoryAdapterError, InvalidTaskIdError, TaskNotFoundError, UnsupportedTaskOperationError, BudgetExceededError, AgentDisposedError, UnsupportedBudgetOperationError;
330
340
  var init_errors = __esm({
331
341
  "src/errors.ts"() {
342
+ init_default_retriable();
332
343
  init_redact();
333
344
  KNOWN_AGENT_RUN_ERROR_CODES = /* @__PURE__ */ new Set([
334
345
  "rate_limit",
@@ -1027,6 +1038,19 @@ function sanitizeIdentifier(input, options) {
1027
1038
  }
1028
1039
  return input.toLowerCase();
1029
1040
  }
1041
+ function safeFilenameForId(id, options) {
1042
+ if (id.length === 0) {
1043
+ throw new ConfigurationError("Filename id must be a non-empty string", {
1044
+ code: "invalid_filename_id"
1045
+ });
1046
+ }
1047
+ const maxLen = options?.maxLen;
1048
+ const lower = id.toLowerCase();
1049
+ if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {
1050
+ return lower;
1051
+ }
1052
+ return `h-${crypto.createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
1053
+ }
1030
1054
  var PathTraversalError, IDENTIFIER_PATTERN;
1031
1055
  var init_path_guard = __esm({
1032
1056
  "src/internal/security/path-guard.ts"() {
@@ -1043,10 +1067,10 @@ var init_path_guard = __esm({
1043
1067
  }
1044
1068
  });
1045
1069
 
1046
- // src/internal/runtime/default-model.ts
1070
+ // src/internal/runtime/config/default-model.ts
1047
1071
  var DEFAULT_AGENTIC_MODEL_ID;
1048
1072
  var init_default_model = __esm({
1049
- "src/internal/runtime/default-model.ts"() {
1073
+ "src/internal/runtime/config/default-model.ts"() {
1050
1074
  DEFAULT_AGENTIC_MODEL_ID = "google/gemini-2.0-flash-001";
1051
1075
  }
1052
1076
  });
@@ -1442,7 +1466,7 @@ var init_agent_registry = __esm({
1442
1466
  }
1443
1467
  });
1444
1468
 
1445
- // src/internal/runtime/system-prompt.ts
1469
+ // src/internal/runtime/system-prompt/system-prompt.ts
1446
1470
  async function resolveSystemPrompt(agent, override, ctx) {
1447
1471
  if (override !== void 0) return override;
1448
1472
  if (agent === void 0) return void 0;
@@ -1460,7 +1484,7 @@ async function resolveSystemPromptForSend(agent, override, buildCtx) {
1460
1484
  return resolveSystemPrompt(agent, override, ctx);
1461
1485
  }
1462
1486
  var init_system_prompt = __esm({
1463
- "src/internal/runtime/system-prompt.ts"() {
1487
+ "src/internal/runtime/system-prompt/system-prompt.ts"() {
1464
1488
  }
1465
1489
  });
1466
1490
 
@@ -3114,7 +3138,7 @@ var init_paths = __esm({
3114
3138
  }
3115
3139
  });
3116
3140
 
3117
- // src/internal/runtime/yaml-frontmatter.ts
3141
+ // src/internal/runtime/context/yaml-frontmatter.ts
3118
3142
  function parseSimpleYaml(text) {
3119
3143
  const fields = {};
3120
3144
  for (const line of text.split(/\r?\n/)) {
@@ -3138,7 +3162,7 @@ function coerce(raw) {
3138
3162
  return raw;
3139
3163
  }
3140
3164
  var init_yaml_frontmatter = __esm({
3141
- "src/internal/runtime/yaml-frontmatter.ts"() {
3165
+ "src/internal/runtime/context/yaml-frontmatter.ts"() {
3142
3166
  }
3143
3167
  });
3144
3168
  async function loadMarkdownEntities(opts) {
@@ -4142,7 +4166,7 @@ function spawnAndCollect(options) {
4142
4166
  });
4143
4167
  }
4144
4168
  var init_spawn_collect = __esm({
4145
- "src/internal/runtime/spawn-collect.ts"() {
4169
+ "src/internal/runtime/lifecycle/spawn-collect.ts"() {
4146
4170
  }
4147
4171
  });
4148
4172
 
@@ -4239,41 +4263,11 @@ var init_hooks_executor = __esm({
4239
4263
  };
4240
4264
  }
4241
4265
  });
4242
-
4243
- // src/internal/runtime/memory/memory-path-selector.ts
4244
- function shouldUsePortMemoryPath() {
4245
- const env = globalThis.process?.env;
4246
- if (env === void 0) return false;
4247
- const val = env[PORT_MEMORY_PATH_ENV_VAR];
4248
- return val === "1" || val === "true";
4249
- }
4250
- function resolveMemoryProviderForLoop(consumerSupplied, defaultAdapter, portPathEnabled) {
4251
- if (consumerSupplied !== void 0) return consumerSupplied;
4252
- if (portPathEnabled) return defaultAdapter;
4253
- return void 0;
4254
- }
4255
- function resolveMemoryToolsForLoop(legacyTools, portPathEnabled) {
4256
- if (portPathEnabled) return void 0;
4257
- return legacyTools;
4258
- }
4259
- function resolveActiveMemorySummaryForSend(legacySummary, portPathEnabled) {
4260
- if (portPathEnabled) return void 0;
4261
- return legacySummary;
4262
- }
4263
- var PORT_MEMORY_PATH_ENV_VAR;
4264
- var init_memory_path_selector = __esm({
4265
- "src/internal/runtime/memory/memory-path-selector.ts"() {
4266
- PORT_MEMORY_PATH_ENV_VAR = "THEOKIT_PORT_MEMORY_PATH";
4267
- }
4268
- });
4269
4266
  function sessionsDir(cwd) {
4270
4267
  return path.join(memoryDir(cwd), "sessions");
4271
4268
  }
4272
4269
  function sessionSummaryPath(cwd, runId) {
4273
- return path.join(sessionsDir(cwd), `${sanitizeRunId(runId)}.md`);
4274
- }
4275
- function sanitizeRunId(runId) {
4276
- return runId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
4270
+ return path.join(sessionsDir(cwd), `${safeFilenameForId(runId, { maxLen: 128 })}.md`);
4277
4271
  }
4278
4272
  function truncate(text) {
4279
4273
  if (text.length <= MAX_TURN_CHARS) return text;
@@ -4309,11 +4303,39 @@ var MAX_TURN_CHARS;
4309
4303
  var init_session_summary_writer = __esm({
4310
4304
  "src/internal/memory/storage/session-summary-writer.ts"() {
4311
4305
  init_atomic_write();
4306
+ init_path_guard();
4312
4307
  init_types();
4313
4308
  init_markdown_store();
4314
4309
  MAX_TURN_CHARS = 2e3;
4315
4310
  }
4316
4311
  });
4312
+
4313
+ // src/internal/runtime/memory/memory-path-selector.ts
4314
+ function shouldUsePortMemoryPath() {
4315
+ const env = globalThis.process?.env;
4316
+ if (env === void 0) return false;
4317
+ const val = env[PORT_MEMORY_PATH_ENV_VAR];
4318
+ return val === "1" || val === "true";
4319
+ }
4320
+ function resolveMemoryProviderForLoop(consumerSupplied, defaultAdapter, portPathEnabled) {
4321
+ if (consumerSupplied !== void 0) return consumerSupplied;
4322
+ if (portPathEnabled) return defaultAdapter;
4323
+ return void 0;
4324
+ }
4325
+ function resolveMemoryToolsForLoop(legacyTools, portPathEnabled) {
4326
+ if (portPathEnabled) return void 0;
4327
+ return legacyTools;
4328
+ }
4329
+ function resolveActiveMemorySummaryForSend(legacySummary, portPathEnabled) {
4330
+ if (portPathEnabled) return void 0;
4331
+ return legacySummary;
4332
+ }
4333
+ var PORT_MEMORY_PATH_ENV_VAR;
4334
+ var init_memory_path_selector = __esm({
4335
+ "src/internal/runtime/memory/memory-path-selector.ts"() {
4336
+ PORT_MEMORY_PATH_ENV_VAR = "THEOKIT_PORT_MEMORY_PATH";
4337
+ }
4338
+ });
4317
4339
  function sessionFilePath(cwd, agentId) {
4318
4340
  const safe2 = sanitizeIdentifier(agentId, { maxLen: 128 });
4319
4341
  return safePathJoin(cwd, ".theokit", "agents", safe2, "messages.jsonl");
@@ -4587,7 +4609,7 @@ var init_agent_session = __esm({
4587
4609
  }
4588
4610
  });
4589
4611
 
4590
- // src/internal/runtime/post-run-lifecycle.ts
4612
+ // src/internal/runtime/lifecycle/post-run-lifecycle.ts
4591
4613
  async function runPostRunLifecycle(inputs) {
4592
4614
  const {
4593
4615
  run,
@@ -4648,7 +4670,7 @@ async function runPostRunLifecycle(inputs) {
4648
4670
  await flushSessionWrites();
4649
4671
  }
4650
4672
  var init_post_run_lifecycle = __esm({
4651
- "src/internal/runtime/post-run-lifecycle.ts"() {
4673
+ "src/internal/runtime/lifecycle/post-run-lifecycle.ts"() {
4652
4674
  init_session_summary_writer();
4653
4675
  init_memory_path_selector();
4654
4676
  init_agent_session();
@@ -4840,7 +4862,7 @@ async function readWorkspaceDir(root, errorCode, describe) {
4840
4862
  }
4841
4863
  }
4842
4864
  var init_workspace_dir = __esm({
4843
- "src/internal/runtime/workspace-dir.ts"() {
4865
+ "src/internal/runtime/config/workspace-dir.ts"() {
4844
4866
  init_errors();
4845
4867
  }
4846
4868
  });
@@ -5171,7 +5193,7 @@ var init_pipeline = __esm({
5171
5193
  }
5172
5194
  });
5173
5195
 
5174
- // src/internal/runtime/validate-agent-options.ts
5196
+ // src/internal/runtime/validation/validate-agent-options.ts
5175
5197
  function validateAgentOptions(options) {
5176
5198
  rejectProgrammaticHooks(options);
5177
5199
  ensureRuntimeShape(options);
@@ -5364,12 +5386,82 @@ function validateMemory(options) {
5364
5386
  }
5365
5387
  var TOOL_NAME_PATTERN, RESERVED_TOOL_NAMES;
5366
5388
  var init_validate_agent_options = __esm({
5367
- "src/internal/runtime/validate-agent-options.ts"() {
5389
+ "src/internal/runtime/validation/validate-agent-options.ts"() {
5368
5390
  init_errors();
5369
5391
  TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
5370
5392
  RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set(["shell", "memory_search", "memory_get"]);
5371
5393
  }
5372
5394
  });
5395
+
5396
+ // src/internal/runtime/config/providers-manager.ts
5397
+ function providerFromModel(model) {
5398
+ if (model === void 0) return void 0;
5399
+ const id = model.id;
5400
+ if (id.includes(":")) return id.split(":")[0];
5401
+ return void 0;
5402
+ }
5403
+ function resolveRoute(route, modelProvider, plugins) {
5404
+ if (route.capability === "chat" && modelProvider === route.provider) {
5405
+ const modelName = extractModelName(modelProvider, route);
5406
+ const base = {
5407
+ capability: route.capability,
5408
+ provider: route.provider,
5409
+ reason: "explicit-model-provider"
5410
+ };
5411
+ if (modelName !== void 0) base.model = modelName;
5412
+ return base;
5413
+ }
5414
+ if (plugins?.enabled !== void 0 && plugins.enabled.length > 0) {
5415
+ return {
5416
+ capability: route.capability,
5417
+ provider: route.provider,
5418
+ reason: "first-available-plugin-provider"
5419
+ };
5420
+ }
5421
+ return {
5422
+ capability: route.capability,
5423
+ provider: route.provider,
5424
+ reason: "explicit-route"
5425
+ };
5426
+ }
5427
+ function extractModelName(prefix, route) {
5428
+ if (route.model !== void 0) return route.model;
5429
+ return prefix === route.provider ? defaultModelForProvider(prefix) : void 0;
5430
+ }
5431
+ function defaultModelForProvider(provider) {
5432
+ if (provider === "anthropic") return "claude-3-7-sonnet";
5433
+ return void 0;
5434
+ }
5435
+ var ProvidersManagerImpl;
5436
+ var init_providers_manager = __esm({
5437
+ "src/internal/runtime/config/providers-manager.ts"() {
5438
+ ProvidersManagerImpl = class {
5439
+ constructor(model, providers, plugins) {
5440
+ this.model = model;
5441
+ this.providers = providers;
5442
+ this.plugins = plugins;
5443
+ }
5444
+ model;
5445
+ providers;
5446
+ plugins;
5447
+ routes() {
5448
+ const resolved = [];
5449
+ const modelProvider = providerFromModel(this.model);
5450
+ const seen = /* @__PURE__ */ new Set();
5451
+ if (this.providers?.routes !== void 0) {
5452
+ for (const route of this.providers.routes) {
5453
+ const resolvedRoute = resolveRoute(route, modelProvider, this.plugins);
5454
+ if (!seen.has(route.capability)) {
5455
+ seen.add(route.capability);
5456
+ resolved.push(resolvedRoute);
5457
+ }
5458
+ }
5459
+ }
5460
+ return Promise.resolve(resolved);
5461
+ }
5462
+ };
5463
+ }
5464
+ });
5373
5465
  function truncateWithMarker(content, max) {
5374
5466
  if (content.length <= max) {
5375
5467
  return { truncated: false, finalContent: content };
@@ -6135,8 +6227,8 @@ var init_plugins_manager = __esm({
6135
6227
  init_errors();
6136
6228
  init_markdown_config_loader();
6137
6229
  init_path_guard();
6138
- init_hooks_source();
6139
6230
  init_workspace_dir();
6231
+ init_hooks_source();
6140
6232
  init_plugin_frontmatter();
6141
6233
  PluginsManager = class {
6142
6234
  constructor(cwd, enabled, settingSourcesIncludePlugins, cloud, localPaths) {
@@ -6219,76 +6311,6 @@ var init_plugins_manager = __esm({
6219
6311
  }
6220
6312
  });
6221
6313
 
6222
- // src/internal/runtime/providers-manager.ts
6223
- function providerFromModel(model) {
6224
- if (model === void 0) return void 0;
6225
- const id = model.id;
6226
- if (id.includes(":")) return id.split(":")[0];
6227
- return void 0;
6228
- }
6229
- function resolveRoute(route, modelProvider, plugins) {
6230
- if (route.capability === "chat" && modelProvider === route.provider) {
6231
- const modelName = extractModelName(modelProvider, route);
6232
- const base = {
6233
- capability: route.capability,
6234
- provider: route.provider,
6235
- reason: "explicit-model-provider"
6236
- };
6237
- if (modelName !== void 0) base.model = modelName;
6238
- return base;
6239
- }
6240
- if (plugins?.enabled !== void 0 && plugins.enabled.length > 0) {
6241
- return {
6242
- capability: route.capability,
6243
- provider: route.provider,
6244
- reason: "first-available-plugin-provider"
6245
- };
6246
- }
6247
- return {
6248
- capability: route.capability,
6249
- provider: route.provider,
6250
- reason: "explicit-route"
6251
- };
6252
- }
6253
- function extractModelName(prefix, route) {
6254
- if (route.model !== void 0) return route.model;
6255
- return prefix === route.provider ? defaultModelForProvider(prefix) : void 0;
6256
- }
6257
- function defaultModelForProvider(provider) {
6258
- if (provider === "anthropic") return "claude-3-7-sonnet";
6259
- return void 0;
6260
- }
6261
- var ProvidersManagerImpl;
6262
- var init_providers_manager = __esm({
6263
- "src/internal/runtime/providers-manager.ts"() {
6264
- ProvidersManagerImpl = class {
6265
- constructor(model, providers, plugins) {
6266
- this.model = model;
6267
- this.providers = providers;
6268
- this.plugins = plugins;
6269
- }
6270
- model;
6271
- providers;
6272
- plugins;
6273
- routes() {
6274
- const resolved = [];
6275
- const modelProvider = providerFromModel(this.model);
6276
- const seen = /* @__PURE__ */ new Set();
6277
- if (this.providers?.routes !== void 0) {
6278
- for (const route of this.providers.routes) {
6279
- const resolvedRoute = resolveRoute(route, modelProvider, this.plugins);
6280
- if (!seen.has(route.capability)) {
6281
- seen.add(route.capability);
6282
- resolved.push(resolvedRoute);
6283
- }
6284
- }
6285
- }
6286
- return Promise.resolve(resolved);
6287
- }
6288
- };
6289
- }
6290
- });
6291
-
6292
6314
  // src/internal/runtime/skills/skill-frontmatter.ts
6293
6315
  function asString(v) {
6294
6316
  return typeof v === "string" ? v : void 0;
@@ -6495,9 +6517,9 @@ function bootstrapSubmanagers(args) {
6495
6517
  }
6496
6518
  var init_local_agent_bootstrap = __esm({
6497
6519
  "src/internal/runtime/local-agent/local-agent-bootstrap.ts"() {
6520
+ init_providers_manager();
6498
6521
  init_context_manager();
6499
6522
  init_plugins_manager();
6500
- init_providers_manager();
6501
6523
  init_agent_registry();
6502
6524
  init_skills_manager();
6503
6525
  }
@@ -6671,7 +6693,7 @@ var init_budget = __esm({
6671
6693
  }
6672
6694
  });
6673
6695
 
6674
- // src/internal/runtime/validate-response.ts
6696
+ // src/internal/runtime/validation/validate-response.ts
6675
6697
  function validateResponse(response) {
6676
6698
  const trimmed = response.content.trim();
6677
6699
  const toolCallsArr = Array.isArray(response.toolCalls) ? response.toolCalls : [];
@@ -6684,7 +6706,7 @@ function validateResponse(response) {
6684
6706
  return { ok: true };
6685
6707
  }
6686
6708
  var init_validate_response = __esm({
6687
- "src/internal/runtime/validate-response.ts"() {
6709
+ "src/internal/runtime/validation/validate-response.ts"() {
6688
6710
  }
6689
6711
  });
6690
6712
 
@@ -7107,11 +7129,80 @@ function checkToolWhitelist(toolName) {
7107
7129
  }
7108
7130
  var toolWhitelistStore;
7109
7131
  var init_async_local_storage = __esm({
7110
- "src/internal/runtime/async-local-storage.ts"() {
7132
+ "src/internal/runtime/concurrency/async-local-storage.ts"() {
7111
7133
  toolWhitelistStore = new async_hooks.AsyncLocalStorage();
7112
7134
  }
7113
7135
  });
7114
7136
 
7137
+ // src/internal/runtime/concurrency/async-semaphore.ts
7138
+ function createSemaphore(permits) {
7139
+ if (!Number.isInteger(permits) || permits < 1) {
7140
+ throw new ConfigurationError(
7141
+ `async-semaphore: permits must be a positive integer, got ${permits}`,
7142
+ { code: "invalid_concurrency" }
7143
+ );
7144
+ }
7145
+ let active = 0;
7146
+ const queue = [];
7147
+ function tryGrant() {
7148
+ if (active < permits && queue.length > 0) {
7149
+ const resolve3 = queue.shift();
7150
+ if (resolve3 !== void 0) {
7151
+ active += 1;
7152
+ resolve3();
7153
+ }
7154
+ }
7155
+ }
7156
+ return {
7157
+ inFlight: () => active,
7158
+ pending: () => queue.length + active,
7159
+ async acquire() {
7160
+ await new Promise((resolve3) => {
7161
+ queue.push(resolve3);
7162
+ tryGrant();
7163
+ });
7164
+ let released = false;
7165
+ return () => {
7166
+ if (released) return;
7167
+ released = true;
7168
+ active -= 1;
7169
+ tryGrant();
7170
+ };
7171
+ }
7172
+ };
7173
+ }
7174
+ var init_async_semaphore = __esm({
7175
+ "src/internal/runtime/concurrency/async-semaphore.ts"() {
7176
+ init_errors();
7177
+ }
7178
+ });
7179
+
7180
+ // src/internal/runtime/concurrency/map-with-concurrency.ts
7181
+ async function mapWithConcurrency(items, concurrency, fn, options) {
7182
+ const semaphore = createSemaphore(concurrency);
7183
+ const signal = NEVER_ABORT;
7184
+ return Promise.all(
7185
+ items.map(async (item, index) => {
7186
+ const release = await semaphore.acquire();
7187
+ try {
7188
+ if (signal.aborted) {
7189
+ throw signal.reason instanceof Error ? signal.reason : new Error("mapWithConcurrency: aborted");
7190
+ }
7191
+ return await fn(item, index, signal);
7192
+ } finally {
7193
+ release();
7194
+ }
7195
+ })
7196
+ );
7197
+ }
7198
+ var NEVER_ABORT;
7199
+ var init_map_with_concurrency = __esm({
7200
+ "src/internal/runtime/concurrency/map-with-concurrency.ts"() {
7201
+ init_async_semaphore();
7202
+ NEVER_ABORT = new AbortController().signal;
7203
+ }
7204
+ });
7205
+
7115
7206
  // src/internal/tool-dispatch/repair-middleware.ts
7116
7207
  function repairToolCall(raw, registry) {
7117
7208
  const repairs = [];
@@ -7190,7 +7281,7 @@ var init_repair_middleware = __esm({
7190
7281
  }
7191
7282
  });
7192
7283
 
7193
- // src/internal/runtime/shell-tool.ts
7284
+ // src/internal/runtime/tools/shell-tool.ts
7194
7285
  async function runShell(options) {
7195
7286
  if (options.sandbox === true && isObviouslyUnsafe(options.command)) {
7196
7287
  return {
@@ -7221,7 +7312,7 @@ function isObviouslyUnsafe(command) {
7221
7312
  return false;
7222
7313
  }
7223
7314
  var init_shell_tool = __esm({
7224
- "src/internal/runtime/shell-tool.ts"() {
7315
+ "src/internal/runtime/tools/shell-tool.ts"() {
7225
7316
  init_spawn_collect();
7226
7317
  }
7227
7318
  });
@@ -7301,38 +7392,12 @@ var init_tool_executors = __esm({
7301
7392
  // src/internal/agent-loop/tool-dispatch.ts
7302
7393
  async function dispatchTools(inputs, tools, toolCalls, events) {
7303
7394
  const maxConcurrent = inputs.maxConcurrentTools ?? 4;
7304
- return boundedParallel(
7305
- maxConcurrent,
7395
+ return mapWithConcurrency(
7306
7396
  toolCalls,
7397
+ maxConcurrent,
7307
7398
  (call) => dispatchSingleCall(inputs, tools, call, events)
7308
7399
  );
7309
7400
  }
7310
- async function boundedParallel(max, items, fn) {
7311
- let running = 0;
7312
- const queue = [];
7313
- async function acquire() {
7314
- if (running < max) {
7315
- running++;
7316
- return;
7317
- }
7318
- await new Promise((resolve3) => queue.push(resolve3));
7319
- running++;
7320
- }
7321
- function release() {
7322
- running--;
7323
- if (queue.length > 0) queue.shift()();
7324
- }
7325
- return Promise.all(
7326
- items.map(async (item) => {
7327
- await acquire();
7328
- try {
7329
- return await fn(item);
7330
- } finally {
7331
- release();
7332
- }
7333
- })
7334
- );
7335
- }
7336
7401
  async function dispatchSingleCall(inputs, tools, call, events) {
7337
7402
  const { call: workingCall, repairs } = applyRepairAndExtractCall(tools, call);
7338
7403
  const callId = generateCallId();
@@ -7556,6 +7621,7 @@ var init_tool_dispatch = __esm({
7556
7621
  "src/internal/agent-loop/tool-dispatch.ts"() {
7557
7622
  init_ids();
7558
7623
  init_async_local_storage();
7624
+ init_map_with_concurrency();
7559
7625
  init_repair_middleware();
7560
7626
  init_tool_executors();
7561
7627
  }
@@ -8538,7 +8604,7 @@ var init_providers = __esm({
8538
8604
  }
8539
8605
  });
8540
8606
 
8541
- // src/internal/errors/mappers/shared.ts
8607
+ // src/internal/error-mappers/shared.ts
8542
8608
  function parseRetryAfter(headers) {
8543
8609
  if (headers === void 0) return void 0;
8544
8610
  const raw = headers.get("retry-after");
@@ -8567,13 +8633,13 @@ function buildErrorMetadata(args) {
8567
8633
  }
8568
8634
  var RAW_MAX_BYTES;
8569
8635
  var init_shared = __esm({
8570
- "src/internal/errors/mappers/shared.ts"() {
8636
+ "src/internal/error-mappers/shared.ts"() {
8571
8637
  init_security();
8572
8638
  RAW_MAX_BYTES = 2048;
8573
8639
  }
8574
8640
  });
8575
8641
 
8576
- // src/internal/errors/mappers/anthropic.ts
8642
+ // src/internal/error-mappers/anthropic.ts
8577
8643
  function mapAnthropicError(args) {
8578
8644
  const { status, body, headers, endpoint } = args;
8579
8645
  const code = mapAnthropicStatusToCode(status, body);
@@ -8627,7 +8693,7 @@ function formatMessage(status, code) {
8627
8693
  return `Anthropic API error: ${code} (HTTP ${status})`;
8628
8694
  }
8629
8695
  var init_anthropic2 = __esm({
8630
- "src/internal/errors/mappers/anthropic.ts"() {
8696
+ "src/internal/error-mappers/anthropic.ts"() {
8631
8697
  init_errors();
8632
8698
  init_shared();
8633
8699
  }
@@ -8934,7 +9000,7 @@ var init_anthropic3 = __esm({
8934
9000
  }
8935
9001
  });
8936
9002
 
8937
- // src/internal/errors/mappers/bedrock.ts
9003
+ // src/internal/error-mappers/bedrock.ts
8938
9004
  function classifyBedrockError(args, awsType, message) {
8939
9005
  if (args.status === 429 || awsType.includes("Throttling") || awsType.includes("TooManyRequests")) {
8940
9006
  return "rate_limit";
@@ -8994,7 +9060,7 @@ function parseBody(body) {
8994
9060
  return {};
8995
9061
  }
8996
9062
  var init_bedrock2 = __esm({
8997
- "src/internal/errors/mappers/bedrock.ts"() {
9063
+ "src/internal/error-mappers/bedrock.ts"() {
8998
9064
  init_errors();
8999
9065
  init_shared();
9000
9066
  }
@@ -9381,7 +9447,7 @@ var init_credential_pool_context = __esm({
9381
9447
  }
9382
9448
  });
9383
9449
 
9384
- // src/internal/errors/mappers/openai-compatible.ts
9450
+ // src/internal/error-mappers/openai-compatible.ts
9385
9451
  function mapOpenAICompatibleError(args) {
9386
9452
  const { providerId, status, body, headers, endpoint } = args;
9387
9453
  const code = mapOpenAiStatusToCode(status, body);
@@ -9444,7 +9510,7 @@ function formatMessage2(providerId, status, code) {
9444
9510
  return `${providerId} API error: ${code} (HTTP ${status})`;
9445
9511
  }
9446
9512
  var init_openai_compatible = __esm({
9447
- "src/internal/errors/mappers/openai-compatible.ts"() {
9513
+ "src/internal/error-mappers/openai-compatible.ts"() {
9448
9514
  init_errors();
9449
9515
  init_shared();
9450
9516
  }
@@ -9556,7 +9622,7 @@ var init_fault_injection = __esm({
9556
9622
  }
9557
9623
  });
9558
9624
 
9559
- // src/internal/errors/mappers/ollama.ts
9625
+ // src/internal/error-mappers/ollama.ts
9560
9626
  function mapOllamaTransportError(args) {
9561
9627
  if (args.providerId !== "ollama") return void 0;
9562
9628
  const causeCode = extractCauseCode(args.cause);
@@ -9629,7 +9695,7 @@ function extractModelName2(errString) {
9629
9695
  return match?.[1];
9630
9696
  }
9631
9697
  var init_ollama2 = __esm({
9632
- "src/internal/errors/mappers/ollama.ts"() {
9698
+ "src/internal/error-mappers/ollama.ts"() {
9633
9699
  init_errors();
9634
9700
  init_shared();
9635
9701
  }
@@ -10230,7 +10296,7 @@ var init_pool_aware_client = __esm({
10230
10296
  }
10231
10297
  });
10232
10298
 
10233
- // src/internal/errors/mappers/vertex.ts
10299
+ // src/internal/error-mappers/vertex.ts
10234
10300
  function classifyVertexError(args, errStatus) {
10235
10301
  for (const rule of VERTEX_RULES) {
10236
10302
  if (rule.test(args.status, errStatus)) return rule.code;
@@ -10267,7 +10333,7 @@ function parseBody2(body) {
10267
10333
  }
10268
10334
  var VERTEX_RULES, VERTEX_ERROR_BUILDERS;
10269
10335
  var init_vertex2 = __esm({
10270
- "src/internal/errors/mappers/vertex.ts"() {
10336
+ "src/internal/error-mappers/vertex.ts"() {
10271
10337
  init_errors();
10272
10338
  init_shared();
10273
10339
  VERTEX_RULES = [
@@ -10827,6 +10893,21 @@ var init_client = __esm({
10827
10893
  }
10828
10894
  });
10829
10895
 
10896
+ // src/internal/providers/register-plugin-providers.ts
10897
+ function registerPluginProviderProfiles(entries) {
10898
+ let registered4 = 0;
10899
+ for (const entry of entries) {
10900
+ registerProvider(entry.profile);
10901
+ registered4 += 1;
10902
+ }
10903
+ return registered4;
10904
+ }
10905
+ var init_register_plugin_providers = __esm({
10906
+ "src/internal/providers/register-plugin-providers.ts"() {
10907
+ init_registry();
10908
+ }
10909
+ });
10910
+
10830
10911
  // src/internal/tool-registry/personality-filter.ts
10831
10912
  function applyPersonalityFilter(exposedTools, whitelist, opts) {
10832
10913
  if (whitelist === void 0) return exposedTools;
@@ -10907,12 +10988,26 @@ function createRealLocalRun(options) {
10907
10988
  registerRun(handle);
10908
10989
  return handle;
10909
10990
  }
10910
- function buildLoopInputs(options, runId, userText) {
10991
+ function resolveRunProvider(options) {
10911
10992
  registerBuiltins();
10993
+ const profiles = options.pluginManager?.aggregated.providerProfiles ?? [];
10994
+ const registered4 = registerPluginProviderProfiles(profiles);
10995
+ if (registered4 > 0 && !pluginProvidersAnnounced) {
10996
+ pluginProvidersAnnounced = true;
10997
+ const names = profiles.map((e) => e.profile.name).join(", ");
10998
+ process.stderr.write(
10999
+ `[theokit-sdk] registered ${registered4} plugin provider profile(s): ${names}
11000
+ `
11001
+ );
11002
+ }
10912
11003
  const parsedModel = parseModelId(options.model?.id);
10913
11004
  const inferredProvider = parsedModel.provider !== void 0 && getProviderProfile(parsedModel.provider) !== void 0 ? parsedModel.provider : void 0;
10914
11005
  const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? inferredProvider ?? detectPrimaryProvider();
10915
11006
  const effectiveModelId = inferredProvider !== void 0 ? parsedModel.name : options.model?.id ?? "claude-sonnet-4-6";
11007
+ return { primary, effectiveModelId };
11008
+ }
11009
+ function buildLoopInputs(options, runId, userText) {
11010
+ const { primary, effectiveModelId } = resolveRunProvider(options);
10916
11011
  const fallback = options.agentOptions.providers?.fallback;
10917
11012
  const apiKeys = options.agentOptions.providers?.apiKeys;
10918
11013
  const credentialPoolStrategy = options.agentOptions.providers?.credentialPoolStrategy;
@@ -11006,7 +11101,7 @@ function buildMcpMap(options) {
11006
11101
  }
11007
11102
  return map;
11008
11103
  }
11009
- var RealLocalRun;
11104
+ var pluginProvidersAnnounced, RealLocalRun;
11010
11105
  var init_real_local_run = __esm({
11011
11106
  "src/internal/runtime/local-agent/real-local-run.ts"() {
11012
11107
  init_loop();
@@ -11015,10 +11110,12 @@ var init_real_local_run = __esm({
11015
11110
  init_router();
11016
11111
  init_client();
11017
11112
  init_providers();
11113
+ init_register_plugin_providers();
11018
11114
  init_tracer();
11019
11115
  init_personality_filter();
11020
11116
  init_fixture_run_base();
11021
11117
  init_run_registry();
11118
+ pluginProvidersAnnounced = false;
11022
11119
  RealLocalRun = class extends FixtureRunBase {
11023
11120
  buildInputs;
11024
11121
  constructor(options, buildInputs) {
@@ -11570,7 +11667,7 @@ async function embedTexts(input) {
11570
11667
  pending
11571
11668
  });
11572
11669
  }
11573
- await runBatches(input, pending, results);
11670
+ await embedInBoundedBatches(input, pending, results);
11574
11671
  return results.map((v) => v ?? new Array(dimension).fill(0));
11575
11672
  }
11576
11673
  function classifyEntry(args) {
@@ -11588,45 +11685,34 @@ function classifyEntry(args) {
11588
11685
  args.stats.cacheMisses += 1;
11589
11686
  args.pending.push({ index: args.index, text: args.text, key });
11590
11687
  }
11591
- async function runBatches(input, pending, results) {
11688
+ async function embedInBoundedBatches(input, pending, results) {
11592
11689
  const batches = [];
11593
11690
  for (let offset = 0; offset < pending.length; offset += MAX_BATCH) {
11594
11691
  batches.push(pending.slice(offset, offset + MAX_BATCH));
11595
11692
  }
11596
- let running = 0;
11597
- const queue = [];
11598
- await Promise.all(batches.map((batch) => processBatch(input, batch, results, acquire, release)));
11599
- async function acquire() {
11600
- if (running >= MAX_CONCURRENT_BATCHES) await new Promise((r) => queue.push(r));
11601
- running++;
11602
- }
11603
- function release() {
11604
- running--;
11605
- if (queue.length > 0) queue.shift()();
11606
- }
11693
+ await mapWithConcurrency(
11694
+ batches,
11695
+ MAX_CONCURRENT_BATCHES,
11696
+ (batch) => processBatch(input, batch, results)
11697
+ );
11607
11698
  }
11608
- async function processBatch(input, batch, results, acquire, release) {
11609
- await acquire();
11610
- try {
11611
- const vectors = await embedBatch({
11612
- apiKey: input.apiKey,
11613
- baseUrl: input.baseUrl,
11614
- embeddingsPath: input.embeddingsPath,
11615
- model: input.model,
11616
- inputs: batch.map((b) => b.text),
11617
- fetchImpl: input.fetchImpl,
11618
- stats: input.stats,
11619
- providerId: input.providerId
11620
- });
11621
- for (let j = 0; j < batch.length; j++) {
11622
- const slot = batch[j];
11623
- const vector = vectors[j];
11624
- if (slot === void 0 || vector === void 0) continue;
11625
- results[slot.index] = vector;
11626
- input.cache.set(slot.key, vector);
11627
- }
11628
- } finally {
11629
- release();
11699
+ async function processBatch(input, batch, results) {
11700
+ const vectors = await embedBatch({
11701
+ apiKey: input.apiKey,
11702
+ baseUrl: input.baseUrl,
11703
+ embeddingsPath: input.embeddingsPath,
11704
+ model: input.model,
11705
+ inputs: batch.map((b) => b.text),
11706
+ fetchImpl: input.fetchImpl,
11707
+ stats: input.stats,
11708
+ providerId: input.providerId
11709
+ });
11710
+ for (let j = 0; j < batch.length; j++) {
11711
+ const slot = batch[j];
11712
+ const vector = vectors[j];
11713
+ if (slot === void 0 || vector === void 0) continue;
11714
+ results[slot.index] = vector;
11715
+ input.cache.set(slot.key, vector);
11630
11716
  }
11631
11717
  }
11632
11718
  async function embedBatch(opts) {
@@ -11700,6 +11786,7 @@ var init_openai_compatible2 = __esm({
11700
11786
  "src/internal/memory/adapters/openai-compatible.ts"() {
11701
11787
  init_errors();
11702
11788
  init_openai_compatible();
11789
+ init_map_with_concurrency();
11703
11790
  init_embedding_cache();
11704
11791
  MAX_BATCH = 100;
11705
11792
  MAX_RETRIES = 2;
@@ -12184,6 +12271,61 @@ var init_sqlite_wal = __esm({
12184
12271
  warnedLabels = /* @__PURE__ */ new Set();
12185
12272
  }
12186
12273
  });
12274
+ async function openSqliteResilient(options) {
12275
+ await promises.mkdir(path.dirname(options.filePath), { recursive: true });
12276
+ try {
12277
+ return await openConcrete(options);
12278
+ } catch (cause) {
12279
+ if (options.recoverCorrupt !== false && isCorruptionError(cause)) {
12280
+ await renameAside(options.filePath, options.label ?? "sqlite");
12281
+ return await openConcrete(options);
12282
+ }
12283
+ throw cause;
12284
+ }
12285
+ }
12286
+ async function openConcrete(options) {
12287
+ const db = await loadDriver(options.filePath);
12288
+ applyWalWithFallback(db, options.label ?? "sqlite");
12289
+ await options.onOpen?.(db);
12290
+ return db;
12291
+ }
12292
+ async function loadDriver(filePath) {
12293
+ try {
12294
+ const mod = await import('better-sqlite3');
12295
+ const Ctor = mod.default ?? mod;
12296
+ if (typeof Ctor !== "function") {
12297
+ throw new Error(`better-sqlite3 export is not a constructor (got ${typeof Ctor})`);
12298
+ }
12299
+ return new Ctor(filePath);
12300
+ } catch (cause) {
12301
+ const message = cause instanceof Error ? cause.message : String(cause);
12302
+ throw new ConfigurationError(
12303
+ `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
12304
+ { code: "sqlite_driver_unavailable", cause }
12305
+ );
12306
+ }
12307
+ }
12308
+ function isCorruptionError(cause) {
12309
+ if (!(cause instanceof Error)) return false;
12310
+ const msg = cause.message.toLowerCase();
12311
+ return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
12312
+ }
12313
+ async function renameAside(filePath, label) {
12314
+ const asidePath = `${filePath}.corrupt-${Date.now()}`;
12315
+ await promises.rename(filePath, asidePath).catch(() => void 0);
12316
+ await promises.rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
12317
+ await promises.rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
12318
+ process.stderr.write(
12319
+ `[theokit-sdk] ${label} database corrupt; renamed aside to ${asidePath} and rebuilt schema
12320
+ `
12321
+ );
12322
+ }
12323
+ var init_sqlite_open = __esm({
12324
+ "src/internal/persistence/sqlite-open.ts"() {
12325
+ init_errors();
12326
+ init_sqlite_wal();
12327
+ }
12328
+ });
12187
12329
 
12188
12330
  // src/internal/memory/index-schema.ts
12189
12331
  var SCHEMA_STATEMENTS, PRAGMA_STATEMENTS;
@@ -12231,60 +12373,22 @@ var init_index_schema = __esm({
12231
12373
  }
12232
12374
  });
12233
12375
  async function openMemoryDb(opts) {
12234
- await promises.mkdir(path.dirname(opts.filePath), { recursive: true });
12235
- try {
12236
- return await openConcrete(opts.filePath);
12237
- } catch (cause) {
12238
- if (opts.recoverCorrupt !== false && isCorruptionError(cause)) {
12239
- await renameAside(opts.filePath);
12240
- return await openConcrete(opts.filePath);
12376
+ return openSqliteResilient({
12377
+ filePath: opts.filePath,
12378
+ label: "memory-index",
12379
+ recoverCorrupt: opts.recoverCorrupt,
12380
+ onOpen: (db) => {
12381
+ for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
12382
+ for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
12241
12383
  }
12242
- throw cause;
12243
- }
12244
- }
12245
- async function openConcrete(filePath) {
12246
- const db = await loadDriver(filePath);
12247
- applyWalWithFallback(db, "memory-index");
12248
- for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
12249
- for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
12250
- return db;
12251
- }
12252
- async function loadDriver(filePath) {
12253
- try {
12254
- const mod = await import('better-sqlite3');
12255
- const Ctor = mod.default ?? mod;
12256
- const db = new Ctor(filePath);
12257
- return db;
12258
- } catch (cause) {
12259
- const message = cause instanceof Error ? cause.message : String(cause);
12260
- throw new ConfigurationError(
12261
- `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. Cause: ${message}`,
12262
- { code: "sqlite_driver_unavailable", cause }
12263
- );
12264
- }
12265
- }
12266
- function isCorruptionError(cause) {
12267
- if (!(cause instanceof Error)) return false;
12268
- const msg = cause.message.toLowerCase();
12269
- return msg.includes("malformed") || msg.includes("not a database") || msg.includes("encrypted") || msg.includes("disk image is malformed");
12270
- }
12271
- async function renameAside(filePath) {
12272
- const asidePath = `${filePath}.corrupt-${Date.now()}`;
12273
- await promises.rename(filePath, asidePath).catch(() => void 0);
12274
- await promises.rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
12275
- await promises.rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
12276
- process.stderr.write(
12277
- `[theokit-sdk] memory index corrupt; renamed aside to ${asidePath} and rebuilt schema
12278
- `
12279
- );
12384
+ });
12280
12385
  }
12281
12386
  function defaultIndexPath(cwd) {
12282
12387
  return path.join(cwd, ".theokit", "memory", ".index", "memory.sqlite");
12283
12388
  }
12284
12389
  var init_index_db = __esm({
12285
12390
  "src/internal/memory/index-db.ts"() {
12286
- init_errors();
12287
- init_sqlite_wal();
12391
+ init_sqlite_open();
12288
12392
  init_index_schema();
12289
12393
  }
12290
12394
  });
@@ -13836,7 +13940,7 @@ var init_local_agent_plugins = __esm({
13836
13940
  }
13837
13941
  });
13838
13942
 
13839
- // src/internal/runtime/run-until.ts
13943
+ // src/internal/runtime/lifecycle/run-until.ts
13840
13944
  var run_until_exports = {};
13841
13945
  __export(run_until_exports, {
13842
13946
  composeContinuation: () => composeContinuation,
@@ -13929,7 +14033,7 @@ Your last response was:
13929
14033
  ${lastResponse.slice(0, 1e3)}`;
13930
14034
  }
13931
14035
  var init_run_until = __esm({
13932
- "src/internal/runtime/run-until.ts"() {
14036
+ "src/internal/runtime/lifecycle/run-until.ts"() {
13933
14037
  }
13934
14038
  });
13935
14039
 
@@ -14040,16 +14144,16 @@ var init_judge_call = __esm({
14040
14144
  // src/internal/runtime/registry/agent-factory-registry.ts
14041
14145
  var agent_factory_registry_exports = {};
14042
14146
  __export(agent_factory_registry_exports, {
14043
- getAgentCreate: () => getAgentCreate,
14044
- setAgentCreate: () => setAgentCreate
14147
+ getAgentFacade: () => getAgentFacade,
14148
+ setAgentFacade: () => setAgentFacade
14045
14149
  });
14046
- function setAgentCreate(fn) {
14047
- registered3 = fn;
14150
+ function setAgentFacade(facade) {
14151
+ registered3 = facade;
14048
14152
  }
14049
- function getAgentCreate() {
14153
+ function getAgentFacade() {
14050
14154
  if (registered3 === void 0) {
14051
14155
  throw new Error(
14052
- "internal: Agent.create not registered. The `agent.ts` module must be loaded before LocalAgent.runUntil/fork are invoked."
14156
+ "internal: Agent facade not registered. The `agent.ts` module must be loaded before internal subsystems (LocalAgent.runUntil/fork, eval, scorers, cron) invoke it."
14053
14157
  );
14054
14158
  }
14055
14159
  return registered3;
@@ -14060,7 +14164,7 @@ var init_agent_factory_registry = __esm({
14060
14164
  }
14061
14165
  });
14062
14166
 
14063
- // src/internal/runtime/fork-agent.ts
14167
+ // src/internal/runtime/lifecycle/fork-agent.ts
14064
14168
  var fork_agent_exports = {};
14065
14169
  __export(fork_agent_exports, {
14066
14170
  filterMemoryPlugins: () => filterMemoryPlugins,
@@ -14120,7 +14224,7 @@ function extractUsage(result) {
14120
14224
  };
14121
14225
  }
14122
14226
  var init_fork_agent = __esm({
14123
- "src/internal/runtime/fork-agent.ts"() {
14227
+ "src/internal/runtime/lifecycle/fork-agent.ts"() {
14124
14228
  init_async_local_storage();
14125
14229
  init_local_agent_plugins();
14126
14230
  }
@@ -14131,8 +14235,8 @@ function localAgentRunUntil(agent, goal, options) {
14131
14235
  async function* wrap() {
14132
14236
  const { runUntilImpl: runUntilImpl2 } = await Promise.resolve().then(() => (init_run_until(), run_until_exports));
14133
14237
  const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
14134
- const { getAgentCreate: getAgentCreate2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14135
- const create = getAgentCreate2();
14238
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14239
+ const create = getAgentFacade2().create;
14136
14240
  const deps = {
14137
14241
  judge: async (ctx, opts) => judgeCallImpl2(ctx, opts, { create })
14138
14242
  };
@@ -14142,9 +14246,9 @@ function localAgentRunUntil(agent, goal, options) {
14142
14246
  }
14143
14247
  async function localAgentFork(parent, options) {
14144
14248
  const { forkAgentImpl: forkAgentImpl2 } = await Promise.resolve().then(() => (init_fork_agent(), fork_agent_exports));
14145
- const { getAgentCreate: getAgentCreate2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14249
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
14146
14250
  const { withPersonalityContext: withPersonalityContext2 } = await Promise.resolve().then(() => (init_context2(), context_exports));
14147
- const create = getAgentCreate2();
14251
+ const create = getAgentFacade2().create;
14148
14252
  return withPersonalityContext2(
14149
14253
  { slug: parent.personalitySlugSnapshot, isFork: true },
14150
14254
  () => forkAgentImpl2(parent, options, { create })
@@ -14168,7 +14272,7 @@ var init_local_agent_runtime_extensions = __esm({
14168
14272
  }
14169
14273
  });
14170
14274
 
14171
- // src/internal/runtime/abort-utils.ts
14275
+ // src/internal/runtime/concurrency/abort-utils.ts
14172
14276
  function anySignal(signals) {
14173
14277
  const filtered = signals.filter((s) => s !== void 0);
14174
14278
  if (filtered.length === 0) {
@@ -14194,7 +14298,7 @@ function ponyfillAny(signals) {
14194
14298
  return ctrl.signal;
14195
14299
  }
14196
14300
  var init_abort_utils = __esm({
14197
- "src/internal/runtime/abort-utils.ts"() {
14301
+ "src/internal/runtime/concurrency/abort-utils.ts"() {
14198
14302
  }
14199
14303
  });
14200
14304
 
@@ -14347,49 +14451,6 @@ var init_task = __esm({
14347
14451
  }
14348
14452
  });
14349
14453
 
14350
- // src/internal/runtime/async-semaphore.ts
14351
- function createSemaphore(permits) {
14352
- if (!Number.isInteger(permits) || permits < 1) {
14353
- throw new ConfigurationError(
14354
- `async-semaphore: permits must be a positive integer, got ${permits}`,
14355
- { code: "invalid_concurrency" }
14356
- );
14357
- }
14358
- let active = 0;
14359
- const queue = [];
14360
- function tryGrant() {
14361
- if (active < permits && queue.length > 0) {
14362
- const resolve3 = queue.shift();
14363
- if (resolve3 !== void 0) {
14364
- active += 1;
14365
- resolve3();
14366
- }
14367
- }
14368
- }
14369
- return {
14370
- inFlight: () => active,
14371
- pending: () => queue.length + active,
14372
- async acquire() {
14373
- await new Promise((resolve3) => {
14374
- queue.push(resolve3);
14375
- tryGrant();
14376
- });
14377
- let released = false;
14378
- return () => {
14379
- if (released) return;
14380
- released = true;
14381
- active -= 1;
14382
- tryGrant();
14383
- };
14384
- }
14385
- };
14386
- }
14387
- var init_async_semaphore = __esm({
14388
- "src/internal/runtime/async-semaphore.ts"() {
14389
- init_errors();
14390
- }
14391
- });
14392
-
14393
14454
  // src/internal/task/ring-buffer.ts
14394
14455
  var RingBuffer;
14395
14456
  var init_ring_buffer = __esm({
@@ -14952,8 +15013,8 @@ var init_local_agent = __esm({
14952
15013
  init_span_names();
14953
15014
  init_tracer();
14954
15015
  init_hooks_executor();
14955
- init_memory_path_selector();
14956
15016
  init_post_run_lifecycle();
15017
+ init_memory_path_selector();
14957
15018
  init_agent_registry();
14958
15019
  init_live_agent_registry();
14959
15020
  init_agent_session();
@@ -16422,7 +16483,13 @@ var init_agent = __esm({
16422
16483
  await flushRegistrySaves();
16423
16484
  }
16424
16485
  };
16425
- setAgentCreate((options) => Agent.create(options));
16486
+ setAgentFacade({
16487
+ create: (options) => Agent.create(options),
16488
+ prompt: (message, options) => Agent.prompt(message, options),
16489
+ get: (agentId) => Agent.get(agentId),
16490
+ resume: (agentId, options) => Agent.resume(agentId, options),
16491
+ batch: (prompts, options) => Agent.batch(prompts, options)
16492
+ });
16426
16493
  }
16427
16494
  });
16428
16495