@theokit/agents 16.0.0 → 16.1.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +47 -1
  3. package/dist/{agent-compiler-BMpuJFAI.d.ts → agent-compiler-JSYkHpa7.d.ts} +2 -2
  4. package/dist/{delegation-scoring-CURe4oSL.d.ts → agent-orchestrator-BFWg2URC.d.ts} +11 -426
  5. package/dist/agent-runner-BUJKNNuI.d.ts +364 -0
  6. package/dist/agent-sse-handler-BRp9vHrb.d.ts +348 -0
  7. package/dist/{bridge-entry-BxJWDpQP.d.ts → bridge-entry-BNWDrPzg.d.ts} +8 -422
  8. package/dist/bridge.d.ts +8 -5
  9. package/dist/bridge.js +19 -15
  10. package/dist/{chunk-4PHZ25JN.js → chunk-3TE4PJZL.js} +62 -1137
  11. package/dist/chunk-3TE4PJZL.js.map +1 -0
  12. package/dist/{chunk-FIGLHWR2.js → chunk-4SXVNI5O.js} +7 -7
  13. package/dist/chunk-A2UVVEB3.js +799 -0
  14. package/dist/chunk-A2UVVEB3.js.map +1 -0
  15. package/dist/chunk-Z5SYU6Z6.js +353 -0
  16. package/dist/chunk-Z5SYU6Z6.js.map +1 -0
  17. package/dist/delegation-scoring-Cn5eM4lQ.d.ts +79 -0
  18. package/dist/evals.d.ts +84 -0
  19. package/dist/evals.js +191 -0
  20. package/dist/evals.js.map +1 -0
  21. package/dist/handoff.d.ts +91 -0
  22. package/dist/handoff.js +268 -0
  23. package/dist/handoff.js.map +1 -0
  24. package/dist/index.d.ts +19 -369
  25. package/dist/index.js +36 -32
  26. package/dist/index.js.map +1 -1
  27. package/dist/mcp-health.d.ts +1 -1
  28. package/dist/sdk-adapter-DQnKx7bA.d.ts +435 -0
  29. package/dist/testing.d.ts +2 -2
  30. package/dist/tools.d.ts +5 -3
  31. package/dist/tools.js +10 -6
  32. package/dist/tools.js.map +1 -1
  33. package/dist/{types-DdltPCj2.d.ts → types-D5cHmSLi.d.ts} +1 -1
  34. package/docs/capability-map.md +31 -1
  35. package/package.json +12 -2
  36. package/dist/chunk-4PHZ25JN.js.map +0 -1
  37. /package/dist/{chunk-FIGLHWR2.js.map → chunk-4SXVNI5O.js.map} +0 -0
