@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/index.cjs CHANGED
@@ -976,10 +976,10 @@ function buildToolPrompt(prompt) {
976
976
  Respond by calling the \`output\` tool with the structured answer that matches the schema.`;
977
977
  }
978
978
  function setupStructuredOutput(schema, maxRetries) {
979
- const z10 = requireZod();
979
+ const z11 = requireZod();
980
980
  const jsonSchema = toJsonSchema(schema, { unrepresentable: "any" });
981
981
  return {
982
- z: z10,
982
+ z: z11,
983
983
  jsonSchema,
984
984
  maxRetries: maxRetries ?? 1,
985
985
  initialUsage: { inputTokens: 0, outputTokens: 0 }
@@ -5769,6 +5769,213 @@ var init_subagents_loader = __esm({
5769
5769
  init_yaml_frontmatter();
5770
5770
  }
5771
5771
  });
5772
+ function loadJsonrepair() {
5773
+ if (cachedJsonrepair === void 0) {
5774
+ const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
5775
+ cachedJsonrepair = req("jsonrepair").jsonrepair;
5776
+ }
5777
+ return cachedJsonrepair;
5778
+ }
5779
+ function isPlainObject(v) {
5780
+ return v !== null && typeof v === "object" && !Array.isArray(v);
5781
+ }
5782
+ function toFiniteNumber(raw) {
5783
+ if (raw === "") return void 0;
5784
+ const n = Number(raw);
5785
+ return Number.isFinite(n) && String(n) === raw ? n : void 0;
5786
+ }
5787
+ function tryJson(raw, repair) {
5788
+ const t = raw.trimStart();
5789
+ if (!(t.startsWith("{") || t.startsWith("["))) return void 0;
5790
+ try {
5791
+ return JSON.parse(repair ? loadJsonrepair()(t) : t);
5792
+ } catch {
5793
+ return void 0;
5794
+ }
5795
+ }
5796
+ function heuristicCoerce(raw, repairJson) {
5797
+ if (raw === "true") return true;
5798
+ if (raw === "false") return false;
5799
+ if (raw === "null") return null;
5800
+ const n = toFiniteNumber(raw);
5801
+ if (n !== void 0) return n;
5802
+ const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
5803
+ return json === void 0 ? raw : json;
5804
+ }
5805
+ function coerceCandidates(raw, repairJson) {
5806
+ const out = [];
5807
+ if (raw === "true") out.push(true);
5808
+ else if (raw === "false") out.push(false);
5809
+ else if (raw === "null") out.push(null);
5810
+ const n = toFiniteNumber(raw);
5811
+ if (n !== void 0) out.push(n);
5812
+ const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
5813
+ if (json !== void 0) out.push(json);
5814
+ out.push(raw);
5815
+ return out;
5816
+ }
5817
+ function objectShape(schema) {
5818
+ const shape = schema?.shape;
5819
+ return shape !== null && typeof shape === "object" ? shape : void 0;
5820
+ }
5821
+ var cachedJsonrepair;
5822
+ var init_coerce = __esm({
5823
+ "src/sanitize/coerce.ts"() {
5824
+ }
5825
+ });
5826
+
5827
+ // src/sanitize/sanitize-tool-input.ts
5828
+ function applyTrim(key2, value, ctx) {
5829
+ const trimmed = value.trim();
5830
+ if (trimmed !== value) ctx.notes.push(`trimmed "${key2}"`);
5831
+ return trimmed;
5832
+ }
5833
+ function applyCoerce(key2, raw, ctx) {
5834
+ const field = ctx.shape?.[key2];
5835
+ let coerced = raw;
5836
+ if (field) {
5837
+ for (const candidate of coerceCandidates(raw, ctx.repairJson)) {
5838
+ if (field.safeParse(candidate).success) {
5839
+ coerced = candidate;
5840
+ break;
5841
+ }
5842
+ }
5843
+ } else {
5844
+ coerced = heuristicCoerce(raw, ctx.repairJson);
5845
+ }
5846
+ if (coerced !== raw) ctx.notes.push(`coerced "${key2}"`);
5847
+ return coerced;
5848
+ }
5849
+ function applyRepair(key2, value, ctx) {
5850
+ const repaired = tryJson(value, true);
5851
+ if (repaired === void 0) return value;
5852
+ ctx.notes.push(`repaired json "${key2}"`);
5853
+ return repaired;
5854
+ }
5855
+ function sanitizeString(key2, value, ctx) {
5856
+ let out = ctx.trim ? applyTrim(key2, value, ctx) : value;
5857
+ if (ctx.coerce && typeof out === "string") out = applyCoerce(key2, out, ctx);
5858
+ if (ctx.repairJson && !ctx.coerce && typeof out === "string") out = applyRepair(key2, out, ctx);
5859
+ return out;
5860
+ }
5861
+ function walk(input, ctx, depth) {
5862
+ const out = {};
5863
+ for (const [key2, value] of Object.entries(input)) {
5864
+ if (typeof value === "string") out[key2] = sanitizeString(key2, value, ctx);
5865
+ else if (ctx.deep && depth < ctx.maxDepth && isPlainObject(value))
5866
+ out[key2] = walk(value, ctx, depth + 1);
5867
+ else out[key2] = value;
5868
+ }
5869
+ return out;
5870
+ }
5871
+ function sanitizeToolInput(input, options) {
5872
+ if (!isPlainObject(input)) return { value: input, changed: false, notes: [] };
5873
+ const ctx = {
5874
+ trim: options?.trim ?? true,
5875
+ coerce: options?.coerce ?? false,
5876
+ repairJson: options?.repairJson ?? false,
5877
+ deep: options?.deep ?? false,
5878
+ maxDepth: options?.maxDepth ?? 8,
5879
+ shape: objectShape(options?.schema),
5880
+ notes: []
5881
+ };
5882
+ const value = walk(input, ctx, 0);
5883
+ return { value, changed: ctx.notes.length > 0, notes: ctx.notes };
5884
+ }
5885
+ var init_sanitize_tool_input = __esm({
5886
+ "src/sanitize/sanitize-tool-input.ts"() {
5887
+ init_coerce();
5888
+ }
5889
+ });
5890
+
5891
+ // src/define-tool.ts
5892
+ async function runValidated(spec, input, ctx) {
5893
+ const raw = spec.sanitize ? sanitizeToolInput(input, {
5894
+ ...spec.sanitize === true ? {} : spec.sanitize,
5895
+ schema: spec.inputSchema
5896
+ }).value : input;
5897
+ const parsed = spec.inputSchema.parse(raw);
5898
+ const out = await spec.handler(parsed, ctx);
5899
+ return spec.outputSchema === void 0 ? out : spec.outputSchema.parse(out);
5900
+ }
5901
+ function serializeOutput(validated) {
5902
+ return typeof validated === "string" ? validated : JSON.stringify(validated);
5903
+ }
5904
+ function shapeModelOutput(spec, validated) {
5905
+ if (spec.toModelOutput !== void 0) return spec.toModelOutput(validated);
5906
+ return serializeOutput(validated);
5907
+ }
5908
+ function defineTool(spec) {
5909
+ const inputSchema = toJsonSchema(spec.inputSchema, {
5910
+ unrepresentable: "any"
5911
+ });
5912
+ const handler = async (input, ctx) => {
5913
+ const validated = await runValidated(spec, input, ctx);
5914
+ return shapeModelOutput(spec, validated);
5915
+ };
5916
+ const tool = { name: spec.name, description: spec.description, inputSchema, handler };
5917
+ if (spec.toModelOutput !== void 0) {
5918
+ const resolver = async (input, ctx) => {
5919
+ const validated = await runValidated(spec, input, ctx);
5920
+ return { model: shapeModelOutput(spec, validated), app: serializeOutput(validated) };
5921
+ };
5922
+ handler[TOOL_SPLIT_RESOLVER] = resolver;
5923
+ }
5924
+ return tool;
5925
+ }
5926
+ var TOOL_SPLIT_RESOLVER; exports.Tool = void 0;
5927
+ var init_define_tool = __esm({
5928
+ "src/define-tool.ts"() {
5929
+ init_to_json_schema();
5930
+ init_sanitize_tool_input();
5931
+ TOOL_SPLIT_RESOLVER = /* @__PURE__ */ Symbol("theokit.toolSplitResolver");
5932
+ exports.Tool = class {
5933
+ constructor() {
5934
+ }
5935
+ static create(spec) {
5936
+ return defineTool(spec);
5937
+ }
5938
+ };
5939
+ }
5940
+ });
5941
+ function createThinkTool() {
5942
+ return exports.Tool.create({
5943
+ name: "think",
5944
+ description: "Scratchpad: reason through ONE step before answering. No side effects \u2014 your private reasoning space. Call it repeatedly before the final answer.",
5945
+ inputSchema: zod.z.object({ thought: zod.z.string().min(1, "think: `thought` must be non-empty.") }),
5946
+ handler: ({ thought }) => thought
5947
+ });
5948
+ }
5949
+ function isNativeReasoning(model) {
5950
+ if (model === void 0 || typeof model === "string") return false;
5951
+ const params = model.params;
5952
+ if (params === void 0) return false;
5953
+ return params.some((p) => NATIVE_REASONING_PARAM_IDS.has(p.id));
5954
+ }
5955
+ function warnDoubleReasoningOnce() {
5956
+ if (warned2.has("double-reasoning")) return;
5957
+ warned2.add("double-reasoning");
5958
+ process.stderr.write(
5959
+ "[theokit-sdk] `reasoning: true` skipped \u2014 a native reasoning model is configured (model.params thinking/reasoning); native reasoning wins. Remove one to silence.\n"
5960
+ );
5961
+ }
5962
+ function reasoningActive(reasoning, model) {
5963
+ if (reasoning !== true) return false;
5964
+ if (isNativeReasoning(model)) {
5965
+ warnDoubleReasoningOnce();
5966
+ return false;
5967
+ }
5968
+ return true;
5969
+ }
5970
+ var NATIVE_REASONING_PARAM_IDS, REASONING_PREAMBLE, warned2;
5971
+ var init_native_reasoning = __esm({
5972
+ "src/internal/runtime/reasoning/native-reasoning.ts"() {
5973
+ init_define_tool();
5974
+ NATIVE_REASONING_PARAM_IDS = /* @__PURE__ */ new Set(["thinking", "reasoning", "reasoning_effort"]);
5975
+ 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.";
5976
+ warned2 = /* @__PURE__ */ new Set();
5977
+ }
5978
+ });
5772
5979
 
5773
5980
  // src/internal/runtime/skills/skill-frontmatter.ts
5774
5981
  function asString(v) {
@@ -6020,6 +6227,9 @@ async function buildAssemblyContext(inputs, userText, baseSystemPrompt, memoryFa
6020
6227
  if (activeMemorySummary !== void 0 && activeMemorySummary.length > 0) {
6021
6228
  assemblyCtx.activeMemorySummary = activeMemorySummary;
6022
6229
  }
6230
+ if (reasoningActive(inputs.options.reasoning, inputs.model)) {
6231
+ assemblyCtx.reasoning = true;
6232
+ }
6023
6233
  if (inputs.context !== void 0) {
6024
6234
  await inputs.context.applyScope(contextPaths);
6025
6235
  const internal = inputs.context.internalAssemblySnapshot();
@@ -6041,6 +6251,7 @@ async function assembleSystemPromptForSend(inputs, userText, baseSystemPrompt, m
6041
6251
  }
6042
6252
  var init_local_assembly = __esm({
6043
6253
  "src/internal/runtime/system-prompt/local-assembly.ts"() {
6254
+ init_native_reasoning();
6044
6255
  init_skills_manager();
6045
6256
  }
6046
6257
  });
@@ -6176,6 +6387,21 @@ ${lines.join("\n")}
6176
6387
  }
6177
6388
  });
6178
6389
 
6390
+ // src/internal/runtime/system-prompt/sources/reasoning-provider.ts
6391
+ var ReasoningPromptProvider;
6392
+ var init_reasoning_provider = __esm({
6393
+ "src/internal/runtime/system-prompt/sources/reasoning-provider.ts"() {
6394
+ init_native_reasoning();
6395
+ ReasoningPromptProvider = class {
6396
+ id = "reasoning";
6397
+ priority = 1;
6398
+ contribute(ctx) {
6399
+ return Promise.resolve(ctx.reasoning === true ? REASONING_PREAMBLE : void 0);
6400
+ }
6401
+ };
6402
+ }
6403
+ });
6404
+
6179
6405
  // src/internal/runtime/skills/skills-block.ts
6180
6406
  function buildSkillsBlock(skills) {
6181
6407
  if (skills.length === 0) return void 0;
@@ -6218,6 +6444,7 @@ var init_pipeline = __esm({
6218
6444
  init_base_provider();
6219
6445
  init_context_provider();
6220
6446
  init_memory_provider();
6447
+ init_reasoning_provider();
6221
6448
  init_skills_provider();
6222
6449
  SystemPromptPipeline = class _SystemPromptPipeline {
6223
6450
  providers;
@@ -6257,6 +6484,7 @@ var init_pipeline = __esm({
6257
6484
  */
6258
6485
  static default() {
6259
6486
  return new _SystemPromptPipeline([
6487
+ new ReasoningPromptProvider(),
6260
6488
  new ActiveMemoryPromptProvider(),
6261
6489
  new ContextPromptProvider(),
6262
6490
  new SkillsPromptProvider(),
@@ -7753,171 +7981,12 @@ var init_local_run = __esm({
7753
7981
  };
7754
7982
  }
7755
7983
  });
7756
- function inheritSubAgentCredentials(tool, creds) {
7757
- const sink = tool[INHERIT_CREDENTIALS];
7758
- if (typeof sink === "function") sink(creds);
7759
- }
7760
- async function applyDelegationStart(spec, input, iteration) {
7761
- if (spec.onDelegationStart === void 0) return { input };
7762
- const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });
7763
- if (decision === void 0) return { input };
7764
- if (decision.proceed === false)
7765
- return { reject: decision.rejectionReason ?? "(delegation rejected)" };
7766
- return {
7767
- input: decision.modifiedInput ?? input,
7768
- ...decision.modifiedMaxSteps !== void 0 ? { maxSteps: decision.modifiedMaxSteps } : {}
7769
- };
7770
- }
7771
- async function collectChildToolResults(run) {
7772
- const lines = [];
7773
- for await (const event of run.stream()) {
7774
- if (event.type === "tool_call" && event.status === "completed") {
7775
- const rendered = typeof event.result === "string" ? event.result : JSON.stringify(event.result ?? null);
7776
- lines.push(`${event.name}: ${rendered}`);
7777
- }
7778
- }
7779
- if (lines.length === 0) return "";
7780
- return `
7781
7984
 
7782
- <subagent-tool-results>
7783
- ${lines.join("\n")}
7784
- </subagent-tool-results>`;
7785
- }
7786
- function buildChildCreateOptions(spec, inherited) {
7787
- const model = spec.model ? { id: spec.model } : inherited?.model;
7788
- return {
7789
- ...inherited?.apiKey !== void 0 ? { apiKey: inherited.apiKey } : {},
7790
- ...model !== void 0 ? { model } : {},
7791
- ...inherited?.plugins !== void 0 ? { plugins: inherited.plugins } : {},
7792
- systemPrompt: spec.instructions,
7793
- tools: spec.tools ?? []
7794
- };
7795
- }
7796
- async function runChildAgent(spec, input, signal, maxSteps, inherited) {
7797
- const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
7798
- const agent = await Agent2.create(buildChildCreateOptions(spec, inherited));
7799
- try {
7800
- const sendOptions = {
7801
- ...signal !== void 0 ? { signal } : {},
7802
- ...maxSteps !== void 0 ? { maxIterations: maxSteps } : {},
7803
- // SE3 — a delegated child's turn is initiated by the coordinating parent.
7804
- origin: { kind: "coordinator" }
7805
- };
7806
- const run = await agent.send(input, sendOptions);
7807
- const result = await run.wait();
7808
- const text = result.result ?? "(no response)";
7809
- return spec.includeToolResults === true ? text + await collectChildToolResults(run) : text;
7810
- } finally {
7811
- agent.dispose();
7812
- }
7813
- }
7814
- async function notifyDelegationError(spec, input, error, iteration) {
7815
- if (spec.onDelegationComplete === void 0) return;
7985
+ // src/types/run-events.ts
7986
+ function emitRunEvent(sink, event) {
7987
+ if (sink === void 0) return;
7816
7988
  try {
7817
- await spec.onDelegationComplete({ input, name: spec.name, error, iteration });
7818
- } catch {
7819
- }
7820
- }
7821
- function applyMessageFilter(spec, input, messages) {
7822
- if (spec.messageFilter === void 0 || messages === void 0) return input;
7823
- const filtered = spec.messageFilter({ messages, input, name: spec.name });
7824
- if (filtered.length === 0) return input;
7825
- const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join("\n");
7826
- return `Prior conversation:
7827
- ${preamble}
7828
-
7829
- Task:
7830
- ${input}`;
7831
- }
7832
- async function applyDelegationComplete(spec, input, result, iteration) {
7833
- if (spec.onDelegationComplete === void 0) return result;
7834
- const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });
7835
- return completion?.feedback !== void 0 ? result + completion.feedback : result;
7836
- }
7837
- function defineSubAgent(spec, _parentDepth = 0) {
7838
- const currentDepth = _parentDepth + 1;
7839
- const maxDepth = spec.maxDelegationDepth ?? 3;
7840
- if (currentDepth > maxDepth) {
7841
- throw new MaxDelegationDepthError(currentDepth, maxDepth);
7842
- }
7843
- const inputZod = zod.z.object({
7844
- input: zod.z.string().describe("Task for the subagent")
7845
- });
7846
- const inputSchema = {
7847
- type: "object",
7848
- properties: {
7849
- input: { type: "string", description: "Task for the subagent" }
7850
- },
7851
- required: ["input"],
7852
- additionalProperties: false
7853
- };
7854
- let iteration = 0;
7855
- let inherited;
7856
- const tool = {
7857
- name: spec.name,
7858
- description: spec.description,
7859
- inputSchema,
7860
- handler: async (rawInput, ctx) => {
7861
- const { input: parsed } = inputZod.parse(rawInput);
7862
- iteration += 1;
7863
- const capturedIteration = iteration;
7864
- const start = await applyDelegationStart(spec, parsed, capturedIteration);
7865
- if ("reject" in start) return start.reject;
7866
- const input = applyMessageFilter(spec, start.input, ctx?.messages);
7867
- let result;
7868
- try {
7869
- result = await runChildAgent(spec, input, ctx?.signal, start.maxSteps, inherited);
7870
- } catch (error) {
7871
- await notifyDelegationError(spec, input, error, capturedIteration);
7872
- throw error;
7873
- }
7874
- return applyDelegationComplete(spec, input, result, capturedIteration);
7875
- }
7876
- };
7877
- Object.defineProperty(tool, INHERIT_CREDENTIALS, {
7878
- value: ((creds) => {
7879
- inherited = creds;
7880
- }),
7881
- enumerable: false
7882
- });
7883
- return tool;
7884
- }
7885
- function subAgentToolsFromDefinitions(agents2, parentTools) {
7886
- return Object.entries(agents2).map(([name, def]) => {
7887
- const whitelist = Array.isArray(def.tools) && def.tools.length > 0 ? new Set(def.tools) : void 0;
7888
- const childTools = whitelist ? parentTools.filter((t) => whitelist.has(t.name)) : parentTools;
7889
- return defineSubAgent({
7890
- name,
7891
- description: def.description,
7892
- instructions: def.prompt,
7893
- ...def.model !== void 0 && def.model !== "inherit" ? { model: def.model.id } : {},
7894
- tools: [...childTools]
7895
- });
7896
- });
7897
- }
7898
- var INHERIT_CREDENTIALS, MaxDelegationDepthError;
7899
- var init_subagent = __esm({
7900
- "src/a2a/subagent.ts"() {
7901
- INHERIT_CREDENTIALS = /* @__PURE__ */ Symbol("theokit.subagent.inheritCredentials");
7902
- MaxDelegationDepthError = class extends Error {
7903
- constructor(currentDepth, maxDepth) {
7904
- super(`Max delegation depth ${maxDepth} exceeded (current: ${currentDepth})`);
7905
- this.currentDepth = currentDepth;
7906
- this.maxDepth = maxDepth;
7907
- this.name = "MaxDelegationDepthError";
7908
- }
7909
- currentDepth;
7910
- maxDepth;
7911
- code = "max_delegation_depth";
7912
- };
7913
- }
7914
- });
7915
-
7916
- // src/types/run-events.ts
7917
- function emitRunEvent(sink, event) {
7918
- if (sink === void 0) return;
7919
- try {
7920
- sink(event);
7989
+ sink(event);
7921
7990
  } catch {
7922
7991
  }
7923
7992
  }
@@ -8742,253 +8811,84 @@ var init_repair_middleware = __esm({
8742
8811
  DECIMAL_RE = /^-?\d+(\.\d+)?$/;
8743
8812
  }
8744
8813
  });
8745
- function loadJsonrepair() {
8746
- if (cachedJsonrepair === void 0) {
8747
- const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
8748
- cachedJsonrepair = req("jsonrepair").jsonrepair;
8749
- }
8750
- return cachedJsonrepair;
8751
- }
8752
- function isPlainObject(v) {
8753
- return v !== null && typeof v === "object" && !Array.isArray(v);
8754
- }
8755
- function toFiniteNumber(raw) {
8756
- if (raw === "") return void 0;
8757
- const n = Number(raw);
8758
- return Number.isFinite(n) && String(n) === raw ? n : void 0;
8814
+
8815
+ // src/tool-error.ts
8816
+ function renderToolErrorMessage(content) {
8817
+ if (typeof content === "string") return content;
8818
+ return content.map((block) => block.type === "text" ? block.text : `[${block.source.media_type} image]`).join("\n");
8759
8819
  }
8760
- function tryJson(raw, repair) {
8761
- const t = raw.trimStart();
8762
- if (!(t.startsWith("{") || t.startsWith("["))) return void 0;
8763
- try {
8764
- return JSON.parse(repair ? loadJsonrepair()(t) : t);
8765
- } catch {
8766
- return void 0;
8820
+ exports.ToolError = void 0;
8821
+ var init_tool_error = __esm({
8822
+ "src/tool-error.ts"() {
8823
+ init_errors();
8824
+ exports.ToolError = class extends exports.TheokitAgentError {
8825
+ name = "ToolError";
8826
+ /** The error content surfaced to the model: a string, or text/image blocks. */
8827
+ content;
8828
+ constructor(content, options = {}) {
8829
+ super(renderToolErrorMessage(content), { ...options, isRetryable: false });
8830
+ this.content = content;
8831
+ }
8832
+ };
8767
8833
  }
8834
+ });
8835
+
8836
+ // src/internal/runtime/tools/shell-tool.ts
8837
+ async function runShell(options) {
8838
+ if (options.sandbox === true && isObviouslyUnsafe(options.command)) {
8839
+ return {
8840
+ stdout: "",
8841
+ stderr: `Sandbox refused command: ${options.command}`,
8842
+ exitCode: 126,
8843
+ timedOut: false
8844
+ };
8845
+ }
8846
+ const result = await spawnAndCollect({
8847
+ command: "sh",
8848
+ args: ["-c", options.command],
8849
+ cwd: options.cwd,
8850
+ ...options.env !== void 0 ? { env: options.env } : {},
8851
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
8852
+ });
8853
+ const stderr = result.spawnError !== void 0 ? result.stderr + result.spawnError.message : result.stderr;
8854
+ return {
8855
+ stdout: result.stdout,
8856
+ stderr,
8857
+ exitCode: result.exitCode,
8858
+ timedOut: result.timedOut
8859
+ };
8768
8860
  }
8769
- function heuristicCoerce(raw, repairJson) {
8770
- if (raw === "true") return true;
8771
- if (raw === "false") return false;
8772
- if (raw === "null") return null;
8773
- const n = toFiniteNumber(raw);
8774
- if (n !== void 0) return n;
8775
- const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
8776
- return json === void 0 ? raw : json;
8777
- }
8778
- function coerceCandidates(raw, repairJson) {
8779
- const out = [];
8780
- if (raw === "true") out.push(true);
8781
- else if (raw === "false") out.push(false);
8782
- else if (raw === "null") out.push(null);
8783
- const n = toFiniteNumber(raw);
8784
- if (n !== void 0) out.push(n);
8785
- const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
8786
- if (json !== void 0) out.push(json);
8787
- out.push(raw);
8788
- return out;
8789
- }
8790
- function objectShape(schema) {
8791
- const shape = schema?.shape;
8792
- return shape !== null && typeof shape === "object" ? shape : void 0;
8861
+ function isObviouslyUnsafe(command) {
8862
+ if (/(^|\s)(rm|mv|cp)\s+[^|;]*\s+\/(etc|var|root)\b/.test(command)) return true;
8863
+ if (/sudo\s/.test(command)) return true;
8864
+ return false;
8793
8865
  }
8794
- var cachedJsonrepair;
8795
- var init_coerce = __esm({
8796
- "src/sanitize/coerce.ts"() {
8866
+ var init_shell_tool = __esm({
8867
+ "src/internal/runtime/tools/shell-tool.ts"() {
8868
+ init_spawn_collect();
8797
8869
  }
8798
8870
  });
8799
8871
 
8800
- // src/sanitize/sanitize-tool-input.ts
8801
- function applyTrim(key2, value, ctx) {
8802
- const trimmed = value.trim();
8803
- if (trimmed !== value) ctx.notes.push(`trimmed "${key2}"`);
8804
- return trimmed;
8805
- }
8806
- function applyCoerce(key2, raw, ctx) {
8807
- const field = ctx.shape?.[key2];
8808
- let coerced = raw;
8809
- if (field) {
8810
- for (const candidate of coerceCandidates(raw, ctx.repairJson)) {
8811
- if (field.safeParse(candidate).success) {
8812
- coerced = candidate;
8813
- break;
8814
- }
8815
- }
8816
- } else {
8817
- coerced = heuristicCoerce(raw, ctx.repairJson);
8872
+ // src/internal/agent-loop/tool-executors.ts
8873
+ async function executeTool(inputs, resolved, call) {
8874
+ if (resolved === void 0) {
8875
+ return { stdout: "", stderr: `Unknown tool ${call.name}`, exitCode: 127 };
8818
8876
  }
8819
- if (coerced !== raw) ctx.notes.push(`coerced "${key2}"`);
8820
- return coerced;
8877
+ if (resolved.origin === "shell") return runShellTool(inputs, call);
8878
+ if (resolved.origin === "memory") return runMemoryTool(resolved, call, inputs.context);
8879
+ if (resolved.origin === "custom")
8880
+ return runCustomTool(resolved, call, inputs.signal, inputs.context, inputs.messages);
8881
+ return runMcpTool(inputs, resolved, call);
8821
8882
  }
8822
- function applyRepair(key2, value, ctx) {
8823
- const repaired = tryJson(value, true);
8824
- if (repaired === void 0) return value;
8825
- ctx.notes.push(`repaired json "${key2}"`);
8826
- return repaired;
8883
+ async function runMemoryTool(resolved, call, context) {
8884
+ return runHandlerTool("memory", resolved.memoryHandler, call, void 0, context);
8827
8885
  }
8828
- function sanitizeString(key2, value, ctx) {
8829
- let out = ctx.trim ? applyTrim(key2, value, ctx) : value;
8830
- if (ctx.coerce && typeof out === "string") out = applyCoerce(key2, out, ctx);
8831
- if (ctx.repairJson && !ctx.coerce && typeof out === "string") out = applyRepair(key2, out, ctx);
8832
- return out;
8886
+ async function runCustomTool(resolved, call, signal, context, messages) {
8887
+ return runHandlerTool("custom", resolved.customHandler, call, signal, context, messages);
8833
8888
  }
8834
- function walk(input, ctx, depth) {
8835
- const out = {};
8836
- for (const [key2, value] of Object.entries(input)) {
8837
- if (typeof value === "string") out[key2] = sanitizeString(key2, value, ctx);
8838
- else if (ctx.deep && depth < ctx.maxDepth && isPlainObject(value))
8839
- out[key2] = walk(value, ctx, depth + 1);
8840
- else out[key2] = value;
8841
- }
8842
- return out;
8843
- }
8844
- function sanitizeToolInput(input, options) {
8845
- if (!isPlainObject(input)) return { value: input, changed: false, notes: [] };
8846
- const ctx = {
8847
- trim: options?.trim ?? true,
8848
- coerce: options?.coerce ?? false,
8849
- repairJson: options?.repairJson ?? false,
8850
- deep: options?.deep ?? false,
8851
- maxDepth: options?.maxDepth ?? 8,
8852
- shape: objectShape(options?.schema),
8853
- notes: []
8854
- };
8855
- const value = walk(input, ctx, 0);
8856
- return { value, changed: ctx.notes.length > 0, notes: ctx.notes };
8857
- }
8858
- var init_sanitize_tool_input = __esm({
8859
- "src/sanitize/sanitize-tool-input.ts"() {
8860
- init_coerce();
8861
- }
8862
- });
8863
-
8864
- // src/define-tool.ts
8865
- async function runValidated(spec, input, ctx) {
8866
- const raw = spec.sanitize ? sanitizeToolInput(input, {
8867
- ...spec.sanitize === true ? {} : spec.sanitize,
8868
- schema: spec.inputSchema
8869
- }).value : input;
8870
- const parsed = spec.inputSchema.parse(raw);
8871
- const out = await spec.handler(parsed, ctx);
8872
- return spec.outputSchema === void 0 ? out : spec.outputSchema.parse(out);
8873
- }
8874
- function serializeOutput(validated) {
8875
- return typeof validated === "string" ? validated : JSON.stringify(validated);
8876
- }
8877
- function shapeModelOutput(spec, validated) {
8878
- if (spec.toModelOutput !== void 0) return spec.toModelOutput(validated);
8879
- return serializeOutput(validated);
8880
- }
8881
- function defineTool(spec) {
8882
- const inputSchema = toJsonSchema(spec.inputSchema, {
8883
- unrepresentable: "any"
8884
- });
8885
- const handler = async (input, ctx) => {
8886
- const validated = await runValidated(spec, input, ctx);
8887
- return shapeModelOutput(spec, validated);
8888
- };
8889
- const tool = { name: spec.name, description: spec.description, inputSchema, handler };
8890
- if (spec.toModelOutput !== void 0) {
8891
- const resolver = async (input, ctx) => {
8892
- const validated = await runValidated(spec, input, ctx);
8893
- return { model: shapeModelOutput(spec, validated), app: serializeOutput(validated) };
8894
- };
8895
- handler[TOOL_SPLIT_RESOLVER] = resolver;
8896
- }
8897
- return tool;
8898
- }
8899
- var TOOL_SPLIT_RESOLVER; exports.Tool = void 0;
8900
- var init_define_tool = __esm({
8901
- "src/define-tool.ts"() {
8902
- init_to_json_schema();
8903
- init_sanitize_tool_input();
8904
- TOOL_SPLIT_RESOLVER = /* @__PURE__ */ Symbol("theokit.toolSplitResolver");
8905
- exports.Tool = class {
8906
- constructor() {
8907
- }
8908
- static create(spec) {
8909
- return defineTool(spec);
8910
- }
8911
- };
8912
- }
8913
- });
8914
-
8915
- // src/tool-error.ts
8916
- function renderToolErrorMessage(content) {
8917
- if (typeof content === "string") return content;
8918
- return content.map((block) => block.type === "text" ? block.text : `[${block.source.media_type} image]`).join("\n");
8919
- }
8920
- exports.ToolError = void 0;
8921
- var init_tool_error = __esm({
8922
- "src/tool-error.ts"() {
8923
- init_errors();
8924
- exports.ToolError = class extends exports.TheokitAgentError {
8925
- name = "ToolError";
8926
- /** The error content surfaced to the model: a string, or text/image blocks. */
8927
- content;
8928
- constructor(content, options = {}) {
8929
- super(renderToolErrorMessage(content), { ...options, isRetryable: false });
8930
- this.content = content;
8931
- }
8932
- };
8933
- }
8934
- });
8935
-
8936
- // src/internal/runtime/tools/shell-tool.ts
8937
- async function runShell(options) {
8938
- if (options.sandbox === true && isObviouslyUnsafe(options.command)) {
8939
- return {
8940
- stdout: "",
8941
- stderr: `Sandbox refused command: ${options.command}`,
8942
- exitCode: 126,
8943
- timedOut: false
8944
- };
8945
- }
8946
- const result = await spawnAndCollect({
8947
- command: "sh",
8948
- args: ["-c", options.command],
8949
- cwd: options.cwd,
8950
- ...options.env !== void 0 ? { env: options.env } : {},
8951
- ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
8952
- });
8953
- const stderr = result.spawnError !== void 0 ? result.stderr + result.spawnError.message : result.stderr;
8954
- return {
8955
- stdout: result.stdout,
8956
- stderr,
8957
- exitCode: result.exitCode,
8958
- timedOut: result.timedOut
8959
- };
8960
- }
8961
- function isObviouslyUnsafe(command) {
8962
- if (/(^|\s)(rm|mv|cp)\s+[^|;]*\s+\/(etc|var|root)\b/.test(command)) return true;
8963
- if (/sudo\s/.test(command)) return true;
8964
- return false;
8965
- }
8966
- var init_shell_tool = __esm({
8967
- "src/internal/runtime/tools/shell-tool.ts"() {
8968
- init_spawn_collect();
8969
- }
8970
- });
8971
-
8972
- // src/internal/agent-loop/tool-executors.ts
8973
- async function executeTool(inputs, resolved, call) {
8974
- if (resolved === void 0) {
8975
- return { stdout: "", stderr: `Unknown tool ${call.name}`, exitCode: 127 };
8976
- }
8977
- if (resolved.origin === "shell") return runShellTool(inputs, call);
8978
- if (resolved.origin === "memory") return runMemoryTool(resolved, call, inputs.context);
8979
- if (resolved.origin === "custom")
8980
- return runCustomTool(resolved, call, inputs.signal, inputs.context, inputs.messages);
8981
- return runMcpTool(inputs, resolved, call);
8982
- }
8983
- async function runMemoryTool(resolved, call, context) {
8984
- return runHandlerTool("memory", resolved.memoryHandler, call, void 0, context);
8985
- }
8986
- async function runCustomTool(resolved, call, signal, context, messages) {
8987
- return runHandlerTool("custom", resolved.customHandler, call, signal, context, messages);
8988
- }
8989
- async function runHandlerTool(kind, handler, call, signal, context, messages) {
8990
- if (handler === void 0) {
8991
- return { stdout: "", stderr: `${kind} tool ${call.name} has no handler`, exitCode: 127 };
8889
+ async function runHandlerTool(kind, handler, call, signal, context, messages) {
8890
+ if (handler === void 0) {
8891
+ return { stdout: "", stderr: `${kind} tool ${call.name} has no handler`, exitCode: 127 };
8992
8892
  }
8993
8893
  try {
8994
8894
  const split = handler[TOOL_SPLIT_RESOLVER];
@@ -13362,6 +13262,198 @@ var init_register_plugin_providers = __esm({
13362
13262
  }
13363
13263
  });
13364
13264
 
13265
+ // src/internal/runtime/local-agent/real-local-run-provider.ts
13266
+ function inferProviderFromApiKey(apiKey) {
13267
+ if (apiKey === void 0 || apiKey.length === 0) return void 0;
13268
+ const byPrefix = [
13269
+ { provider: "openrouter", prefix: "sk-or-" },
13270
+ { provider: "anthropic", prefix: "sk-ant-" },
13271
+ { provider: "openai", prefix: "sk-" }
13272
+ ];
13273
+ for (const { provider, prefix } of byPrefix) {
13274
+ if (apiKey.startsWith(prefix) && getProviderProfile(provider) !== void 0) {
13275
+ return provider;
13276
+ }
13277
+ }
13278
+ return void 0;
13279
+ }
13280
+ function detectPrimaryProvider() {
13281
+ if (process.env.ANTHROPIC_API_KEY !== void 0 && process.env.ANTHROPIC_API_KEY.length > 0) {
13282
+ return "anthropic";
13283
+ }
13284
+ if (process.env.OPENAI_API_KEY !== void 0 && process.env.OPENAI_API_KEY.length > 0) {
13285
+ return "openai";
13286
+ }
13287
+ if (process.env.OPENROUTER_API_KEY !== void 0 && process.env.OPENROUTER_API_KEY.length > 0) {
13288
+ return "openrouter";
13289
+ }
13290
+ return "openai";
13291
+ }
13292
+ var init_real_local_run_provider = __esm({
13293
+ "src/internal/runtime/local-agent/real-local-run-provider.ts"() {
13294
+ init_providers();
13295
+ }
13296
+ });
13297
+ function inheritSubAgentCredentials(tool, creds) {
13298
+ const sink = tool[INHERIT_CREDENTIALS];
13299
+ if (typeof sink === "function") sink(creds);
13300
+ }
13301
+ async function applyDelegationStart(spec, input, iteration) {
13302
+ if (spec.onDelegationStart === void 0) return { input };
13303
+ const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });
13304
+ if (decision === void 0) return { input };
13305
+ if (decision.proceed === false)
13306
+ return { reject: decision.rejectionReason ?? "(delegation rejected)" };
13307
+ return {
13308
+ input: decision.modifiedInput ?? input,
13309
+ ...decision.modifiedMaxSteps !== void 0 ? { maxSteps: decision.modifiedMaxSteps } : {}
13310
+ };
13311
+ }
13312
+ async function collectChildToolResults(run) {
13313
+ const lines = [];
13314
+ for await (const event of run.stream()) {
13315
+ if (event.type === "tool_call" && event.status === "completed") {
13316
+ const rendered = typeof event.result === "string" ? event.result : JSON.stringify(event.result ?? null);
13317
+ lines.push(`${event.name}: ${rendered}`);
13318
+ }
13319
+ }
13320
+ if (lines.length === 0) return "";
13321
+ return `
13322
+
13323
+ <subagent-tool-results>
13324
+ ${lines.join("\n")}
13325
+ </subagent-tool-results>`;
13326
+ }
13327
+ function buildChildCreateOptions(spec, inherited) {
13328
+ const model = spec.model ? { id: spec.model } : inherited?.model;
13329
+ return {
13330
+ ...inherited?.apiKey !== void 0 ? { apiKey: inherited.apiKey } : {},
13331
+ ...model !== void 0 ? { model } : {},
13332
+ ...inherited?.plugins !== void 0 ? { plugins: inherited.plugins } : {},
13333
+ systemPrompt: spec.instructions,
13334
+ tools: spec.tools ?? []
13335
+ };
13336
+ }
13337
+ async function runChildAgent(spec, input, signal, maxSteps, inherited) {
13338
+ const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
13339
+ const agent = await Agent2.create(buildChildCreateOptions(spec, inherited));
13340
+ try {
13341
+ const sendOptions = {
13342
+ ...signal !== void 0 ? { signal } : {},
13343
+ ...maxSteps !== void 0 ? { maxIterations: maxSteps } : {},
13344
+ // SE3 — a delegated child's turn is initiated by the coordinating parent.
13345
+ origin: { kind: "coordinator" }
13346
+ };
13347
+ const run = await agent.send(input, sendOptions);
13348
+ const result = await run.wait();
13349
+ const text = result.result ?? "(no response)";
13350
+ return spec.includeToolResults === true ? text + await collectChildToolResults(run) : text;
13351
+ } finally {
13352
+ agent.dispose();
13353
+ }
13354
+ }
13355
+ async function notifyDelegationError(spec, input, error, iteration) {
13356
+ if (spec.onDelegationComplete === void 0) return;
13357
+ try {
13358
+ await spec.onDelegationComplete({ input, name: spec.name, error, iteration });
13359
+ } catch {
13360
+ }
13361
+ }
13362
+ function applyMessageFilter(spec, input, messages) {
13363
+ if (spec.messageFilter === void 0 || messages === void 0) return input;
13364
+ const filtered = spec.messageFilter({ messages, input, name: spec.name });
13365
+ if (filtered.length === 0) return input;
13366
+ const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join("\n");
13367
+ return `Prior conversation:
13368
+ ${preamble}
13369
+
13370
+ Task:
13371
+ ${input}`;
13372
+ }
13373
+ async function applyDelegationComplete(spec, input, result, iteration) {
13374
+ if (spec.onDelegationComplete === void 0) return result;
13375
+ const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });
13376
+ return completion?.feedback !== void 0 ? result + completion.feedback : result;
13377
+ }
13378
+ function defineSubAgent(spec, _parentDepth = 0) {
13379
+ const currentDepth = _parentDepth + 1;
13380
+ const maxDepth = spec.maxDelegationDepth ?? 3;
13381
+ if (currentDepth > maxDepth) {
13382
+ throw new MaxDelegationDepthError(currentDepth, maxDepth);
13383
+ }
13384
+ const inputZod = zod.z.object({
13385
+ input: zod.z.string().describe("Task for the subagent")
13386
+ });
13387
+ const inputSchema = {
13388
+ type: "object",
13389
+ properties: {
13390
+ input: { type: "string", description: "Task for the subagent" }
13391
+ },
13392
+ required: ["input"],
13393
+ additionalProperties: false
13394
+ };
13395
+ let iteration = 0;
13396
+ let inherited;
13397
+ const tool = {
13398
+ name: spec.name,
13399
+ description: spec.description,
13400
+ inputSchema,
13401
+ handler: async (rawInput, ctx) => {
13402
+ const { input: parsed } = inputZod.parse(rawInput);
13403
+ iteration += 1;
13404
+ const capturedIteration = iteration;
13405
+ const start = await applyDelegationStart(spec, parsed, capturedIteration);
13406
+ if ("reject" in start) return start.reject;
13407
+ const input = applyMessageFilter(spec, start.input, ctx?.messages);
13408
+ let result;
13409
+ try {
13410
+ result = await runChildAgent(spec, input, ctx?.signal, start.maxSteps, inherited);
13411
+ } catch (error) {
13412
+ await notifyDelegationError(spec, input, error, capturedIteration);
13413
+ throw error;
13414
+ }
13415
+ return applyDelegationComplete(spec, input, result, capturedIteration);
13416
+ }
13417
+ };
13418
+ Object.defineProperty(tool, INHERIT_CREDENTIALS, {
13419
+ value: ((creds) => {
13420
+ inherited = creds;
13421
+ }),
13422
+ enumerable: false
13423
+ });
13424
+ return tool;
13425
+ }
13426
+ function subAgentToolsFromDefinitions(agents2, parentTools) {
13427
+ return Object.entries(agents2).map(([name, def]) => {
13428
+ const whitelist = Array.isArray(def.tools) && def.tools.length > 0 ? new Set(def.tools) : void 0;
13429
+ const childTools = whitelist ? parentTools.filter((t) => whitelist.has(t.name)) : parentTools;
13430
+ return defineSubAgent({
13431
+ name,
13432
+ description: def.description,
13433
+ instructions: def.prompt,
13434
+ ...def.model !== void 0 && def.model !== "inherit" ? { model: def.model.id } : {},
13435
+ tools: [...childTools]
13436
+ });
13437
+ });
13438
+ }
13439
+ var INHERIT_CREDENTIALS, MaxDelegationDepthError;
13440
+ var init_subagent = __esm({
13441
+ "src/a2a/subagent.ts"() {
13442
+ INHERIT_CREDENTIALS = /* @__PURE__ */ Symbol("theokit.subagent.inheritCredentials");
13443
+ MaxDelegationDepthError = class extends Error {
13444
+ constructor(currentDepth, maxDepth) {
13445
+ super(`Max delegation depth ${maxDepth} exceeded (current: ${currentDepth})`);
13446
+ this.currentDepth = currentDepth;
13447
+ this.maxDepth = maxDepth;
13448
+ this.name = "MaxDelegationDepthError";
13449
+ }
13450
+ currentDepth;
13451
+ maxDepth;
13452
+ code = "max_delegation_depth";
13453
+ };
13454
+ }
13455
+ });
13456
+
13365
13457
  // src/internal/tool-registry/personality-filter.ts
13366
13458
  function applyPersonalityFilter(exposedTools, whitelist, opts) {
13367
13459
  if (whitelist === void 0) return exposedTools;
@@ -13417,36 +13509,49 @@ var init_personality_filter = __esm({
13417
13509
  }
13418
13510
  });
13419
13511
 
13420
- // src/internal/runtime/local-agent/real-local-run-provider.ts
13421
- function inferProviderFromApiKey(apiKey) {
13422
- if (apiKey === void 0 || apiKey.length === 0) return void 0;
13423
- const byPrefix = [
13424
- { provider: "openrouter", prefix: "sk-or-" },
13425
- { provider: "anthropic", prefix: "sk-ant-" },
13426
- { provider: "openai", prefix: "sk-" }
13427
- ];
13428
- for (const { provider, prefix } of byPrefix) {
13429
- if (apiKey.startsWith(prefix) && getProviderProfile(provider) !== void 0) {
13430
- return provider;
13431
- }
13432
- }
13433
- return void 0;
13512
+ // src/internal/runtime/local-agent/real-local-run-tools.ts
13513
+ function declarativeSubagentTools(agents2, parentTools) {
13514
+ if (agents2 === void 0 || Object.keys(agents2).length === 0) return [];
13515
+ return subAgentToolsFromDefinitions(agents2, parentTools);
13434
13516
  }
13435
- function detectPrimaryProvider() {
13436
- if (process.env.ANTHROPIC_API_KEY !== void 0 && process.env.ANTHROPIC_API_KEY.length > 0) {
13437
- return "anthropic";
13438
- }
13439
- if (process.env.OPENAI_API_KEY !== void 0 && process.env.OPENAI_API_KEY.length > 0) {
13440
- return "openai";
13441
- }
13442
- if (process.env.OPENROUTER_API_KEY !== void 0 && process.env.OPENROUTER_API_KEY.length > 0) {
13443
- return "openrouter";
13517
+ function bindParentCredentials(tools, agentOptions) {
13518
+ const parentPlugins = Array.isArray(agentOptions.plugins) ? agentOptions.plugins : void 0;
13519
+ const credentials = {
13520
+ ...agentOptions.apiKey !== void 0 ? { apiKey: agentOptions.apiKey } : {},
13521
+ ...typeof agentOptions.model === "object" ? { model: agentOptions.model } : {},
13522
+ ...parentPlugins !== void 0 ? { plugins: parentPlugins } : {}
13523
+ };
13524
+ for (const tool of tools) inheritSubAgentCredentials(tool, credentials);
13525
+ }
13526
+ function buildCustomToolsInput(agentOptions, sendOptions, pluginManager, personalityToolWhitelist, agentId, personalityName, subagents, effectiveModel) {
13527
+ const baseTools = sendOptions?.tools ?? agentOptions.tools ?? [];
13528
+ const agentsForTools = subagents !== void 0 && Object.keys(subagents).length > 0 ? subagents : agentOptions.agents;
13529
+ const subagentTools = declarativeSubagentTools(agentsForTools, baseTools);
13530
+ const pluginTools = pluginManager?.aggregated.tools ?? [];
13531
+ const reasoningTools = reasoningActive(agentOptions.reasoning, effectiveModel) ? [createThinkTool()] : [];
13532
+ if (baseTools.length === 0 && subagentTools.length === 0 && pluginTools.length === 0 && reasoningTools.length === 0) {
13533
+ return {};
13444
13534
  }
13445
- return "openai";
13535
+ const allTools = [...baseTools, ...subagentTools, ...pluginTools, ...reasoningTools];
13536
+ bindParentCredentials(allTools, agentOptions);
13537
+ const merged = allTools.map((tool) => ({
13538
+ name: tool.name,
13539
+ description: tool.description,
13540
+ inputSchema: tool.inputSchema,
13541
+ handler: tool.handler
13542
+ }));
13543
+ const customTools = applyPersonalityFilter(merged, personalityToolWhitelist, {
13544
+ agentId,
13545
+ personalityName
13546
+ });
13547
+ if (customTools.length === 0 && personalityToolWhitelist === void 0) return {};
13548
+ return { customTools };
13446
13549
  }
13447
- var init_real_local_run_provider = __esm({
13448
- "src/internal/runtime/local-agent/real-local-run-provider.ts"() {
13449
- init_providers();
13550
+ var init_real_local_run_tools = __esm({
13551
+ "src/internal/runtime/local-agent/real-local-run-tools.ts"() {
13552
+ init_subagent();
13553
+ init_personality_filter();
13554
+ init_native_reasoning();
13450
13555
  }
13451
13556
  });
13452
13557
 
@@ -13565,7 +13670,8 @@ function buildLoopInputs(options, runId, userText) {
13565
13670
  options.personalityToolWhitelist,
13566
13671
  options.agentId,
13567
13672
  options.personalityName,
13568
- options.subagents
13673
+ options.subagents,
13674
+ options.model
13569
13675
  ),
13570
13676
  ...options.pluginManager !== void 0 ? { pluginManager: options.pluginManager } : {},
13571
13677
  // D318 — forward SendOptions.signal to the agent loop so streamLlmTurn
@@ -13603,40 +13709,6 @@ function buildLoopInputs(options, runId, userText) {
13603
13709
  ...options.agentOptions.memoryProvider !== void 0 ? { memoryProvider: options.agentOptions.memoryProvider } : {}
13604
13710
  };
13605
13711
  }
13606
- function declarativeSubagentTools(agents2, parentTools) {
13607
- if (agents2 === void 0 || Object.keys(agents2).length === 0) return [];
13608
- return subAgentToolsFromDefinitions(agents2, parentTools);
13609
- }
13610
- function bindParentCredentials(tools, agentOptions) {
13611
- const parentPlugins = Array.isArray(agentOptions.plugins) ? agentOptions.plugins : void 0;
13612
- const credentials = {
13613
- ...agentOptions.apiKey !== void 0 ? { apiKey: agentOptions.apiKey } : {},
13614
- ...typeof agentOptions.model === "object" ? { model: agentOptions.model } : {},
13615
- ...parentPlugins !== void 0 ? { plugins: parentPlugins } : {}
13616
- };
13617
- for (const tool of tools) inheritSubAgentCredentials(tool, credentials);
13618
- }
13619
- function buildCustomToolsInput(agentOptions, sendOptions, pluginManager, personalityToolWhitelist, agentId, personalityName, subagents) {
13620
- const baseTools = sendOptions?.tools ?? agentOptions.tools ?? [];
13621
- const agentsForTools = subagents !== void 0 && Object.keys(subagents).length > 0 ? subagents : agentOptions.agents;
13622
- const subagentTools = declarativeSubagentTools(agentsForTools, baseTools);
13623
- const pluginTools = pluginManager?.aggregated.tools ?? [];
13624
- if (baseTools.length === 0 && subagentTools.length === 0 && pluginTools.length === 0) return {};
13625
- const allTools = [...baseTools, ...subagentTools, ...pluginTools];
13626
- bindParentCredentials(allTools, agentOptions);
13627
- const merged = allTools.map((tool) => ({
13628
- name: tool.name,
13629
- description: tool.description,
13630
- inputSchema: tool.inputSchema,
13631
- handler: tool.handler
13632
- }));
13633
- const customTools = applyPersonalityFilter(merged, personalityToolWhitelist, {
13634
- agentId,
13635
- personalityName
13636
- });
13637
- if (customTools.length === 0 && personalityToolWhitelist === void 0) return {};
13638
- return { customTools };
13639
- }
13640
13712
  function buildMcpMap(options) {
13641
13713
  const map = /* @__PURE__ */ new Map();
13642
13714
  const inline = options.sendOptions.mcpServers ?? options.agentOptions.mcpServers;
@@ -13649,7 +13721,6 @@ function buildMcpMap(options) {
13649
13721
  var pluginProvidersAnnounced, RealLocalRun;
13650
13722
  var init_real_local_run = __esm({
13651
13723
  "src/internal/runtime/local-agent/real-local-run.ts"() {
13652
- init_subagent();
13653
13724
  init_errors();
13654
13725
  init_run_events();
13655
13726
  init_loop();
@@ -13662,11 +13733,11 @@ var init_real_local_run = __esm({
13662
13733
  init_providers();
13663
13734
  init_register_plugin_providers();
13664
13735
  init_tracer();
13665
- init_personality_filter();
13666
13736
  init_async_local_storage();
13667
13737
  init_fixture_run_base();
13668
13738
  init_run_registry();
13669
13739
  init_real_local_run_provider();
13740
+ init_real_local_run_tools();
13670
13741
  pluginProvidersAnnounced = false;
13671
13742
  RealLocalRun = class extends FixtureRunBase {
13672
13743
  buildInputs;