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