@theokit/sdk 3.5.0 → 3.6.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.
package/dist/cron.cjs CHANGED
@@ -966,10 +966,10 @@ function buildToolPrompt(prompt) {
966
966
  Respond by calling the \`output\` tool with the structured answer that matches the schema.`;
967
967
  }
968
968
  function setupStructuredOutput(schema, maxRetries) {
969
- const z7 = requireZod();
969
+ const z8 = requireZod();
970
970
  const jsonSchema = toJsonSchema(schema, { unrepresentable: "any" });
971
971
  return {
972
- z: z7,
972
+ z: z8,
973
973
  jsonSchema,
974
974
  maxRetries: maxRetries ?? 1,
975
975
  initialUsage: { inputTokens: 0, outputTokens: 0 }
@@ -5759,6 +5759,213 @@ var init_subagents_loader = __esm({
5759
5759
  init_yaml_frontmatter();
5760
5760
  }
5761
5761
  });
5762
+ function loadJsonrepair() {
5763
+ if (cachedJsonrepair === void 0) {
5764
+ const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cron.cjs', document.baseURI).href)));
5765
+ cachedJsonrepair = req("jsonrepair").jsonrepair;
5766
+ }
5767
+ return cachedJsonrepair;
5768
+ }
5769
+ function isPlainObject(v) {
5770
+ return v !== null && typeof v === "object" && !Array.isArray(v);
5771
+ }
5772
+ function toFiniteNumber(raw) {
5773
+ if (raw === "") return void 0;
5774
+ const n = Number(raw);
5775
+ return Number.isFinite(n) && String(n) === raw ? n : void 0;
5776
+ }
5777
+ function tryJson(raw, repair) {
5778
+ const t = raw.trimStart();
5779
+ if (!(t.startsWith("{") || t.startsWith("["))) return void 0;
5780
+ try {
5781
+ return JSON.parse(repair ? loadJsonrepair()(t) : t);
5782
+ } catch {
5783
+ return void 0;
5784
+ }
5785
+ }
5786
+ function heuristicCoerce(raw, repairJson) {
5787
+ if (raw === "true") return true;
5788
+ if (raw === "false") return false;
5789
+ if (raw === "null") return null;
5790
+ const n = toFiniteNumber(raw);
5791
+ if (n !== void 0) return n;
5792
+ const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
5793
+ return json === void 0 ? raw : json;
5794
+ }
5795
+ function coerceCandidates(raw, repairJson) {
5796
+ const out = [];
5797
+ if (raw === "true") out.push(true);
5798
+ else if (raw === "false") out.push(false);
5799
+ else if (raw === "null") out.push(null);
5800
+ const n = toFiniteNumber(raw);
5801
+ if (n !== void 0) out.push(n);
5802
+ const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
5803
+ if (json !== void 0) out.push(json);
5804
+ out.push(raw);
5805
+ return out;
5806
+ }
5807
+ function objectShape(schema) {
5808
+ const shape = schema?.shape;
5809
+ return shape !== null && typeof shape === "object" ? shape : void 0;
5810
+ }
5811
+ var cachedJsonrepair;
5812
+ var init_coerce = __esm({
5813
+ "src/sanitize/coerce.ts"() {
5814
+ }
5815
+ });
5816
+
5817
+ // src/sanitize/sanitize-tool-input.ts
5818
+ function applyTrim(key, value, ctx) {
5819
+ const trimmed = value.trim();
5820
+ if (trimmed !== value) ctx.notes.push(`trimmed "${key}"`);
5821
+ return trimmed;
5822
+ }
5823
+ function applyCoerce(key, raw, ctx) {
5824
+ const field = ctx.shape?.[key];
5825
+ let coerced = raw;
5826
+ if (field) {
5827
+ for (const candidate of coerceCandidates(raw, ctx.repairJson)) {
5828
+ if (field.safeParse(candidate).success) {
5829
+ coerced = candidate;
5830
+ break;
5831
+ }
5832
+ }
5833
+ } else {
5834
+ coerced = heuristicCoerce(raw, ctx.repairJson);
5835
+ }
5836
+ if (coerced !== raw) ctx.notes.push(`coerced "${key}"`);
5837
+ return coerced;
5838
+ }
5839
+ function applyRepair(key, value, ctx) {
5840
+ const repaired = tryJson(value, true);
5841
+ if (repaired === void 0) return value;
5842
+ ctx.notes.push(`repaired json "${key}"`);
5843
+ return repaired;
5844
+ }
5845
+ function sanitizeString(key, value, ctx) {
5846
+ let out = ctx.trim ? applyTrim(key, value, ctx) : value;
5847
+ if (ctx.coerce && typeof out === "string") out = applyCoerce(key, out, ctx);
5848
+ if (ctx.repairJson && !ctx.coerce && typeof out === "string") out = applyRepair(key, out, ctx);
5849
+ return out;
5850
+ }
5851
+ function walk(input, ctx, depth) {
5852
+ const out = {};
5853
+ for (const [key, value] of Object.entries(input)) {
5854
+ if (typeof value === "string") out[key] = sanitizeString(key, value, ctx);
5855
+ else if (ctx.deep && depth < ctx.maxDepth && isPlainObject(value))
5856
+ out[key] = walk(value, ctx, depth + 1);
5857
+ else out[key] = value;
5858
+ }
5859
+ return out;
5860
+ }
5861
+ function sanitizeToolInput(input, options) {
5862
+ if (!isPlainObject(input)) return { value: input, changed: false, notes: [] };
5863
+ const ctx = {
5864
+ trim: options?.trim ?? true,
5865
+ coerce: options?.coerce ?? false,
5866
+ repairJson: options?.repairJson ?? false,
5867
+ deep: options?.deep ?? false,
5868
+ maxDepth: options?.maxDepth ?? 8,
5869
+ shape: objectShape(options?.schema),
5870
+ notes: []
5871
+ };
5872
+ const value = walk(input, ctx, 0);
5873
+ return { value, changed: ctx.notes.length > 0, notes: ctx.notes };
5874
+ }
5875
+ var init_sanitize_tool_input = __esm({
5876
+ "src/sanitize/sanitize-tool-input.ts"() {
5877
+ init_coerce();
5878
+ }
5879
+ });
5880
+
5881
+ // src/define-tool.ts
5882
+ async function runValidated(spec, input, ctx) {
5883
+ const raw = spec.sanitize ? sanitizeToolInput(input, {
5884
+ ...spec.sanitize === true ? {} : spec.sanitize,
5885
+ schema: spec.inputSchema
5886
+ }).value : input;
5887
+ const parsed = spec.inputSchema.parse(raw);
5888
+ const out = await spec.handler(parsed, ctx);
5889
+ return spec.outputSchema === void 0 ? out : spec.outputSchema.parse(out);
5890
+ }
5891
+ function serializeOutput(validated) {
5892
+ return typeof validated === "string" ? validated : JSON.stringify(validated);
5893
+ }
5894
+ function shapeModelOutput(spec, validated) {
5895
+ if (spec.toModelOutput !== void 0) return spec.toModelOutput(validated);
5896
+ return serializeOutput(validated);
5897
+ }
5898
+ function defineTool(spec) {
5899
+ const inputSchema = toJsonSchema(spec.inputSchema, {
5900
+ unrepresentable: "any"
5901
+ });
5902
+ const handler = async (input, ctx) => {
5903
+ const validated = await runValidated(spec, input, ctx);
5904
+ return shapeModelOutput(spec, validated);
5905
+ };
5906
+ const tool = { name: spec.name, description: spec.description, inputSchema, handler };
5907
+ if (spec.toModelOutput !== void 0) {
5908
+ const resolver = async (input, ctx) => {
5909
+ const validated = await runValidated(spec, input, ctx);
5910
+ return { model: shapeModelOutput(spec, validated), app: serializeOutput(validated) };
5911
+ };
5912
+ handler[TOOL_SPLIT_RESOLVER] = resolver;
5913
+ }
5914
+ return tool;
5915
+ }
5916
+ var TOOL_SPLIT_RESOLVER, Tool;
5917
+ var init_define_tool = __esm({
5918
+ "src/define-tool.ts"() {
5919
+ init_to_json_schema();
5920
+ init_sanitize_tool_input();
5921
+ TOOL_SPLIT_RESOLVER = /* @__PURE__ */ Symbol("theokit.toolSplitResolver");
5922
+ Tool = class {
5923
+ constructor() {
5924
+ }
5925
+ static create(spec) {
5926
+ return defineTool(spec);
5927
+ }
5928
+ };
5929
+ }
5930
+ });
5931
+ function createThinkTool() {
5932
+ return Tool.create({
5933
+ name: "think",
5934
+ description: "Scratchpad: reason through ONE step before answering. No side effects \u2014 your private reasoning space. Call it repeatedly before the final answer.",
5935
+ inputSchema: zod.z.object({ thought: zod.z.string().min(1, "think: `thought` must be non-empty.") }),
5936
+ handler: ({ thought }) => thought
5937
+ });
5938
+ }
5939
+ function isNativeReasoning(model) {
5940
+ if (model === void 0 || typeof model === "string") return false;
5941
+ const params = model.params;
5942
+ if (params === void 0) return false;
5943
+ return params.some((p) => NATIVE_REASONING_PARAM_IDS.has(p.id));
5944
+ }
5945
+ function warnDoubleReasoningOnce() {
5946
+ if (warned2.has("double-reasoning")) return;
5947
+ warned2.add("double-reasoning");
5948
+ process.stderr.write(
5949
+ "[theokit-sdk] `reasoning: true` skipped \u2014 a native reasoning model is configured (model.params thinking/reasoning); native reasoning wins. Remove one to silence.\n"
5950
+ );
5951
+ }
5952
+ function reasoningActive(reasoning, model) {
5953
+ if (reasoning !== true) return false;
5954
+ if (isNativeReasoning(model)) {
5955
+ warnDoubleReasoningOnce();
5956
+ return false;
5957
+ }
5958
+ return true;
5959
+ }
5960
+ var NATIVE_REASONING_PARAM_IDS, REASONING_PREAMBLE, warned2;
5961
+ var init_native_reasoning = __esm({
5962
+ "src/internal/runtime/reasoning/native-reasoning.ts"() {
5963
+ init_define_tool();
5964
+ NATIVE_REASONING_PARAM_IDS = /* @__PURE__ */ new Set(["thinking", "reasoning", "reasoning_effort"]);
5965
+ REASONING_PREAMBLE = "Think step by step before answering: use the `think` tool to reason through each step, validate your work, then answer. Reason about magnitude before comparing numbers.";
5966
+ warned2 = /* @__PURE__ */ new Set();
5967
+ }
5968
+ });
5762
5969
 
5763
5970
  // src/internal/runtime/skills/skill-frontmatter.ts
5764
5971
  function asString(v) {
@@ -6010,6 +6217,9 @@ async function buildAssemblyContext(inputs, userText, baseSystemPrompt, memoryFa
6010
6217
  if (activeMemorySummary !== void 0 && activeMemorySummary.length > 0) {
6011
6218
  assemblyCtx.activeMemorySummary = activeMemorySummary;
6012
6219
  }
6220
+ if (reasoningActive(inputs.options.reasoning, inputs.model)) {
6221
+ assemblyCtx.reasoning = true;
6222
+ }
6013
6223
  if (inputs.context !== void 0) {
6014
6224
  await inputs.context.applyScope(contextPaths);
6015
6225
  const internal = inputs.context.internalAssemblySnapshot();
@@ -6031,6 +6241,7 @@ async function assembleSystemPromptForSend(inputs, userText, baseSystemPrompt, m
6031
6241
  }
6032
6242
  var init_local_assembly = __esm({
6033
6243
  "src/internal/runtime/system-prompt/local-assembly.ts"() {
6244
+ init_native_reasoning();
6034
6245
  init_skills_manager();
6035
6246
  }
6036
6247
  });
@@ -6166,6 +6377,21 @@ ${lines.join("\n")}
6166
6377
  }
6167
6378
  });
6168
6379
 
6380
+ // src/internal/runtime/system-prompt/sources/reasoning-provider.ts
6381
+ var ReasoningPromptProvider;
6382
+ var init_reasoning_provider = __esm({
6383
+ "src/internal/runtime/system-prompt/sources/reasoning-provider.ts"() {
6384
+ init_native_reasoning();
6385
+ ReasoningPromptProvider = class {
6386
+ id = "reasoning";
6387
+ priority = 1;
6388
+ contribute(ctx) {
6389
+ return Promise.resolve(ctx.reasoning === true ? REASONING_PREAMBLE : void 0);
6390
+ }
6391
+ };
6392
+ }
6393
+ });
6394
+
6169
6395
  // src/internal/runtime/skills/skills-block.ts
6170
6396
  function buildSkillsBlock(skills) {
6171
6397
  if (skills.length === 0) return void 0;
@@ -6208,6 +6434,7 @@ var init_pipeline = __esm({
6208
6434
  init_base_provider();
6209
6435
  init_context_provider();
6210
6436
  init_memory_provider();
6437
+ init_reasoning_provider();
6211
6438
  init_skills_provider();
6212
6439
  SystemPromptPipeline = class _SystemPromptPipeline {
6213
6440
  providers;
@@ -6247,6 +6474,7 @@ var init_pipeline = __esm({
6247
6474
  */
6248
6475
  static default() {
6249
6476
  return new _SystemPromptPipeline([
6477
+ new ReasoningPromptProvider(),
6250
6478
  new ActiveMemoryPromptProvider(),
6251
6479
  new ContextPromptProvider(),
6252
6480
  new SkillsPromptProvider(),
@@ -7743,176 +7971,17 @@ var init_local_run = __esm({
7743
7971
  };
7744
7972
  }
7745
7973
  });
7746
- function inheritSubAgentCredentials(tool, creds) {
7747
- const sink = tool[INHERIT_CREDENTIALS];
7748
- if (typeof sink === "function") sink(creds);
7749
- }
7750
- async function applyDelegationStart(spec, input, iteration) {
7751
- if (spec.onDelegationStart === void 0) return { input };
7752
- const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });
7753
- if (decision === void 0) return { input };
7754
- if (decision.proceed === false)
7755
- return { reject: decision.rejectionReason ?? "(delegation rejected)" };
7756
- return {
7757
- input: decision.modifiedInput ?? input,
7758
- ...decision.modifiedMaxSteps !== void 0 ? { maxSteps: decision.modifiedMaxSteps } : {}
7759
- };
7760
- }
7761
- async function collectChildToolResults(run) {
7762
- const lines = [];
7763
- for await (const event of run.stream()) {
7764
- if (event.type === "tool_call" && event.status === "completed") {
7765
- const rendered = typeof event.result === "string" ? event.result : JSON.stringify(event.result ?? null);
7766
- lines.push(`${event.name}: ${rendered}`);
7767
- }
7768
- }
7769
- if (lines.length === 0) return "";
7770
- return `
7771
7974
 
7772
- <subagent-tool-results>
7773
- ${lines.join("\n")}
7774
- </subagent-tool-results>`;
7775
- }
7776
- function buildChildCreateOptions(spec, inherited) {
7777
- const model = spec.model ? { id: spec.model } : inherited?.model;
7778
- return {
7779
- ...inherited?.apiKey !== void 0 ? { apiKey: inherited.apiKey } : {},
7780
- ...model !== void 0 ? { model } : {},
7781
- ...inherited?.plugins !== void 0 ? { plugins: inherited.plugins } : {},
7782
- systemPrompt: spec.instructions,
7783
- tools: spec.tools ?? []
7784
- };
7785
- }
7786
- async function runChildAgent(spec, input, signal, maxSteps, inherited) {
7787
- const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
7788
- const agent = await Agent2.create(buildChildCreateOptions(spec, inherited));
7789
- try {
7790
- const sendOptions = {
7791
- ...signal !== void 0 ? { signal } : {},
7792
- ...maxSteps !== void 0 ? { maxIterations: maxSteps } : {},
7793
- // SE3 — a delegated child's turn is initiated by the coordinating parent.
7794
- origin: { kind: "coordinator" }
7795
- };
7796
- const run = await agent.send(input, sendOptions);
7797
- const result = await run.wait();
7798
- const text = result.result ?? "(no response)";
7799
- return spec.includeToolResults === true ? text + await collectChildToolResults(run) : text;
7800
- } finally {
7801
- agent.dispose();
7802
- }
7803
- }
7804
- async function notifyDelegationError(spec, input, error, iteration) {
7805
- if (spec.onDelegationComplete === void 0) return;
7975
+ // src/types/run-events.ts
7976
+ function emitRunEvent(sink, event) {
7977
+ if (sink === void 0) return;
7806
7978
  try {
7807
- await spec.onDelegationComplete({ input, name: spec.name, error, iteration });
7979
+ sink(event);
7808
7980
  } catch {
7809
7981
  }
7810
7982
  }
7811
- function applyMessageFilter(spec, input, messages) {
7812
- if (spec.messageFilter === void 0 || messages === void 0) return input;
7813
- const filtered = spec.messageFilter({ messages, input, name: spec.name });
7814
- if (filtered.length === 0) return input;
7815
- const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join("\n");
7816
- return `Prior conversation:
7817
- ${preamble}
7818
-
7819
- Task:
7820
- ${input}`;
7821
- }
7822
- async function applyDelegationComplete(spec, input, result, iteration) {
7823
- if (spec.onDelegationComplete === void 0) return result;
7824
- const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });
7825
- return completion?.feedback !== void 0 ? result + completion.feedback : result;
7826
- }
7827
- function defineSubAgent(spec, _parentDepth = 0) {
7828
- const currentDepth = _parentDepth + 1;
7829
- const maxDepth = spec.maxDelegationDepth ?? 3;
7830
- if (currentDepth > maxDepth) {
7831
- throw new MaxDelegationDepthError(currentDepth, maxDepth);
7832
- }
7833
- const inputZod = zod.z.object({
7834
- input: zod.z.string().describe("Task for the subagent")
7835
- });
7836
- const inputSchema = {
7837
- type: "object",
7838
- properties: {
7839
- input: { type: "string", description: "Task for the subagent" }
7840
- },
7841
- required: ["input"],
7842
- additionalProperties: false
7843
- };
7844
- let iteration = 0;
7845
- let inherited;
7846
- const tool = {
7847
- name: spec.name,
7848
- description: spec.description,
7849
- inputSchema,
7850
- handler: async (rawInput, ctx) => {
7851
- const { input: parsed } = inputZod.parse(rawInput);
7852
- iteration += 1;
7853
- const capturedIteration = iteration;
7854
- const start = await applyDelegationStart(spec, parsed, capturedIteration);
7855
- if ("reject" in start) return start.reject;
7856
- const input = applyMessageFilter(spec, start.input, ctx?.messages);
7857
- let result;
7858
- try {
7859
- result = await runChildAgent(spec, input, ctx?.signal, start.maxSteps, inherited);
7860
- } catch (error) {
7861
- await notifyDelegationError(spec, input, error, capturedIteration);
7862
- throw error;
7863
- }
7864
- return applyDelegationComplete(spec, input, result, capturedIteration);
7865
- }
7866
- };
7867
- Object.defineProperty(tool, INHERIT_CREDENTIALS, {
7868
- value: ((creds) => {
7869
- inherited = creds;
7870
- }),
7871
- enumerable: false
7872
- });
7873
- return tool;
7874
- }
7875
- function subAgentToolsFromDefinitions(agents2, parentTools) {
7876
- return Object.entries(agents2).map(([name, def]) => {
7877
- const whitelist = Array.isArray(def.tools) && def.tools.length > 0 ? new Set(def.tools) : void 0;
7878
- const childTools = whitelist ? parentTools.filter((t) => whitelist.has(t.name)) : parentTools;
7879
- return defineSubAgent({
7880
- name,
7881
- description: def.description,
7882
- instructions: def.prompt,
7883
- ...def.model !== void 0 && def.model !== "inherit" ? { model: def.model.id } : {},
7884
- tools: [...childTools]
7885
- });
7886
- });
7887
- }
7888
- var INHERIT_CREDENTIALS, MaxDelegationDepthError;
7889
- var init_subagent = __esm({
7890
- "src/a2a/subagent.ts"() {
7891
- INHERIT_CREDENTIALS = /* @__PURE__ */ Symbol("theokit.subagent.inheritCredentials");
7892
- MaxDelegationDepthError = class extends Error {
7893
- constructor(currentDepth, maxDepth) {
7894
- super(`Max delegation depth ${maxDepth} exceeded (current: ${currentDepth})`);
7895
- this.currentDepth = currentDepth;
7896
- this.maxDepth = maxDepth;
7897
- this.name = "MaxDelegationDepthError";
7898
- }
7899
- currentDepth;
7900
- maxDepth;
7901
- code = "max_delegation_depth";
7902
- };
7903
- }
7904
- });
7905
-
7906
- // src/types/run-events.ts
7907
- function emitRunEvent(sink, event) {
7908
- if (sink === void 0) return;
7909
- try {
7910
- sink(event);
7911
- } catch {
7912
- }
7913
- }
7914
- var init_run_events = __esm({
7915
- "src/types/run-events.ts"() {
7983
+ var init_run_events = __esm({
7984
+ "src/types/run-events.ts"() {
7916
7985
  }
7917
7986
  });
7918
7987
 
@@ -8732,132 +8801,6 @@ var init_repair_middleware = __esm({
8732
8801
  DECIMAL_RE = /^-?\d+(\.\d+)?$/;
8733
8802
  }
8734
8803
  });
8735
- function loadJsonrepair() {
8736
- if (cachedJsonrepair === void 0) {
8737
- const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cron.cjs', document.baseURI).href)));
8738
- cachedJsonrepair = req("jsonrepair").jsonrepair;
8739
- }
8740
- return cachedJsonrepair;
8741
- }
8742
- function isPlainObject(v) {
8743
- return v !== null && typeof v === "object" && !Array.isArray(v);
8744
- }
8745
- function toFiniteNumber(raw) {
8746
- if (raw === "") return void 0;
8747
- const n = Number(raw);
8748
- return Number.isFinite(n) && String(n) === raw ? n : void 0;
8749
- }
8750
- function tryJson(raw, repair) {
8751
- const t = raw.trimStart();
8752
- if (!(t.startsWith("{") || t.startsWith("["))) return void 0;
8753
- try {
8754
- return JSON.parse(repair ? loadJsonrepair()(t) : t);
8755
- } catch {
8756
- return void 0;
8757
- }
8758
- }
8759
- function heuristicCoerce(raw, repairJson) {
8760
- if (raw === "true") return true;
8761
- if (raw === "false") return false;
8762
- if (raw === "null") return null;
8763
- const n = toFiniteNumber(raw);
8764
- if (n !== void 0) return n;
8765
- const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
8766
- return json === void 0 ? raw : json;
8767
- }
8768
- function coerceCandidates(raw, repairJson) {
8769
- const out = [];
8770
- if (raw === "true") out.push(true);
8771
- else if (raw === "false") out.push(false);
8772
- else if (raw === "null") out.push(null);
8773
- const n = toFiniteNumber(raw);
8774
- if (n !== void 0) out.push(n);
8775
- const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
8776
- if (json !== void 0) out.push(json);
8777
- out.push(raw);
8778
- return out;
8779
- }
8780
- function objectShape(schema) {
8781
- const shape = schema?.shape;
8782
- return shape !== null && typeof shape === "object" ? shape : void 0;
8783
- }
8784
- var cachedJsonrepair;
8785
- var init_coerce = __esm({
8786
- "src/sanitize/coerce.ts"() {
8787
- }
8788
- });
8789
-
8790
- // src/sanitize/sanitize-tool-input.ts
8791
- function applyTrim(key, value, ctx) {
8792
- const trimmed = value.trim();
8793
- if (trimmed !== value) ctx.notes.push(`trimmed "${key}"`);
8794
- return trimmed;
8795
- }
8796
- function applyCoerce(key, raw, ctx) {
8797
- const field = ctx.shape?.[key];
8798
- let coerced = raw;
8799
- if (field) {
8800
- for (const candidate of coerceCandidates(raw, ctx.repairJson)) {
8801
- if (field.safeParse(candidate).success) {
8802
- coerced = candidate;
8803
- break;
8804
- }
8805
- }
8806
- } else {
8807
- coerced = heuristicCoerce(raw, ctx.repairJson);
8808
- }
8809
- if (coerced !== raw) ctx.notes.push(`coerced "${key}"`);
8810
- return coerced;
8811
- }
8812
- function applyRepair(key, value, ctx) {
8813
- const repaired = tryJson(value, true);
8814
- if (repaired === void 0) return value;
8815
- ctx.notes.push(`repaired json "${key}"`);
8816
- return repaired;
8817
- }
8818
- function sanitizeString(key, value, ctx) {
8819
- let out = ctx.trim ? applyTrim(key, value, ctx) : value;
8820
- if (ctx.coerce && typeof out === "string") out = applyCoerce(key, out, ctx);
8821
- if (ctx.repairJson && !ctx.coerce && typeof out === "string") out = applyRepair(key, out, ctx);
8822
- return out;
8823
- }
8824
- function walk(input, ctx, depth) {
8825
- const out = {};
8826
- for (const [key, value] of Object.entries(input)) {
8827
- if (typeof value === "string") out[key] = sanitizeString(key, value, ctx);
8828
- else if (ctx.deep && depth < ctx.maxDepth && isPlainObject(value))
8829
- out[key] = walk(value, ctx, depth + 1);
8830
- else out[key] = value;
8831
- }
8832
- return out;
8833
- }
8834
- function sanitizeToolInput(input, options) {
8835
- if (!isPlainObject(input)) return { value: input, changed: false, notes: [] };
8836
- const ctx = {
8837
- trim: options?.trim,
8838
- coerce: options?.coerce ?? false,
8839
- repairJson: options?.repairJson ?? false,
8840
- deep: options?.deep ?? false,
8841
- maxDepth: options?.maxDepth ?? 8,
8842
- shape: objectShape(options?.schema),
8843
- notes: []
8844
- };
8845
- const value = walk(input, ctx, 0);
8846
- return { value, changed: ctx.notes.length > 0, notes: ctx.notes };
8847
- }
8848
- var init_sanitize_tool_input = __esm({
8849
- "src/sanitize/sanitize-tool-input.ts"() {
8850
- init_coerce();
8851
- }
8852
- });
8853
-
8854
- // src/define-tool.ts
8855
- var TOOL_SPLIT_RESOLVER;
8856
- var init_define_tool = __esm({
8857
- "src/define-tool.ts"() {
8858
- TOOL_SPLIT_RESOLVER = /* @__PURE__ */ Symbol("theokit.toolSplitResolver");
8859
- }
8860
- });
8861
8804
 
8862
8805
  // src/tool-error.ts
8863
8806
  function renderToolErrorMessage(content) {
@@ -13295,6 +13238,198 @@ var init_register_plugin_providers = __esm({
13295
13238
  }
13296
13239
  });
13297
13240
 
13241
+ // src/internal/runtime/local-agent/real-local-run-provider.ts
13242
+ function inferProviderFromApiKey(apiKey) {
13243
+ if (apiKey === void 0 || apiKey.length === 0) return void 0;
13244
+ const byPrefix = [
13245
+ { provider: "openrouter", prefix: "sk-or-" },
13246
+ { provider: "anthropic", prefix: "sk-ant-" },
13247
+ { provider: "openai", prefix: "sk-" }
13248
+ ];
13249
+ for (const { provider, prefix } of byPrefix) {
13250
+ if (apiKey.startsWith(prefix) && getProviderProfile(provider) !== void 0) {
13251
+ return provider;
13252
+ }
13253
+ }
13254
+ return void 0;
13255
+ }
13256
+ function detectPrimaryProvider() {
13257
+ if (process.env.ANTHROPIC_API_KEY !== void 0 && process.env.ANTHROPIC_API_KEY.length > 0) {
13258
+ return "anthropic";
13259
+ }
13260
+ if (process.env.OPENAI_API_KEY !== void 0 && process.env.OPENAI_API_KEY.length > 0) {
13261
+ return "openai";
13262
+ }
13263
+ if (process.env.OPENROUTER_API_KEY !== void 0 && process.env.OPENROUTER_API_KEY.length > 0) {
13264
+ return "openrouter";
13265
+ }
13266
+ return "openai";
13267
+ }
13268
+ var init_real_local_run_provider = __esm({
13269
+ "src/internal/runtime/local-agent/real-local-run-provider.ts"() {
13270
+ init_providers();
13271
+ }
13272
+ });
13273
+ function inheritSubAgentCredentials(tool, creds) {
13274
+ const sink = tool[INHERIT_CREDENTIALS];
13275
+ if (typeof sink === "function") sink(creds);
13276
+ }
13277
+ async function applyDelegationStart(spec, input, iteration) {
13278
+ if (spec.onDelegationStart === void 0) return { input };
13279
+ const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });
13280
+ if (decision === void 0) return { input };
13281
+ if (decision.proceed === false)
13282
+ return { reject: decision.rejectionReason ?? "(delegation rejected)" };
13283
+ return {
13284
+ input: decision.modifiedInput ?? input,
13285
+ ...decision.modifiedMaxSteps !== void 0 ? { maxSteps: decision.modifiedMaxSteps } : {}
13286
+ };
13287
+ }
13288
+ async function collectChildToolResults(run) {
13289
+ const lines = [];
13290
+ for await (const event of run.stream()) {
13291
+ if (event.type === "tool_call" && event.status === "completed") {
13292
+ const rendered = typeof event.result === "string" ? event.result : JSON.stringify(event.result ?? null);
13293
+ lines.push(`${event.name}: ${rendered}`);
13294
+ }
13295
+ }
13296
+ if (lines.length === 0) return "";
13297
+ return `
13298
+
13299
+ <subagent-tool-results>
13300
+ ${lines.join("\n")}
13301
+ </subagent-tool-results>`;
13302
+ }
13303
+ function buildChildCreateOptions(spec, inherited) {
13304
+ const model = spec.model ? { id: spec.model } : inherited?.model;
13305
+ return {
13306
+ ...inherited?.apiKey !== void 0 ? { apiKey: inherited.apiKey } : {},
13307
+ ...model !== void 0 ? { model } : {},
13308
+ ...inherited?.plugins !== void 0 ? { plugins: inherited.plugins } : {},
13309
+ systemPrompt: spec.instructions,
13310
+ tools: spec.tools ?? []
13311
+ };
13312
+ }
13313
+ async function runChildAgent(spec, input, signal, maxSteps, inherited) {
13314
+ const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
13315
+ const agent = await Agent2.create(buildChildCreateOptions(spec, inherited));
13316
+ try {
13317
+ const sendOptions = {
13318
+ ...signal !== void 0 ? { signal } : {},
13319
+ ...maxSteps !== void 0 ? { maxIterations: maxSteps } : {},
13320
+ // SE3 — a delegated child's turn is initiated by the coordinating parent.
13321
+ origin: { kind: "coordinator" }
13322
+ };
13323
+ const run = await agent.send(input, sendOptions);
13324
+ const result = await run.wait();
13325
+ const text = result.result ?? "(no response)";
13326
+ return spec.includeToolResults === true ? text + await collectChildToolResults(run) : text;
13327
+ } finally {
13328
+ agent.dispose();
13329
+ }
13330
+ }
13331
+ async function notifyDelegationError(spec, input, error, iteration) {
13332
+ if (spec.onDelegationComplete === void 0) return;
13333
+ try {
13334
+ await spec.onDelegationComplete({ input, name: spec.name, error, iteration });
13335
+ } catch {
13336
+ }
13337
+ }
13338
+ function applyMessageFilter(spec, input, messages) {
13339
+ if (spec.messageFilter === void 0 || messages === void 0) return input;
13340
+ const filtered = spec.messageFilter({ messages, input, name: spec.name });
13341
+ if (filtered.length === 0) return input;
13342
+ const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join("\n");
13343
+ return `Prior conversation:
13344
+ ${preamble}
13345
+
13346
+ Task:
13347
+ ${input}`;
13348
+ }
13349
+ async function applyDelegationComplete(spec, input, result, iteration) {
13350
+ if (spec.onDelegationComplete === void 0) return result;
13351
+ const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });
13352
+ return completion?.feedback !== void 0 ? result + completion.feedback : result;
13353
+ }
13354
+ function defineSubAgent(spec, _parentDepth = 0) {
13355
+ const currentDepth = _parentDepth + 1;
13356
+ const maxDepth = spec.maxDelegationDepth ?? 3;
13357
+ if (currentDepth > maxDepth) {
13358
+ throw new MaxDelegationDepthError(currentDepth, maxDepth);
13359
+ }
13360
+ const inputZod = zod.z.object({
13361
+ input: zod.z.string().describe("Task for the subagent")
13362
+ });
13363
+ const inputSchema = {
13364
+ type: "object",
13365
+ properties: {
13366
+ input: { type: "string", description: "Task for the subagent" }
13367
+ },
13368
+ required: ["input"],
13369
+ additionalProperties: false
13370
+ };
13371
+ let iteration = 0;
13372
+ let inherited;
13373
+ const tool = {
13374
+ name: spec.name,
13375
+ description: spec.description,
13376
+ inputSchema,
13377
+ handler: async (rawInput, ctx) => {
13378
+ const { input: parsed } = inputZod.parse(rawInput);
13379
+ iteration += 1;
13380
+ const capturedIteration = iteration;
13381
+ const start = await applyDelegationStart(spec, parsed, capturedIteration);
13382
+ if ("reject" in start) return start.reject;
13383
+ const input = applyMessageFilter(spec, start.input, ctx?.messages);
13384
+ let result;
13385
+ try {
13386
+ result = await runChildAgent(spec, input, ctx?.signal, start.maxSteps, inherited);
13387
+ } catch (error) {
13388
+ await notifyDelegationError(spec, input, error, capturedIteration);
13389
+ throw error;
13390
+ }
13391
+ return applyDelegationComplete(spec, input, result, capturedIteration);
13392
+ }
13393
+ };
13394
+ Object.defineProperty(tool, INHERIT_CREDENTIALS, {
13395
+ value: ((creds) => {
13396
+ inherited = creds;
13397
+ }),
13398
+ enumerable: false
13399
+ });
13400
+ return tool;
13401
+ }
13402
+ function subAgentToolsFromDefinitions(agents2, parentTools) {
13403
+ return Object.entries(agents2).map(([name, def]) => {
13404
+ const whitelist = Array.isArray(def.tools) && def.tools.length > 0 ? new Set(def.tools) : void 0;
13405
+ const childTools = whitelist ? parentTools.filter((t) => whitelist.has(t.name)) : parentTools;
13406
+ return defineSubAgent({
13407
+ name,
13408
+ description: def.description,
13409
+ instructions: def.prompt,
13410
+ ...def.model !== void 0 && def.model !== "inherit" ? { model: def.model.id } : {},
13411
+ tools: [...childTools]
13412
+ });
13413
+ });
13414
+ }
13415
+ var INHERIT_CREDENTIALS, MaxDelegationDepthError;
13416
+ var init_subagent = __esm({
13417
+ "src/a2a/subagent.ts"() {
13418
+ INHERIT_CREDENTIALS = /* @__PURE__ */ Symbol("theokit.subagent.inheritCredentials");
13419
+ MaxDelegationDepthError = class extends Error {
13420
+ constructor(currentDepth, maxDepth) {
13421
+ super(`Max delegation depth ${maxDepth} exceeded (current: ${currentDepth})`);
13422
+ this.currentDepth = currentDepth;
13423
+ this.maxDepth = maxDepth;
13424
+ this.name = "MaxDelegationDepthError";
13425
+ }
13426
+ currentDepth;
13427
+ maxDepth;
13428
+ code = "max_delegation_depth";
13429
+ };
13430
+ }
13431
+ });
13432
+
13298
13433
  // src/internal/tool-registry/personality-filter.ts
13299
13434
  function applyPersonalityFilter(exposedTools, whitelist, opts) {
13300
13435
  if (whitelist === void 0) return exposedTools;
@@ -13350,36 +13485,49 @@ var init_personality_filter = __esm({
13350
13485
  }
13351
13486
  });
13352
13487
 
13353
- // src/internal/runtime/local-agent/real-local-run-provider.ts
13354
- function inferProviderFromApiKey(apiKey) {
13355
- if (apiKey === void 0 || apiKey.length === 0) return void 0;
13356
- const byPrefix = [
13357
- { provider: "openrouter", prefix: "sk-or-" },
13358
- { provider: "anthropic", prefix: "sk-ant-" },
13359
- { provider: "openai", prefix: "sk-" }
13360
- ];
13361
- for (const { provider, prefix } of byPrefix) {
13362
- if (apiKey.startsWith(prefix) && getProviderProfile(provider) !== void 0) {
13363
- return provider;
13364
- }
13365
- }
13366
- return void 0;
13488
+ // src/internal/runtime/local-agent/real-local-run-tools.ts
13489
+ function declarativeSubagentTools(agents2, parentTools) {
13490
+ if (agents2 === void 0 || Object.keys(agents2).length === 0) return [];
13491
+ return subAgentToolsFromDefinitions(agents2, parentTools);
13367
13492
  }
13368
- function detectPrimaryProvider() {
13369
- if (process.env.ANTHROPIC_API_KEY !== void 0 && process.env.ANTHROPIC_API_KEY.length > 0) {
13370
- return "anthropic";
13371
- }
13372
- if (process.env.OPENAI_API_KEY !== void 0 && process.env.OPENAI_API_KEY.length > 0) {
13373
- return "openai";
13374
- }
13375
- if (process.env.OPENROUTER_API_KEY !== void 0 && process.env.OPENROUTER_API_KEY.length > 0) {
13376
- return "openrouter";
13493
+ function bindParentCredentials(tools, agentOptions) {
13494
+ const parentPlugins = Array.isArray(agentOptions.plugins) ? agentOptions.plugins : void 0;
13495
+ const credentials = {
13496
+ ...agentOptions.apiKey !== void 0 ? { apiKey: agentOptions.apiKey } : {},
13497
+ ...typeof agentOptions.model === "object" ? { model: agentOptions.model } : {},
13498
+ ...parentPlugins !== void 0 ? { plugins: parentPlugins } : {}
13499
+ };
13500
+ for (const tool of tools) inheritSubAgentCredentials(tool, credentials);
13501
+ }
13502
+ function buildCustomToolsInput(agentOptions, sendOptions, pluginManager, personalityToolWhitelist, agentId, personalityName, subagents, effectiveModel) {
13503
+ const baseTools = sendOptions?.tools ?? agentOptions.tools ?? [];
13504
+ const agentsForTools = subagents !== void 0 && Object.keys(subagents).length > 0 ? subagents : agentOptions.agents;
13505
+ const subagentTools = declarativeSubagentTools(agentsForTools, baseTools);
13506
+ const pluginTools = pluginManager?.aggregated.tools ?? [];
13507
+ const reasoningTools = reasoningActive(agentOptions.reasoning, effectiveModel) ? [createThinkTool()] : [];
13508
+ if (baseTools.length === 0 && subagentTools.length === 0 && pluginTools.length === 0 && reasoningTools.length === 0) {
13509
+ return {};
13377
13510
  }
13378
- return "openai";
13511
+ const allTools = [...baseTools, ...subagentTools, ...pluginTools, ...reasoningTools];
13512
+ bindParentCredentials(allTools, agentOptions);
13513
+ const merged = allTools.map((tool) => ({
13514
+ name: tool.name,
13515
+ description: tool.description,
13516
+ inputSchema: tool.inputSchema,
13517
+ handler: tool.handler
13518
+ }));
13519
+ const customTools = applyPersonalityFilter(merged, personalityToolWhitelist, {
13520
+ agentId,
13521
+ personalityName
13522
+ });
13523
+ if (customTools.length === 0 && personalityToolWhitelist === void 0) return {};
13524
+ return { customTools };
13379
13525
  }
13380
- var init_real_local_run_provider = __esm({
13381
- "src/internal/runtime/local-agent/real-local-run-provider.ts"() {
13382
- init_providers();
13526
+ var init_real_local_run_tools = __esm({
13527
+ "src/internal/runtime/local-agent/real-local-run-tools.ts"() {
13528
+ init_subagent();
13529
+ init_personality_filter();
13530
+ init_native_reasoning();
13383
13531
  }
13384
13532
  });
13385
13533
 
@@ -13498,7 +13646,8 @@ function buildLoopInputs(options, runId, userText) {
13498
13646
  options.personalityToolWhitelist,
13499
13647
  options.agentId,
13500
13648
  options.personalityName,
13501
- options.subagents
13649
+ options.subagents,
13650
+ options.model
13502
13651
  ),
13503
13652
  ...options.pluginManager !== void 0 ? { pluginManager: options.pluginManager } : {},
13504
13653
  // D318 — forward SendOptions.signal to the agent loop so streamLlmTurn
@@ -13536,40 +13685,6 @@ function buildLoopInputs(options, runId, userText) {
13536
13685
  ...options.agentOptions.memoryProvider !== void 0 ? { memoryProvider: options.agentOptions.memoryProvider } : {}
13537
13686
  };
13538
13687
  }
13539
- function declarativeSubagentTools(agents2, parentTools) {
13540
- if (agents2 === void 0 || Object.keys(agents2).length === 0) return [];
13541
- return subAgentToolsFromDefinitions(agents2, parentTools);
13542
- }
13543
- function bindParentCredentials(tools, agentOptions) {
13544
- const parentPlugins = Array.isArray(agentOptions.plugins) ? agentOptions.plugins : void 0;
13545
- const credentials = {
13546
- ...agentOptions.apiKey !== void 0 ? { apiKey: agentOptions.apiKey } : {},
13547
- ...typeof agentOptions.model === "object" ? { model: agentOptions.model } : {},
13548
- ...parentPlugins !== void 0 ? { plugins: parentPlugins } : {}
13549
- };
13550
- for (const tool of tools) inheritSubAgentCredentials(tool, credentials);
13551
- }
13552
- function buildCustomToolsInput(agentOptions, sendOptions, pluginManager, personalityToolWhitelist, agentId, personalityName, subagents) {
13553
- const baseTools = sendOptions?.tools ?? agentOptions.tools ?? [];
13554
- const agentsForTools = subagents !== void 0 && Object.keys(subagents).length > 0 ? subagents : agentOptions.agents;
13555
- const subagentTools = declarativeSubagentTools(agentsForTools, baseTools);
13556
- const pluginTools = pluginManager?.aggregated.tools ?? [];
13557
- if (baseTools.length === 0 && subagentTools.length === 0 && pluginTools.length === 0) return {};
13558
- const allTools = [...baseTools, ...subagentTools, ...pluginTools];
13559
- bindParentCredentials(allTools, agentOptions);
13560
- const merged = allTools.map((tool) => ({
13561
- name: tool.name,
13562
- description: tool.description,
13563
- inputSchema: tool.inputSchema,
13564
- handler: tool.handler
13565
- }));
13566
- const customTools = applyPersonalityFilter(merged, personalityToolWhitelist, {
13567
- agentId,
13568
- personalityName
13569
- });
13570
- if (customTools.length === 0 && personalityToolWhitelist === void 0) return {};
13571
- return { customTools };
13572
- }
13573
13688
  function buildMcpMap(options) {
13574
13689
  const map = /* @__PURE__ */ new Map();
13575
13690
  const inline = options.sendOptions.mcpServers ?? options.agentOptions.mcpServers;
@@ -13582,7 +13697,6 @@ function buildMcpMap(options) {
13582
13697
  var pluginProvidersAnnounced, RealLocalRun;
13583
13698
  var init_real_local_run = __esm({
13584
13699
  "src/internal/runtime/local-agent/real-local-run.ts"() {
13585
- init_subagent();
13586
13700
  init_errors();
13587
13701
  init_run_events();
13588
13702
  init_loop();
@@ -13595,11 +13709,11 @@ var init_real_local_run = __esm({
13595
13709
  init_providers();
13596
13710
  init_register_plugin_providers();
13597
13711
  init_tracer();
13598
- init_personality_filter();
13599
13712
  init_async_local_storage();
13600
13713
  init_fixture_run_base();
13601
13714
  init_run_registry();
13602
13715
  init_real_local_run_provider();
13716
+ init_real_local_run_tools();
13603
13717
  pluginProvidersAnnounced = false;
13604
13718
  RealLocalRun = class extends FixtureRunBase {
13605
13719
  buildInputs;