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