package/dist/evals.js ADDED
@@ -0,0 +1,191 @@
1
+ import {
2
+ toAgentFactory
3
+ } from "./chunk-3TE4PJZL.js";
4
+ import "./chunk-M5J3Q6YC.js";
5
+ import "./chunk-Q65ZIFNK.js";
6
+ import "./chunk-NIQJ4GZX.js";
7
+ import "./chunk-2SP5BB6U.js";
8
+ import "./chunk-OXNDJSAJ.js";
9
+ import {
10
+ __name
11
+ } from "./chunk-Z4QWC7IK.js";
12
+
13
+ // src/evals/run-agent-evals.ts
14
+ import { TheokitAgentError } from "@theokit/sdk/errors";
15
+ import { Eval } from "@theokit/sdk/eval";
16
+ var EvalConfigError = class extends TheokitAgentError {
17
+ static {
18
+ __name(this, "EvalConfigError");
19
+ }
20
+ name = "EvalConfigError";
21
+ constructor(message) {
22
+ super(`[@theokit/agents] ${message}`, {
23
+ code: "eval_config_invalid",
24
+ isRetryable: false
25
+ });
26
+ }
27
+ };
28
+ var DEFAULT_THRESHOLD = 0.5;
29
+ async function runAgentEvals(opts) {
30
+ validate(opts);
31
+ const name = opts.name ?? `theokit-agent-evals-${crypto.randomUUID()}`;
32
+ const threshold = opts.threshold ?? DEFAULT_THRESHOLD;
33
+ const factory = toAgentFactory(opts.agent, {
34
+ apiKey: opts.apiKey,
35
+ approvals: opts.approvals,
36
+ ...opts.overrides === void 0 ? {} : {
37
+ overrides: opts.overrides
38
+ }
39
+ });
40
+ const runId = crypto.randomUUID();
41
+ const handles = [];
42
+ let caseNumber = 0;
43
+ const agentFor = /* @__PURE__ */ __name(async () => {
44
+ caseNumber += 1;
45
+ const handle = await factory(`${name}-${runId}-case-${String(caseNumber)}`);
46
+ handles.push(handle);
47
+ return handle;
48
+ }, "agentFor");
49
+ const failureMark = `theokit-scorer-failed-${runId}: `;
50
+ const scorers = opts.scorers.map((scorer, index) => strictScorer(scorer, index, failureMark));
51
+ let rows;
52
+ try {
53
+ const run = await Eval.create({
54
+ name,
55
+ dataset: opts.cases,
56
+ scorers,
57
+ agent: asEvalAgentFactory(agentFor)
58
+ }).run();
59
+ rows = run.rows;
60
+ } catch (runError) {
61
+ await Promise.allSettled(handles.map((h) => h.dispose()));
62
+ throw runError;
63
+ }
64
+ await Promise.all(handles.map((h) => h.dispose()));
65
+ const cases = rows.map((row) => toCaseResult(row, threshold, failureMark));
66
+ return {
67
+ name,
68
+ threshold,
69
+ cases,
70
+ counts: countVerdicts(cases)
71
+ };
72
+ }
73
+ __name(runAgentEvals, "runAgentEvals");
74
+ function validate(opts) {
75
+ if (!Array.isArray(opts.cases) || opts.cases.length === 0) {
76
+ throw new EvalConfigError("runAgentEvals: cases must be a non-empty array");
77
+ }
78
+ opts.cases.forEach((c, i) => {
79
+ const entry = c;
80
+ const input = typeof entry === "object" && entry !== null ? entry.input : void 0;
81
+ if (typeof input !== "string") {
82
+ throw new EvalConfigError(`runAgentEvals: cases[${String(i)}].input must be a string, got ${typeof input}`);
83
+ }
84
+ });
85
+ if (!Array.isArray(opts.scorers) || opts.scorers.length === 0) {
86
+ throw new EvalConfigError("runAgentEvals: scorers must be a non-empty array");
87
+ }
88
+ const t = opts.threshold;
89
+ if (t !== void 0 && !(Number.isFinite(t) && t >= 0 && t <= 1)) {
90
+ throw new EvalConfigError(`runAgentEvals: threshold must be within [0, 1], got ${String(t)}`);
91
+ }
92
+ }
93
+ __name(validate, "validate");
94
+ function strictScorer(scorer, index, failureMark) {
95
+ const name = typeof scorer === "function" ? `scorer-${String(index)}` : scorer.name;
96
+ const score = typeof scorer === "function" ? scorer : scorer.score;
97
+ const failed = /* @__PURE__ */ __name((why) => ({
98
+ score: 0,
99
+ reason: `${failureMark}scorer ${name} ${why}`
100
+ }), "failed");
101
+ return {
102
+ name,
103
+ score: /* @__PURE__ */ __name(async (output, expected) => {
104
+ let result;
105
+ try {
106
+ result = await score(output, expected);
107
+ } catch (scorerError) {
108
+ return failed(`threw: ${scorerError instanceof Error ? scorerError.message : describe(scorerError)}`);
109
+ }
110
+ if (!isUnitScore(result)) {
111
+ return failed(`returned ${describeScore(result)}, not { score: number within [0, 1], reason?: string }`);
112
+ }
113
+ return result;
114
+ }, "score")
115
+ };
116
+ }
117
+ __name(strictScorer, "strictScorer");
118
+ function isUnitScore(value) {
119
+ if (typeof value !== "object" || value === null) return false;
120
+ const { score, reason } = value;
121
+ return typeof score === "number" && score >= 0 && score <= 1 && (reason === void 0 || typeof reason === "string");
122
+ }
123
+ __name(isUnitScore, "isUnitScore");
124
+ function describeScore(value) {
125
+ if (typeof value === "object" && value !== null && "score" in value) {
126
+ return describe(value.score);
127
+ }
128
+ return describe(value);
129
+ }
130
+ __name(describeScore, "describeScore");
131
+ function describe(value) {
132
+ try {
133
+ return String(value);
134
+ } catch {
135
+ return `a value of type ${typeof value} with no string form`;
136
+ }
137
+ }
138
+ __name(describe, "describe");
139
+ function asEvalAgentFactory(agentFor) {
140
+ return agentFor;
141
+ }
142
+ __name(asEvalAgentFactory, "asEvalAgentFactory");
143
+ function toCaseResult(row, threshold, failureMark) {
144
+ const scores = row.scores.map((s) => s.reason?.startsWith(failureMark) === true ? {
145
+ ...s,
146
+ reason: s.reason.slice(failureMark.length)
147
+ } : s);
148
+ const failure = row.scores.find((s) => s.reason?.startsWith(failureMark) === true);
149
+ const error = row.error ?? failure?.reason?.slice(failureMark.length);
150
+ return {
151
+ index: row.index,
152
+ input: row.input,
153
+ ...row.expected === void 0 ? {} : {
154
+ expected: row.expected
155
+ },
156
+ output: row.output,
157
+ verdict: verdictOf(error, row.meanScore, threshold),
158
+ meanScore: row.meanScore,
159
+ scores,
160
+ ...error === void 0 ? {} : {
161
+ error
162
+ },
163
+ durationMs: row.durationMs
164
+ };
165
+ }
166
+ __name(toCaseResult, "toCaseResult");
167
+ function verdictOf(error, meanScore, threshold) {
168
+ if (error !== void 0) return "error";
169
+ return meanScore >= threshold ? "pass" : "fail";
170
+ }
171
+ __name(verdictOf, "verdictOf");
172
+ function countVerdicts(cases) {
173
+ const counts = {
174
+ pass: 0,
175
+ fail: 0,
176
+ error: 0
177
+ };
178
+ for (const c of cases) counts[c.verdict] += 1;
179
+ return counts;
180
+ }
181
+ __name(countVerdicts, "countVerdicts");
182
+
183
+ // src/evals-entry.ts
184
+ import { EvalAlreadyRunningError, Scorers } from "@theokit/sdk/eval";
185
+ export {
186
+ EvalAlreadyRunningError,
187
+ EvalConfigError,
188
+ Scorers,
189
+ runAgentEvals
190
+ };
191
+ //# sourceMappingURL=evals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/evals/run-agent-evals.ts","../src/evals-entry.ts"],"mappings":";;;;;;;;;;;;;AAaA,SAASA,yBAAyB;AAClC,SACEC,YAMK;AAuDA,IAAMC,kBAAN,cAA8BC,kBAAAA;EA5ErC,OA4EqCA;;;EACjBC,OAAO;EAEzB,YAAYC,SAAiB;AAE3B,UAAM,qBAAqBA,OAAAA,IAAW;MAAEC,MAAM;MAAuBC,aAAa;IAAM,CAAA;EAC1F;AACF;AAEA,IAAMC,oBAAoB;AAE1B,eAAsBC,cAAcC,MAA0B;AAC5DC,WAASD,IAAAA;AACT,QAAMN,OAAOM,KAAKN,QAAQ,uBAAuBQ,OAAOC,WAAU,CAAA;AAClE,QAAMC,YAAYJ,KAAKI,aAAaN;AACpC,QAAMO,UAAUC,eAAeN,KAAKO,OAAO;IACzCC,QAAQR,KAAKQ;IACbC,WAAWT,KAAKS;IAChB,GAAIT,KAAKU,cAAcC,SAAY,CAAC,IAAI;MAAED,WAAWV,KAAKU;IAAU;EACtE,CAAA;AAGA,QAAME,QAAQV,OAAOC,WAAU;AAC/B,QAAMU,UAA4B,CAAA;AAClC,MAAIC,aAAa;AACjB,QAAMC,WAAW,mCAAA;AAEfD,kBAAc;AACd,UAAME,SAAS,MAAMX,QAAQ,GA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E,aAAavE,YAAY,SAAS;AAC3C;AAPSsE;AAST,SAASjC,cAAcX,OAAqC;AAC1D,QAAMU,SAAS;IAAEqC,MAAM;IAAGC,MAAM;IAAGN,OAAO;EAAE;AAC5C,aAAW1B,KAAKhB,MAAOU,QAAOM,EAAE2B,OAAO,KAAK;AAC5C,SAAOjC;AACT;AAJSC;;;AC1PT,SAASsC,yBAAyBC,eAAe;","names":["TheokitAgentError","Eval","EvalConfigError","TheokitAgentError","name","message","code","isRetryable","DEFAULT_THRESHOLD","runAgentEvals","opts","validate","crypto","randomUUID","threshold","factory","toAgentFactory","agent","apiKey","approvals","overrides","undefined","runId","handles","caseNumber","agentFor","handle","String","push","failureMark","scorers","map","scorer","index","strictScorer","rows","run","Eval","create","dataset","cases","asEvalAgentFactory","runError","Promise","allSettled","h","dispose","all","row","toCaseResult","counts","countVerdicts","Array","isArray","length","forEach","c","i","entry","input","t","Number","isFinite","score","failed","why","reason","output","expected","result","scorerError","Error","describe","isUnitScore","describeScore","value","scores","s","startsWith","slice","failure","find","error","verdict","verdictOf","meanScore","durationMs","pass","fail","EvalAlreadyRunningError","Scorers"]}
@@ -0,0 +1,91 @@
1
+ import { TheokitAgentError } from '@theokit/sdk/errors';
2
+ import { S as SubAgentSpec, D as DelegationResult } from './agent-orchestrator-BFWg2URC.js';
3
+ import { A as AgentRunnerRunOptions } from './agent-runner-BUJKNNuI.js';
4
+ import '@theokit/sdk';
5
+ import '@theokit/sdk/retry';
6
+ import './agent-compiler-JSYkHpa7.js';
7
+ import '@theokit/sdk/subagents-loader';
8
+ import './types-D5cHmSLi.js';
9
+ import 'zod';
10
+ import './setting-sources-gate-BJJiKq33.js';
11
+ import './hook-handlers-Cw2FsnE5.js';
12
+ import './agent-sse-handler-BRp9vHrb.js';
13
+ import '@theokit/presenter/wire';
14
+ import '@theokit/sdk/compaction';
15
+
16
+ type HandoffErrorCode = 'unknown_agent' | 'roster_too_small' | 'duplicate_name' | 'turn_in_progress' | 'step_ceiling_too_low' | 'reserved_tool_name' | 'invalid_agent_name' | 'already_responder';
17
+ /** A roster misconfiguration, an unknown target, or a call made while a turn is running. */
18
+ declare class HandoffError extends TheokitAgentError {
19
+ readonly code: HandoffErrorCode;
20
+ readonly name = "HandoffError";
21
+ constructor(message: string, code: HandoffErrorCode);
22
+ }
23
+ interface CreateHandoffConversationOptions {
24
+ /** The agents the conversation can hand off between: at least 2, each with a unique name. */
25
+ readonly agents: readonly SubAgentSpec[];
26
+ /** The name of the agent that answers the first message. */
27
+ readonly initial: string;
28
+ /**
29
+ * Prefix of each agent's session id (`<conversationId>:<agentName>`). Default: a fresh UUID. Only
30
+ * one conversation may run a turn on an id at a time; the responder and a waiting note live in
31
+ * this object's memory, not in the id.
32
+ */
33
+ readonly conversationId?: string;
34
+ }
35
+ /**
36
+ * The run options a turn accepts: every `AgentRunner.run` option except the four the conversation
37
+ * owns. The session id and the tool list are the conversation's; a `streamFactory` replaces the
38
+ * adapter and with it the transfer tool; a per-run `maxIterations` of 1 disables tools in round 1.
39
+ */
40
+ type HandoffSendOptions = Omit<AgentRunnerRunOptions, 'sessionId' | 'tools' | 'streamFactory' | 'maxIterations'>;
41
+ /** A transfer committed by a turn. */
42
+ interface HandoffTransfer {
43
+ readonly from: string;
44
+ readonly to: string;
45
+ readonly note: string;
46
+ }
47
+ /** One turn's result: the run's result, the agent that answered it, and the transfer it made. */
48
+ interface HandoffTurn extends DelegationResult {
49
+ readonly responder: string;
50
+ readonly handoff?: HandoffTransfer;
51
+ }
52
+ interface HandoffConversation {
53
+ readonly conversationId: string;
54
+ /** The agent that answers the next message. */
55
+ readonly responder: string;
56
+ /**
57
+ * Run one turn on the current responder. Rejects with `turn_in_progress` while a turn runs on
58
+ * this conversation or on another one with the same `conversationId`, and with
59
+ * `reserved_tool_name` when `opts.sdkTools` names `transfer_to_agent`.
60
+ */
61
+ send(message: string, opts: HandoffSendOptions): Promise<HandoffTurn>;
62
+ /**
63
+ * Move the next turn to `name`; `note` is put in front of that agent's next message. Naming the
64
+ * agent that already answers changes nothing; naming it with a `note` throws `already_responder`,
65
+ * because no transfer would carry the note.
66
+ */
67
+ handoffTo(name: string, note?: string): void;
68
+ }
69
+ /**
70
+ * Create a conversation that one agent can hand to another.
71
+ *
72
+ * Each agent runs on its own session (`<conversationId>:<agentName>`) and is offered a
73
+ * `transfer_to_agent` tool naming the other agents. A transfer the agent requests is committed when
74
+ * its run returns normally and was not cancelled, so the NEXT `send()` is answered by the target,
75
+ * which reads the transferring agent's note before the user's message. The note is written by a
76
+ * model and the message by the user; neither can open the receiver's message with a note, because
77
+ * `[Handoff from` inside either, and its lookalikes (fullwidth or accented letters, zero-width
78
+ * characters, another bracket or separator), is rewritten to `[quoted: Handoff from`.
79
+ *
80
+ * The responder and a waiting note live in memory. To resume after a restart, keep the last
81
+ * `turn.handoff`. If the receiver has not answered yet, create the conversation with `initial` set
82
+ * to its `from` and call `handoffTo(handoff.to, handoff.note)`, which rebuilds the note with its
83
+ * sender; once the receiver has answered, create it with `initial` set to its `to`.
84
+ *
85
+ * @throws {HandoffError} `roster_too_small`, `duplicate_name`, `invalid_agent_name` (a ':' in a
86
+ * name), `step_ceiling_too_low`, `reserved_tool_name` or `unknown_agent` (for `initial`) at
87
+ * creation.
88
+ */
89
+ declare function createHandoffConversation(options: CreateHandoffConversationOptions): HandoffConversation;
90
+
91
+ export { type CreateHandoffConversationOptions, type HandoffConversation, HandoffError, type HandoffErrorCode, type HandoffSendOptions, type HandoffTransfer, type HandoffTurn, SubAgentSpec, createHandoffConversation };
@@ -0,0 +1,268 @@
1
+ import {
2
+ AgentRunner
3
+ } from "./chunk-A2UVVEB3.js";
4
+ import "./chunk-3TE4PJZL.js";
5
+ import "./chunk-M5J3Q6YC.js";
6
+ import "./chunk-Q65ZIFNK.js";
7
+ import "./chunk-NIQJ4GZX.js";
8
+ import "./chunk-2SP5BB6U.js";
9
+ import "./chunk-OXNDJSAJ.js";
10
+ import {
11
+ __name
12
+ } from "./chunk-Z4QWC7IK.js";
13
+
14
+ // src/handoff/handoff-conversation.ts
15
+ import { TheokitAgentError } from "@theokit/sdk/errors";
16
+ import { z } from "zod";
17
+ var TRANSFER_TOOL_NAME = "transfer_to_agent";
18
+ var NOTE_MARKER = "[Handoff from";
19
+ var QUOTED_MARKER = "[quoted: Handoff from";
20
+ var FORMAT_CHARACTER = /\p{Cf}/u;
21
+ var COMBINING_MARK = /\p{M}/gu;
22
+ var CONFUSABLE_LETTERS = {
23
+ "\u0430": "a",
24
+ "\u03B1": "a",
25
+ "\u0501": "d",
26
+ "\u04BB": "h",
27
+ "\u043C": "m",
28
+ "\u0578": "n",
29
+ "\u043E": "o",
30
+ "\u03BF": "o"
31
+ };
32
+ var FOLDED_MARKER = /[[({<\u2329\u3008\u300A\u300C\u300E\u3010\u3014][\s_.:\-\u2010-\u2015]*hand[\s_.:\-\u2010-\u2015]*off[\s_.:\-\u2010-\u2015]*from/g;
33
+ var runningConversationIds = /* @__PURE__ */ new Set();
34
+ var HandoffError = class extends TheokitAgentError {
35
+ static {
36
+ __name(this, "HandoffError");
37
+ }
38
+ code;
39
+ name = "HandoffError";
40
+ constructor(message, code) {
41
+ super(message), this.code = code;
42
+ }
43
+ };
44
+ function assertUsableRoster(agents, initial) {
45
+ if (agents.length < 2) {
46
+ throw new HandoffError(`createHandoffConversation: a handoff needs at least 2 agents, the roster holds ${agents.length}.`, "roster_too_small");
47
+ }
48
+ const seen = /* @__PURE__ */ new Set();
49
+ for (const spec of agents) {
50
+ if (seen.has(spec.name)) {
51
+ throw new HandoffError(`createHandoffConversation: duplicate agent name ${JSON.stringify(spec.name)}; each agent must be uniquely addressable.`, "duplicate_name");
52
+ }
53
+ seen.add(spec.name);
54
+ if (spec.name.includes(":")) {
55
+ throw new HandoffError(`createHandoffConversation: agent name ${JSON.stringify(spec.name)} contains ':', which ends the conversation id in each session id (<conversationId>:<agentName>).`, "invalid_agent_name");
56
+ }
57
+ assertNoTransferTool(spec.compiled.tools, `createHandoffConversation: agent ${JSON.stringify(spec.name)} already has`);
58
+ if (spec.maxIterations === 1) {
59
+ throw new HandoffError(`createHandoffConversation: agent ${JSON.stringify(spec.name)} has maxIterations 1, which disables tools in its only round and with them the transfer.`, "step_ceiling_too_low");
60
+ }
61
+ }
62
+ assertKnown(seen, initial);
63
+ }
64
+ __name(assertUsableRoster, "assertUsableRoster");
65
+ function assertNoTransferTool(tools, owner) {
66
+ if (tools.some((tool) => tool.name === TRANSFER_TOOL_NAME)) {
67
+ throw new HandoffError(`${owner} a tool named ${TRANSFER_TOOL_NAME}, which the conversation reserves for the transfer.`, "reserved_tool_name");
68
+ }
69
+ }
70
+ __name(assertNoTransferTool, "assertNoTransferTool");
71
+ function foldForMatching(text) {
72
+ let folded = "";
73
+ const spans = [];
74
+ let start = 0;
75
+ for (const char of text) {
76
+ const end = start + char.length;
77
+ if (!FORMAT_CHARACTER.test(char)) {
78
+ for (const piece of char.normalize("NFKD").replace(COMBINING_MARK, "").toLowerCase()) {
79
+ const letter = CONFUSABLE_LETTERS[piece] ?? piece;
80
+ folded += letter;
81
+ spans.push(...Array.from({
82
+ length: letter.length
83
+ }, () => ({
84
+ start,
85
+ end
86
+ })));
87
+ }
88
+ }
89
+ start = end;
90
+ }
91
+ return {
92
+ folded,
93
+ spans
94
+ };
95
+ }
96
+ __name(foldForMatching, "foldForMatching");
97
+ function quoteMarkers(text) {
98
+ const { folded, spans } = foldForMatching(text);
99
+ let quoted = "";
100
+ let cursor = 0;
101
+ for (const match of folded.matchAll(FOLDED_MARKER)) {
102
+ const first = spans[match.index];
103
+ const last = spans[match.index + match[0].length - 1];
104
+ quoted += text.slice(cursor, Math.max(cursor, first.start)) + QUOTED_MARKER;
105
+ cursor = Math.max(cursor, last.end);
106
+ }
107
+ return quoted + text.slice(cursor);
108
+ }
109
+ __name(quoteMarkers, "quoteMarkers");
110
+ function unknownAgent(names, name) {
111
+ return new HandoffError(`handoff: unknown agent ${JSON.stringify(name)}; the roster holds ${[
112
+ ...names
113
+ ].join(", ")}.`, "unknown_agent");
114
+ }
115
+ __name(unknownAgent, "unknownAgent");
116
+ function assertKnown(names, name) {
117
+ if (!names.has(name)) throw unknownAgent(names, name);
118
+ }
119
+ __name(assertKnown, "assertKnown");
120
+ function transferTool(from, others, onTransfer) {
121
+ const inputSchema = z.object({
122
+ agent: z.enum(others).describe(`Which agent answers the next message. One of: ${others.join(", ")}.`),
123
+ note: z.string().min(1).describe("What the receiving agent needs to know to continue without asking again.")
124
+ });
125
+ return {
126
+ name: TRANSFER_TOOL_NAME,
127
+ description: `Hand this conversation to another agent (${others.join(", ")}). The receiving agent answers the user's NEXT message and reads your note first; you still answer this one. Use it when the request belongs to that agent, not to you (${from}).`,
128
+ inputSchema,
129
+ handler: /* @__PURE__ */ __name((raw) => {
130
+ const { agent, note } = inputSchema.parse(raw);
131
+ onTransfer(agent, note);
132
+ return `Transfer to ${agent} recorded. ${agent} answers the user's next message.`;
133
+ }, "handler")
134
+ };
135
+ }
136
+ __name(transferTool, "transferTool");
137
+ var RosterConversation = class RosterConversation2 {
138
+ static {
139
+ __name(this, "RosterConversation");
140
+ }
141
+ conversationId;
142
+ current;
143
+ running = false;
144
+ pending;
145
+ waiting;
146
+ names;
147
+ agents = /* @__PURE__ */ new Map();
148
+ constructor(options) {
149
+ assertUsableRoster(options.agents, options.initial);
150
+ this.conversationId = options.conversationId ?? crypto.randomUUID();
151
+ this.current = options.initial;
152
+ this.names = new Set(options.agents.map((spec) => spec.name));
153
+ for (const spec of options.agents) {
154
+ const others = options.agents.map((other) => other.name).filter((name) => name !== spec.name);
155
+ const transfer = transferTool(spec.name, others, (to, note) => {
156
+ this.pending = {
157
+ to,
158
+ note
159
+ };
160
+ });
161
+ this.agents.set(spec.name, {
162
+ runner: AgentRunner.fromSpec(spec).build(),
163
+ tools: [
164
+ ...spec.compiled.tools,
165
+ transfer
166
+ ]
167
+ });
168
+ }
169
+ }
170
+ get responder() {
171
+ return this.current;
172
+ }
173
+ async send(message, opts) {
174
+ if (this.running) throw this.turnInProgress("send");
175
+ if (runningConversationIds.has(this.conversationId)) throw this.idInUse();
176
+ assertNoTransferTool(opts.sdkTools ?? [], "send: opts.sdkTools has");
177
+ this.running = true;
178
+ runningConversationIds.add(this.conversationId);
179
+ try {
180
+ return await this.runTurn(message, opts);
181
+ } finally {
182
+ this.running = false;
183
+ runningConversationIds.delete(this.conversationId);
184
+ }
185
+ }
186
+ handoffTo(name, note) {
187
+ if (this.running) throw this.turnInProgress("handoffTo");
188
+ assertKnown(this.names, name);
189
+ if (name === this.current) {
190
+ if (note === void 0) return;
191
+ throw new HandoffError(`handoff: handoffTo(${JSON.stringify(name)}) was given a note, but ${JSON.stringify(name)} already answers the next message, so no transfer would carry it. To restore a waiting note after a restart, create the conversation with \`initial\` set to the transfer's \`from\` and call handoffTo(to, note).`, "already_responder");
192
+ }
193
+ this.waiting = note === void 0 ? void 0 : {
194
+ from: this.current,
195
+ note
196
+ };
197
+ this.current = name;
198
+ }
199
+ async runTurn(message, opts) {
200
+ const from = this.current;
201
+ this.pending = void 0;
202
+ const wide = opts;
203
+ const { sessionId: _sessionId, tools: _tools, streamFactory: _streamFactory, maxIterations: _maxIterations, ...run } = wide;
204
+ const agent = this.agentOf(from);
205
+ const result = await agent.runner.run(this.withWaitingNote(message), {
206
+ ...run,
207
+ sessionId: `${this.conversationId}:${from}`,
208
+ tools: agent.tools
209
+ });
210
+ if (opts.signal?.aborted === true) return {
211
+ ...result,
212
+ responder: from
213
+ };
214
+ this.waiting = void 0;
215
+ const transfer = this.takePending();
216
+ if (transfer === void 0) return {
217
+ ...result,
218
+ responder: from
219
+ };
220
+ this.current = transfer.to;
221
+ this.waiting = {
222
+ from,
223
+ note: transfer.note
224
+ };
225
+ return {
226
+ ...result,
227
+ responder: from,
228
+ handoff: {
229
+ from,
230
+ to: transfer.to,
231
+ note: transfer.note
232
+ }
233
+ };
234
+ }
235
+ /** The transfer the run's tool call recorded, read once; the handler writes it during `run()`. */
236
+ takePending() {
237
+ const transfer = this.pending;
238
+ this.pending = void 0;
239
+ return transfer;
240
+ }
241
+ withWaitingNote(message) {
242
+ const quoted = quoteMarkers(message);
243
+ if (this.waiting === void 0) return quoted;
244
+ return `${NOTE_MARKER} ${this.waiting.from}] ${quoteMarkers(this.waiting.note)}
245
+
246
+ ${quoted}`;
247
+ }
248
+ agentOf(name) {
249
+ const agent = this.agents.get(name);
250
+ if (agent === void 0) throw unknownAgent(this.names, name);
251
+ return agent;
252
+ }
253
+ idInUse() {
254
+ return new HandoffError(`handoff: send() was called while another conversation runs a turn on conversationId ${JSON.stringify(this.conversationId)}; one conversation id belongs to one conversation at a time.`, "turn_in_progress");
255
+ }
256
+ turnInProgress(call) {
257
+ return new HandoffError(`handoff: ${call}() was called while a turn is running on ${JSON.stringify(this.current)}; await the running send() first.`, "turn_in_progress");
258
+ }
259
+ };
260
+ function createHandoffConversation(options) {
261
+ return new RosterConversation(options);
262
+ }
263
+ __name(createHandoffConversation, "createHandoffConversation");
264
+ export {
265
+ HandoffError,
266
+ createHandoffConversation
267
+ };
268
+ //# sourceMappingURL=handoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/handoff/handoff-conversation.ts"],"mappings":";;;;;;;;;;;;;;AAUA,SAASA,yBAAyB;AAClC,SAASC,SAAS;AAQlB,IAAMC,qBAAqB;AAO3B,IAAMC,cAAc;AACpB,IAAMC,gBAAgB;AAUtB,IAAMC,mBAAmB;AACzB,IAAMC,iBAAiB;AACvB,IAAMC,qBAAuD;EAC3D,UAAU;EACV,UAAU;EACV,UAAU;EACV,UAAU;EACV,UAAU;EACV,UAAU;EACV,UAAU;EACV,UAAU;AACZ;AACA,IAAMC,gBACJ;AAQF,IAAMC,yBAAyB,oBAAIC,IAAAA;AAa5B,IAAMC,eAAN,cAA2BC,kBAAAA;EAvElC,OAuEkCA;;;;EACdC,OAAO;EAEzB,YACEC,SACkBC,MAClB;AACA,UAAMD,OAAAA,GAAAA,KAFYC,OAAAA;EAGpB;AACF;AAmEA,SAASC,m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C,SAAyC;AAEzC,SAAO,IAAIP,mBAAmBO,OAAAA;AAChC;AAJgBwC;","names":["TheokitAgentError","z","TRANSFER_TOOL_NAME","NOTE_MARKER","QUOTED_MARKER","FORMAT_CHARACTER","COMBINING_MARK","CONFUSABLE_LETTERS","FOLDED_MARKER","runningConversationIds","Set","HandoffError","TheokitAgentError","name","message","code","assertUsableRoster","agents","initial","length","seen","spec","has","JSON","stringify","add","includes","assertNoTransferTool","compiled","tools","maxIterations","assertKnown","owner","some","tool","foldForMatching","text","folded","spans","start","char","end","test","piece","normalize","replace","toLowerCase","letter","push","Array","from","quoteMarkers","quoted","cursor","match","matchAll","first","index","last","slice","Math","max","unknownAgent","names","join","transferTool","others","onTransfer","inputSchema","z","object","agent","enum","describe","note","string","min","description","handler","raw","parse","RosterConversation","conversationId","current","running","pending","waiting","Map","options","crypto","randomUUID","map","other","filter","transfer","to","set","runner","AgentRunner","fromSpec","build","responder","send","opts","turnInProgress","idInUse","sdkTools","runTurn","delete","handoffTo","undefined","wide","sessionId","_sessionId","_tools","streamFactory","_streamFactory","_maxIterations","run","agentOf","result","withWaitingNote","signal","aborted","takePending","handoff","get","call","createHandoffConversation"]}