@theokit/sdk 2.21.0 → 2.23.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.
@@ -3,7 +3,8 @@
3
3
  * Exported via `@theokit/sdk/a2a`.
4
4
  * @public
5
5
  */
6
+ export type { ToolContextMessage } from "../types/agent-prims.js";
6
7
  export { AgentMailbox } from "./agent-mailbox.js";
7
8
  export { MessageBus, type RequestOptions } from "./message-bus.js";
8
- export { defineSubAgent, MaxDelegationDepthError, type SubAgentSpec, } from "./subagent.js";
9
+ export { type DelegationCompleteContext, type DelegationCompleteDecision, type DelegationStartContext, type DelegationStartDecision, defineSubAgent, MaxDelegationDepthError, type MessageFilterArgs, type SubAgentSpec, } from "./subagent.js";
9
10
  export type { A2AMessage, MessageHandler } from "./types.js";
@@ -3,7 +3,8 @@
3
3
  * Exported via `@theokit/sdk/a2a`.
4
4
  * @public
5
5
  */
6
+ export type { ToolContextMessage } from "../types/agent-prims.js";
6
7
  export { AgentMailbox } from "./agent-mailbox.js";
7
8
  export { MessageBus, type RequestOptions } from "./message-bus.js";
8
- export { defineSubAgent, MaxDelegationDepthError, type SubAgentSpec, } from "./subagent.js";
9
+ export { type DelegationCompleteContext, type DelegationCompleteDecision, type DelegationStartContext, type DelegationStartDecision, defineSubAgent, MaxDelegationDepthError, type MessageFilterArgs, type SubAgentSpec, } from "./subagent.js";
9
10
  export type { A2AMessage, MessageHandler } from "./types.js";
package/dist/a2a/index.js CHANGED
@@ -8323,21 +8323,21 @@ async function executeTool(inputs, resolved, call) {
8323
8323
  if (resolved.origin === "shell") return runShellTool(inputs, call);
8324
8324
  if (resolved.origin === "memory") return runMemoryTool(resolved, call, inputs.context);
8325
8325
  if (resolved.origin === "custom")
8326
- return runCustomTool(resolved, call, inputs.signal, inputs.context);
8326
+ return runCustomTool(resolved, call, inputs.signal, inputs.context, inputs.messages);
8327
8327
  return runMcpTool(inputs, resolved, call);
8328
8328
  }
8329
8329
  async function runMemoryTool(resolved, call, context) {
8330
8330
  return runHandlerTool("memory", resolved.memoryHandler, call, void 0, context);
8331
8331
  }
8332
- async function runCustomTool(resolved, call, signal, context) {
8333
- return runHandlerTool("custom", resolved.customHandler, call, signal, context);
8332
+ async function runCustomTool(resolved, call, signal, context, messages) {
8333
+ return runHandlerTool("custom", resolved.customHandler, call, signal, context, messages);
8334
8334
  }
8335
- async function runHandlerTool(kind, handler, call, signal, context) {
8335
+ async function runHandlerTool(kind, handler, call, signal, context, messages) {
8336
8336
  if (handler === void 0) {
8337
8337
  return { stdout: "", stderr: `${kind} tool ${call.name} has no handler`, exitCode: 127 };
8338
8338
  }
8339
8339
  try {
8340
- const out = await handler(call.input, { signal, context });
8340
+ const out = await handler(call.input, { signal, context, messages });
8341
8341
  if (typeof out !== "string") return { stdout: "", stderr: "", exitCode: 0, content: out };
8342
8342
  return { stdout: out, stderr: "", exitCode: 0 };
8343
8343
  } catch (cause) {
@@ -9162,6 +9162,14 @@ var init_usage_and_cost = __esm({
9162
9162
  });
9163
9163
 
9164
9164
  // src/internal/agent-loop/loop.ts
9165
+ function projectToolContextMessages(messages) {
9166
+ const projected = [];
9167
+ for (const m of messages) {
9168
+ const content = m.content.flatMap((p) => p.type === "text" ? [p.text] : []).join("");
9169
+ if (content !== "") projected.push({ role: m.role, content });
9170
+ }
9171
+ return projected;
9172
+ }
9165
9173
  async function runAgentLoop(inputs) {
9166
9174
  const sendSpan = inputs.telemetry?.startSpan("agent.send", {
9167
9175
  agentId: inputs.agentId,
@@ -9402,7 +9410,9 @@ async function continueOrTerminate(inputs, ctx, llmOutput) {
9402
9410
  const outText = await transformLlmOutputText(inputs, llmOutput.text, tCtx);
9403
9411
  ctx.messages.push(buildAssistantTurn(outText, llmOutput.toolCalls));
9404
9412
  const rawResults = await dispatchTools(
9405
- inputs,
9413
+ // SE12 — forward a read-only text projection of the transcript-so-far to tool
9414
+ // handlers via `ctx.messages` (consumed by defineSubAgent's messageFilter).
9415
+ { ...inputs, messages: projectToolContextMessages(ctx.messages) },
9406
9416
  ctx.tools,
9407
9417
  llmOutput.toolCalls,
9408
9418
  ctx.events,
@@ -18413,6 +18423,75 @@ var MaxDelegationDepthError = class extends Error {
18413
18423
  maxDepth;
18414
18424
  code = "max_delegation_depth";
18415
18425
  };
18426
+ async function applyDelegationStart(spec, input, iteration) {
18427
+ if (spec.onDelegationStart === void 0) return { input };
18428
+ const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });
18429
+ if (decision === void 0) return { input };
18430
+ if (decision.proceed === false)
18431
+ return { reject: decision.rejectionReason ?? "(delegation rejected)" };
18432
+ return {
18433
+ input: decision.modifiedInput ?? input,
18434
+ ...decision.modifiedMaxSteps !== void 0 ? { maxSteps: decision.modifiedMaxSteps } : {}
18435
+ };
18436
+ }
18437
+ async function collectChildToolResults(run) {
18438
+ const lines = [];
18439
+ for await (const event of run.stream()) {
18440
+ if (event.type === "tool_call" && event.status === "completed") {
18441
+ const rendered = typeof event.result === "string" ? event.result : JSON.stringify(event.result ?? null);
18442
+ lines.push(`${event.name}: ${rendered}`);
18443
+ }
18444
+ }
18445
+ if (lines.length === 0) return "";
18446
+ return `
18447
+
18448
+ <subagent-tool-results>
18449
+ ${lines.join("\n")}
18450
+ </subagent-tool-results>`;
18451
+ }
18452
+ async function runChildAgent(spec, input, signal, maxSteps) {
18453
+ const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
18454
+ const agent = await Agent2.create({
18455
+ ...spec.model ? { model: { id: spec.model } } : {},
18456
+ systemPrompt: spec.instructions,
18457
+ tools: spec.tools ?? []
18458
+ });
18459
+ try {
18460
+ const sendOptions = {
18461
+ ...signal !== void 0 ? { signal } : {},
18462
+ ...maxSteps !== void 0 ? { maxIterations: maxSteps } : {}
18463
+ };
18464
+ const run = Object.keys(sendOptions).length > 0 ? await agent.send(input, sendOptions) : await agent.send(input);
18465
+ const result = await run.wait();
18466
+ const text = result.result ?? "(no response)";
18467
+ return spec.includeToolResults === true ? text + await collectChildToolResults(run) : text;
18468
+ } finally {
18469
+ agent.dispose();
18470
+ }
18471
+ }
18472
+ async function notifyDelegationError(spec, input, error, iteration) {
18473
+ if (spec.onDelegationComplete === void 0) return;
18474
+ try {
18475
+ await spec.onDelegationComplete({ input, name: spec.name, error, iteration });
18476
+ } catch {
18477
+ }
18478
+ }
18479
+ function applyMessageFilter(spec, input, messages) {
18480
+ if (spec.messageFilter === void 0 || messages === void 0) return input;
18481
+ const filtered = spec.messageFilter({ messages, input, name: spec.name });
18482
+ if (filtered.length === 0) return input;
18483
+ const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join("\n");
18484
+ return `Prior conversation:
18485
+ ${preamble}
18486
+
18487
+ Task:
18488
+ ${input}`;
18489
+ }
18490
+ async function applyDelegationComplete(spec, input, result, iteration) {
18491
+ if (spec.onDelegationComplete === void 0) return result;
18492
+ const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });
18493
+ return completion?.feedback !== void 0 ? result + completion.feedback : result;
18494
+ }
18416
18495
  function defineSubAgent(spec, _parentDepth = 0) {
18417
18496
  const currentDepth = _parentDepth + 1;
18418
18497
  const maxDepth = spec.maxDelegationDepth ?? 3;
@@ -18422,25 +18501,26 @@ function defineSubAgent(spec, _parentDepth = 0) {
18422
18501
  const inputSchema = z.object({
18423
18502
  input: z.string().describe("Task for the subagent")
18424
18503
  });
18504
+ let iteration = 0;
18425
18505
  return {
18426
18506
  name: spec.name,
18427
18507
  description: spec.description,
18428
18508
  inputSchema,
18429
- handler: async (rawInput) => {
18430
- const { input } = inputSchema.parse(rawInput);
18431
- const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
18432
- const agent = await Agent2.create({
18433
- ...spec.model ? { model: { id: spec.model } } : {},
18434
- systemPrompt: spec.instructions,
18435
- tools: spec.tools ?? []
18436
- });
18509
+ handler: async (rawInput, ctx) => {
18510
+ const { input: parsed } = inputSchema.parse(rawInput);
18511
+ iteration += 1;
18512
+ const capturedIteration = iteration;
18513
+ const start = await applyDelegationStart(spec, parsed, capturedIteration);
18514
+ if ("reject" in start) return start.reject;
18515
+ const input = applyMessageFilter(spec, start.input, ctx?.messages);
18516
+ let result;
18437
18517
  try {
18438
- const run = await agent.send(input);
18439
- const result = await run.wait();
18440
- return result.result ?? "(no response)";
18441
- } finally {
18442
- agent.dispose();
18518
+ result = await runChildAgent(spec, input, ctx?.signal, start.maxSteps);
18519
+ } catch (error) {
18520
+ await notifyDelegationError(spec, input, error, capturedIteration);
18521
+ throw error;
18443
18522
  }
18523
+ return applyDelegationComplete(spec, input, result, capturedIteration);
18444
18524
  }
18445
18525
  };
18446
18526
  }