@buildanagent/sdk 0.1.0-alpha.3 → 0.1.0-alpha.5
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/README.md +76 -6
- package/dist/compose.d.ts +22 -0
- package/dist/compose.js +137 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +12 -7
- package/dist/errors.js +11 -6
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +22 -2
- package/dist/events.js +2 -0
- package/dist/events.js.map +1 -1
- package/dist/freeze.d.ts +11 -0
- package/dist/freeze.js +42 -0
- package/dist/freeze.js.map +1 -0
- package/dist/hook-checks.d.ts +31 -0
- package/dist/hook-checks.js +113 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +60 -0
- package/dist/hook-runner.js +169 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +177 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +18 -8
- package/dist/loop.js +191 -29
- package/dist/loop.js.map +1 -1
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.js.map +1 -0
- package/dist/result.d.ts +11 -5
- package/dist/result.js.map +1 -1
- package/dist/run.d.ts +34 -4
- package/dist/run.js +84 -7
- package/dist/run.js.map +1 -1
- package/dist/tools/define.d.ts +3 -2
- package/dist/tools/define.js +10 -2
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/format-error.js +1 -0
- package/dist/tools/format-error.js.map +1 -1
- package/dist/tools/pipeline.d.ts +40 -7
- package/dist/tools/pipeline.js +196 -37
- package/dist/tools/pipeline.js.map +1 -1
- package/dist/tools/scheduler.d.ts +33 -0
- package/dist/tools/scheduler.js +51 -0
- package/dist/tools/scheduler.js.map +1 -0
- package/dist/tools/types.d.ts +41 -5
- package/dist/tools/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { frozenCopy } from "./freeze.js";
|
|
2
|
+
/** The hook name a `hook_error` event gives for a failed observer. */
|
|
3
|
+
export const OBSERVER_HOOK = "observer";
|
|
4
|
+
/** Delivers events to observers. `deliver` and `flush` never throw and never reject. */
|
|
5
|
+
export class ObserverBus {
|
|
6
|
+
#subscriptions = new Set();
|
|
7
|
+
#report;
|
|
8
|
+
#timeoutMs;
|
|
9
|
+
/** `timeoutMs` bounds how long `flush` waits for an observer before it drops it. */
|
|
10
|
+
constructor(report, timeoutMs) {
|
|
11
|
+
this.#report = report;
|
|
12
|
+
this.#timeoutMs = timeoutMs;
|
|
13
|
+
}
|
|
14
|
+
/** Starts delivering later events to `observer`, and returns the function that stops it. */
|
|
15
|
+
add(observer) {
|
|
16
|
+
const subscription = {
|
|
17
|
+
observer,
|
|
18
|
+
active: true,
|
|
19
|
+
tail: Promise.resolve(),
|
|
20
|
+
pending: 0,
|
|
21
|
+
current: undefined,
|
|
22
|
+
};
|
|
23
|
+
this.#subscriptions.add(subscription);
|
|
24
|
+
return () => this.#remove(subscription);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Queues `event` for every subscriber. They all get one frozen copy, so an observer can neither change the event
|
|
28
|
+
* the run and its iterators hold nor any message or result inside it.
|
|
29
|
+
*/
|
|
30
|
+
deliver(event) {
|
|
31
|
+
if (this.#subscriptions.size === 0)
|
|
32
|
+
return;
|
|
33
|
+
const frozen = frozenCopy(event);
|
|
34
|
+
for (const subscription of this.#subscriptions) {
|
|
35
|
+
subscription.pending += 1;
|
|
36
|
+
subscription.tail = subscription.tail.then(() => this.#call(subscription, frozen));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Resolves once every subscriber has handled every event delivered so far, including events its failures add. A
|
|
41
|
+
* subscriber that has not caught up within the timeout is dropped and reported, so an observer whose promise never
|
|
42
|
+
* settles can't hold the run open.
|
|
43
|
+
*/
|
|
44
|
+
async flush() {
|
|
45
|
+
let timer;
|
|
46
|
+
const expired = new Promise((resolve) => {
|
|
47
|
+
timer = setTimeout(() => resolve("expired"), this.#timeoutMs);
|
|
48
|
+
});
|
|
49
|
+
try {
|
|
50
|
+
let tails;
|
|
51
|
+
do {
|
|
52
|
+
tails = [...this.#subscriptions].map((subscription) => subscription.tail);
|
|
53
|
+
const outcome = await Promise.race([Promise.all(tails), expired]);
|
|
54
|
+
if (outcome === "expired") {
|
|
55
|
+
this.#dropLagging();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
} while ([...this.#subscriptions].some((subscription, index) => subscription.tail !== tails[index]));
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
#dropLagging() {
|
|
65
|
+
const lagging = [...this.#subscriptions].filter((subscription) => subscription.pending > 0);
|
|
66
|
+
for (const subscription of lagging)
|
|
67
|
+
this.#remove(subscription);
|
|
68
|
+
for (const subscription of lagging) {
|
|
69
|
+
const what = subscription.current === undefined ? "its events" : `a ${subscription.current} event`;
|
|
70
|
+
this.#report(OBSERVER_HOOK, new Error(`an observer did not handle ${what} within ${this.#timeoutMs} ms, so it was removed`));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
#remove(subscription) {
|
|
74
|
+
subscription.active = false;
|
|
75
|
+
this.#subscriptions.delete(subscription);
|
|
76
|
+
}
|
|
77
|
+
async #call(subscription, event) {
|
|
78
|
+
try {
|
|
79
|
+
// An unsubscribe call stops events that are queued but not yet handled, too.
|
|
80
|
+
if (!subscription.active)
|
|
81
|
+
return;
|
|
82
|
+
subscription.current = event.type;
|
|
83
|
+
await subscription.observer(event);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// A failure while handling `hook_error` or `run_end` is dropped: reporting the first would loop for ever, and
|
|
87
|
+
// nothing may follow the second.
|
|
88
|
+
if (subscription.active && event.type !== "hook_error" && event.type !== "run_end") {
|
|
89
|
+
this.#report(OBSERVER_HOOK, error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
subscription.pending -= 1;
|
|
94
|
+
subscription.current = undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=observers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"observers.js","sourceRoot":"","sources":["../src/observers.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,sEAAsE;AACtE,MAAM,CAAC,MAAM,aAAa,GAAG,UAAU,CAAC;AAexC,wFAAwF;AACxF,MAAM,OAAO,WAAW;IACb,cAAc,GAAG,IAAI,GAAG,EAAgB,CAAC;IACzC,OAAO,CAAgB;IACvB,UAAU,CAAS;IAE5B,oFAAoF;IACpF,YAAY,MAAqB,EAAE,SAAiB;QAClD,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED,4FAA4F;IAC5F,GAAG,CAAC,QAAkB;QACpB,MAAM,YAAY,GAAiB;YACjC,QAAQ;YACR,MAAM,EAAE,IAAI;YACZ,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;YACvB,OAAO,EAAE,CAAC;YACV,OAAO,EAAE,SAAS;SACnB,CAAC;QACF,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QACtC,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1C,CAAC;IAED;;;OAGG;IACH,OAAO,CAAC,KAAiB;QACvB,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,KAAK,CAAC;YAAE,OAAO;QAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;QACjC,KAAK,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O,IAAI,CAAC,CAAC;YAC1B,YAAY,CAAC,OAAO,GAAG,SAAS,CAAC;QACnC,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The observer channel: delivers each event to every subscriber, in order, without ever letting a subscriber change\n * or break the run. Each subscriber has its own queue, so a slow one delays only itself, and the run waits for the\n * queues to empty only where it must, before `agent_settled` and before the run ends, and then only for a bounded\n * time.\n */\nimport type { AgentEvent } from \"./events.js\";\nimport { frozenCopy } from \"./freeze.js\";\nimport type { Observer } from \"./hooks.js\";\n\n/** The hook name a `hook_error` event gives for a failed observer. */\nexport const OBSERVER_HOOK = \"observer\";\n\ninterface Subscription {\n readonly observer: Observer;\n active: boolean;\n tail: Promise<void>;\n /** The events queued for it and not yet handled. */\n pending: number;\n /** The type of the event it is handling, for the report when it is dropped. */\n current: AgentEvent[\"type\"] | undefined;\n}\n\n/** What a failed observer turns into: the run reports it as a `hook_error` event. */\nexport type ReportFailure = (hook: string, error: unknown) => void;\n\n/** Delivers events to observers. `deliver` and `flush` never throw and never reject. */\nexport class ObserverBus {\n readonly #subscriptions = new Set<Subscription>();\n readonly #report: ReportFailure;\n readonly #timeoutMs: number;\n\n /** `timeoutMs` bounds how long `flush` waits for an observer before it drops it. */\n constructor(report: ReportFailure, timeoutMs: number) {\n this.#report = report;\n this.#timeoutMs = timeoutMs;\n }\n\n /** Starts delivering later events to `observer`, and returns the function that stops it. */\n add(observer: Observer): () => void {\n const subscription: Subscription = {\n observer,\n active: true,\n tail: Promise.resolve(),\n pending: 0,\n current: undefined,\n };\n this.#subscriptions.add(subscription);\n return () => this.#remove(subscription);\n }\n\n /**\n * Queues `event` for every subscriber. They all get one frozen copy, so an observer can neither change the event\n * the run and its iterators hold nor any message or result inside it.\n */\n deliver(event: AgentEvent): void {\n if (this.#subscriptions.size === 0) return;\n const frozen = frozenCopy(event);\n for (const subscription of this.#subscriptions) {\n subscription.pending += 1;\n subscription.tail = subscription.tail.then(() => this.#call(subscription, frozen));\n }\n }\n\n /**\n * Resolves once every subscriber has handled every event delivered so far, including events its failures add. A\n * subscriber that has not caught up within the timeout is dropped and reported, so an observer whose promise never\n * settles can't hold the run open.\n */\n async flush(): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<\"expired\">((resolve) => {\n timer = setTimeout(() => resolve(\"expired\"), this.#timeoutMs);\n });\n try {\n let tails: Promise<void>[];\n do {\n tails = [...this.#subscriptions].map((subscription) => subscription.tail);\n const outcome = await Promise.race([Promise.all(tails), expired]);\n if (outcome === \"expired\") {\n this.#dropLagging();\n return;\n }\n } while ([...this.#subscriptions].some((subscription, index) => subscription.tail !== tails[index]));\n } finally {\n clearTimeout(timer);\n }\n }\n\n #dropLagging(): void {\n const lagging = [...this.#subscriptions].filter((subscription) => subscription.pending > 0);\n for (const subscription of lagging) this.#remove(subscription);\n for (const subscription of lagging) {\n const what = subscription.current === undefined ? \"its events\" : `a ${subscription.current} event`;\n this.#report(\n OBSERVER_HOOK,\n new Error(`an observer did not handle ${what} within ${this.#timeoutMs} ms, so it was removed`),\n );\n }\n }\n\n #remove(subscription: Subscription): void {\n subscription.active = false;\n this.#subscriptions.delete(subscription);\n }\n\n async #call(subscription: Subscription, event: AgentEvent): Promise<void> {\n try {\n // An unsubscribe call stops events that are queued but not yet handled, too.\n if (!subscription.active) return;\n subscription.current = event.type;\n await subscription.observer(event);\n } catch (error) {\n // A failure while handling `hook_error` or `run_end` is dropped: reporting the first would loop for ever, and\n // nothing may follow the second.\n if (subscription.active && event.type !== \"hook_error\" && event.type !== \"run_end\") {\n this.#report(OBSERVER_HOOK, error);\n }\n } finally {\n subscription.pending -= 1;\n subscription.current = undefined;\n }\n }\n}\n"]}
|
package/dist/result.d.ts
CHANGED
|
@@ -17,9 +17,9 @@ export interface RunError {
|
|
|
17
17
|
/**
|
|
18
18
|
* `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or
|
|
19
19
|
* credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a
|
|
20
|
-
* rejected request.
|
|
20
|
+
* rejected request. `hook`: an interceptor threw while the run fails closed, and `message` says which one.
|
|
21
21
|
*/
|
|
22
|
-
readonly kind: NonNullable<AssistantMessage["error"]>["kind"];
|
|
22
|
+
readonly kind: NonNullable<AssistantMessage["error"]>["kind"] | "hook";
|
|
23
23
|
readonly message: string;
|
|
24
24
|
/** The provider's HTTP status, when the failure came with one. */
|
|
25
25
|
readonly status?: number;
|
|
@@ -57,14 +57,20 @@ export interface DoneResult<S> extends ResultBase {
|
|
|
57
57
|
export interface EndedResult extends ResultBase {
|
|
58
58
|
readonly stopReason: "max_steps" | "aborted";
|
|
59
59
|
}
|
|
60
|
-
/** A run that ended
|
|
60
|
+
/** A run that a `shouldStop` hook ended with `{ stop: "no_progress" }`, which gave `reason`. */
|
|
61
|
+
export interface NoProgressResult extends ResultBase {
|
|
62
|
+
readonly stopReason: "no_progress";
|
|
63
|
+
readonly reason: string;
|
|
64
|
+
}
|
|
65
|
+
/** A run that ended because a model call failed, or because an interceptor failed while the run fails closed. */
|
|
61
66
|
export interface ErrorResult extends ResultBase {
|
|
62
67
|
readonly stopReason: "error";
|
|
63
68
|
readonly error: RunError;
|
|
64
69
|
}
|
|
65
70
|
/**
|
|
66
71
|
* A run that stopped before it finished, for a reason `stoppedBy` names. `clarification`: a tool from
|
|
67
|
-
* `clarificationTool()` asked the user a question.
|
|
72
|
+
* `clarificationTool()` asked the user a question. Any other value is the `reason` a `shouldStop` hook gave, or
|
|
73
|
+
* `"hook"` when it returned `true`. To go on, add the answer to `context` as a user message and pass the
|
|
68
74
|
* context to `continueRun()`.
|
|
69
75
|
*/
|
|
70
76
|
export interface StoppedResult extends ResultBase {
|
|
@@ -72,6 +78,6 @@ export interface StoppedResult extends ResultBase {
|
|
|
72
78
|
readonly stoppedBy: string;
|
|
73
79
|
}
|
|
74
80
|
/** What a run returns. Check `stopReason` before you read the fields of one variant. */
|
|
75
|
-
export type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | StoppedResult;
|
|
81
|
+
export type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | NoProgressResult | StoppedResult;
|
|
76
82
|
/** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */
|
|
77
83
|
export type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;
|
package/dist/result.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"result.js","sourceRoot":"","sources":["../src/result.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so\n * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the\n * usage, the cost and a context the run can continue from.\n */\nimport type { AssistantMessage, Cost, Message, Usage } from \"@buildanagent/gateway\";\n\n/**\n * A run's conversation as plain JSON: the system prompt and every message so far. Store it anywhere and pass it to\n * `continueRun()` to go on from where the run stopped.\n */\nexport interface Context {\n readonly system: string;\n readonly messages: readonly Message[];\n}\n\n/** Why a model call failed, copied from the failed message's `error`. */\nexport interface RunError {\n /**\n * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or\n * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a\n * rejected request.\n */\n readonly kind: NonNullable<AssistantMessage[\"error\"]>[\"kind\"];\n readonly message: string;\n /** The provider's HTTP status, when the failure came with one. */\n readonly status?: number;\n}\n\n/** The fields every run result carries. */\nexport interface ResultBase {\n /** The messages this run added: the input, if any, then every response and tool result, in order. */\n readonly messages: readonly Message[];\n /** The whole conversation, earlier history included, ready for `continueRun()`. */\n readonly context: Context;\n /** The tokens of every model call, summed. */\n readonly usage: Usage;\n /**\n * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact\n * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.\n */\n readonly cost: Cost;\n /** How many model calls the run made. */\n readonly steps: number;\n}\n\n/**\n * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is\n * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool\n * ended the run with `terminate: true`. A text\n * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `\"length\"`.\n */\nexport interface DoneResult<S> extends ResultBase {\n readonly stopReason: \"done\";\n readonly output: S | undefined;\n}\n\n/**\n * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to\n * continue. `aborted`: it was aborted.\n */\nexport interface EndedResult extends ResultBase {\n readonly stopReason: \"max_steps\" | \"aborted\";\n}\n\n/** A run that ended because a model call failed. */\nexport interface ErrorResult extends ResultBase {\n readonly stopReason: \"error\";\n readonly error: RunError;\n}\n\n/**\n * A run that stopped before it finished, for a reason `stoppedBy` names. `clarification`: a tool from\n * `clarificationTool()` asked the user a question. To go on, add the answer to `context` as a user message and pass the\n * context to `continueRun()`.\n */\nexport interface StoppedResult extends ResultBase {\n readonly stopReason: \"stopped\";\n readonly stoppedBy: string;\n}\n\n/** What a run returns. Check `stopReason` before you read the fields of one variant. */\nexport type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | StoppedResult;\n\n/** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */\nexport type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;\n"]}
|
|
1
|
+
{"version":3,"file":"result.js","sourceRoot":"","sources":["../src/result.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so\n * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the\n * usage, the cost and a context the run can continue from.\n */\nimport type { AssistantMessage, Cost, Message, Usage } from \"@buildanagent/gateway\";\n\n/**\n * A run's conversation as plain JSON: the system prompt and every message so far. Store it anywhere and pass it to\n * `continueRun()` to go on from where the run stopped.\n */\nexport interface Context {\n readonly system: string;\n readonly messages: readonly Message[];\n}\n\n/** Why a model call failed, copied from the failed message's `error`. */\nexport interface RunError {\n /**\n * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or\n * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a\n * rejected request. `hook`: an interceptor threw while the run fails closed, and `message` says which one.\n */\n readonly kind: NonNullable<AssistantMessage[\"error\"]>[\"kind\"] | \"hook\";\n readonly message: string;\n /** The provider's HTTP status, when the failure came with one. */\n readonly status?: number;\n}\n\n/** The fields every run result carries. */\nexport interface ResultBase {\n /** The messages this run added: the input, if any, then every response and tool result, in order. */\n readonly messages: readonly Message[];\n /** The whole conversation, earlier history included, ready for `continueRun()`. */\n readonly context: Context;\n /** The tokens of every model call, summed. */\n readonly usage: Usage;\n /**\n * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact\n * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.\n */\n readonly cost: Cost;\n /** How many model calls the run made. */\n readonly steps: number;\n}\n\n/**\n * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is\n * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool\n * ended the run with `terminate: true`. A text\n * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `\"length\"`.\n */\nexport interface DoneResult<S> extends ResultBase {\n readonly stopReason: \"done\";\n readonly output: S | undefined;\n}\n\n/**\n * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to\n * continue. `aborted`: it was aborted.\n */\nexport interface EndedResult extends ResultBase {\n readonly stopReason: \"max_steps\" | \"aborted\";\n}\n\n/** A run that a `shouldStop` hook ended with `{ stop: \"no_progress\" }`, which gave `reason`. */\nexport interface NoProgressResult extends ResultBase {\n readonly stopReason: \"no_progress\";\n readonly reason: string;\n}\n\n/** A run that ended because a model call failed, or because an interceptor failed while the run fails closed. */\nexport interface ErrorResult extends ResultBase {\n readonly stopReason: \"error\";\n readonly error: RunError;\n}\n\n/**\n * A run that stopped before it finished, for a reason `stoppedBy` names. `clarification`: a tool from\n * `clarificationTool()` asked the user a question. Any other value is the `reason` a `shouldStop` hook gave, or\n * `\"hook\"` when it returned `true`. To go on, add the answer to `context` as a user message and pass the\n * context to `continueRun()`.\n */\nexport interface StoppedResult extends ResultBase {\n readonly stopReason: \"stopped\";\n readonly stoppedBy: string;\n}\n\n/** What a run returns. Check `stopReason` before you read the fields of one variant. */\nexport type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | NoProgressResult | StoppedResult;\n\n/** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */\nexport type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;\n"]}
|
package/dist/run.d.ts
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
* its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the
|
|
4
4
|
* non-streaming caller drive one loop.
|
|
5
5
|
*/
|
|
6
|
-
import type { ContentBlock, Message, Model
|
|
6
|
+
import type { ContentBlock, Message, Model } from "@buildanagent/gateway";
|
|
7
7
|
import type { AgentEvent } from "./events.js";
|
|
8
|
+
import type { CallOptions, Interceptors, Observer } from "./hooks.js";
|
|
8
9
|
import type { Context, DoneResult, RunResult } from "./result.js";
|
|
9
10
|
import type { Clock } from "./testing/determinism.js";
|
|
10
11
|
import type { ToolDefinition } from "./tools/types.js";
|
|
@@ -12,7 +13,10 @@ import type { ToolDefinition } from "./tools/types.js";
|
|
|
12
13
|
export interface RunOptions<S = unknown> {
|
|
13
14
|
/** The model, from `createModel()`. */
|
|
14
15
|
readonly model: Model;
|
|
15
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a
|
|
18
|
+
* `beforeModelCall` interceptor names them in `activeTools`.
|
|
19
|
+
*/
|
|
16
20
|
readonly tools?: readonly ToolDefinition<unknown, unknown>[];
|
|
17
21
|
/**
|
|
18
22
|
* A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls
|
|
@@ -27,7 +31,25 @@ export interface RunOptions<S = unknown> {
|
|
|
27
31
|
/** Aborts the run, like `run.abort()`. */
|
|
28
32
|
readonly signal?: AbortSignal;
|
|
29
33
|
/** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */
|
|
30
|
-
readonly modelOptions?:
|
|
34
|
+
readonly modelOptions?: CallOptions;
|
|
35
|
+
/**
|
|
36
|
+
* The interceptors: hooks that can change the run at six moments. A run takes one object; join several with
|
|
37
|
+
* `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.
|
|
38
|
+
*/
|
|
39
|
+
readonly interceptors?: Interceptors;
|
|
40
|
+
/**
|
|
41
|
+
* Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in
|
|
42
|
+
* order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a
|
|
43
|
+
* `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most
|
|
44
|
+
* `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a
|
|
45
|
+
* `hook_error`.
|
|
46
|
+
*/
|
|
47
|
+
readonly observers?: readonly Observer[];
|
|
48
|
+
/**
|
|
49
|
+
* The longest the run waits for its observers each time it waits for them: before `agent_settled`, before
|
|
50
|
+
* `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.
|
|
51
|
+
*/
|
|
52
|
+
readonly observerTimeoutMs?: number;
|
|
31
53
|
/** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */
|
|
32
54
|
readonly clock?: Clock;
|
|
33
55
|
/** Makes the run's id. Defaults to `crypto.randomUUID()`. */
|
|
@@ -54,9 +76,17 @@ export interface Run<S = unknown> extends AsyncIterable<AgentEvent> {
|
|
|
54
76
|
readonly result: Promise<RunResult<S>>;
|
|
55
77
|
/**
|
|
56
78
|
* Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started
|
|
57
|
-
* get an error result instead. The run then ends with `stopReason: "aborted"`. Does nothing once the run has
|
|
79
|
+
* get an error result instead. The run then ends with `stopReason: "aborted"`. Does nothing once the run has its
|
|
80
|
+
* outcome and is ending, which is before `agent_settled`.
|
|
58
81
|
*/
|
|
59
82
|
abort(reason?: string): void;
|
|
83
|
+
/**
|
|
84
|
+
* Adds an observer that receives the events from now on, in order, and returns the function that removes it. An
|
|
85
|
+
* event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to
|
|
86
|
+
* see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer
|
|
87
|
+
* in the `observers` option.
|
|
88
|
+
*/
|
|
89
|
+
on(observer: Observer): () => void;
|
|
60
90
|
}
|
|
61
91
|
/**
|
|
62
92
|
* Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool
|
package/dist/run.js
CHANGED
|
@@ -1,11 +1,49 @@
|
|
|
1
1
|
import { RunStoppedError, SdkError } from "./errors.js";
|
|
2
2
|
import { runLoop } from "./loop.js";
|
|
3
|
+
import { ObserverBus } from "./observers.js";
|
|
3
4
|
import { preparedSchemaOf } from "./tools/define.js";
|
|
4
5
|
import { SDK_VERSION } from "./version.js";
|
|
5
6
|
/** The step cap's default, counted in model calls. */
|
|
6
7
|
const DEFAULT_MAX_STEPS = 20;
|
|
8
|
+
/** How long the run waits, by default, for an observer to catch up before it drops it. */
|
|
9
|
+
const DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;
|
|
10
|
+
/** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */
|
|
11
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
7
12
|
const systemClock = { now: () => new Date().toISOString() };
|
|
8
13
|
const randomIds = () => globalThis.crypto.randomUUID();
|
|
14
|
+
function messageOf(error) {
|
|
15
|
+
return error instanceof Error ? error.message : String(error);
|
|
16
|
+
}
|
|
17
|
+
function checkObserver(observer) {
|
|
18
|
+
if (typeof observer !== "function") {
|
|
19
|
+
throw new SdkError("invalid_run_options", `an observer must be a function, got ${typeof observer}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const HOOK_NAMES = [
|
|
23
|
+
"transformContext",
|
|
24
|
+
"beforeModelCall",
|
|
25
|
+
"afterModelCall",
|
|
26
|
+
"beforeToolCall",
|
|
27
|
+
"afterToolCall",
|
|
28
|
+
"shouldStop",
|
|
29
|
+
];
|
|
30
|
+
/** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */
|
|
31
|
+
function checkInterceptors(interceptors) {
|
|
32
|
+
if (typeof interceptors !== "object" || interceptors === null) {
|
|
33
|
+
throw new SdkError("invalid_run_options", "interceptors must be an object of hooks");
|
|
34
|
+
}
|
|
35
|
+
for (const name of HOOK_NAMES) {
|
|
36
|
+
const hook = interceptors[name];
|
|
37
|
+
if (hook !== undefined && typeof hook !== "function") {
|
|
38
|
+
throw new SdkError("invalid_run_options", `interceptors.${name} must be a function, got ${typeof hook}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const { onFailure } = interceptors;
|
|
42
|
+
if (onFailure !== undefined && onFailure !== "fail_closed" && onFailure !== "continue") {
|
|
43
|
+
throw new SdkError("invalid_run_options", `interceptors.onFailure must be "fail_closed" or "continue"`);
|
|
44
|
+
}
|
|
45
|
+
return interceptors;
|
|
46
|
+
}
|
|
9
47
|
function reasonOf(reason) {
|
|
10
48
|
if (typeof reason === "string")
|
|
11
49
|
return reason;
|
|
@@ -17,13 +55,25 @@ class RunHandle {
|
|
|
17
55
|
#events = [];
|
|
18
56
|
#controller = new AbortController();
|
|
19
57
|
#clock;
|
|
58
|
+
#bus;
|
|
20
59
|
#waiters = [];
|
|
21
60
|
#ended = false;
|
|
61
|
+
/** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */
|
|
62
|
+
#settled = false;
|
|
63
|
+
/** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */
|
|
64
|
+
#closed = false;
|
|
22
65
|
#failure;
|
|
23
66
|
#stepIndex = 0;
|
|
24
|
-
constructor(setup, signal) {
|
|
67
|
+
constructor(setup, signal, watch) {
|
|
25
68
|
this.id = setup.runId;
|
|
26
69
|
this.#clock = setup.clock;
|
|
70
|
+
this.#bus = new ObserverBus((hook, error) => {
|
|
71
|
+
if (!this.#closed)
|
|
72
|
+
this.#push({ type: "hook_error", hook, error: messageOf(error) }, this.#stepIndex);
|
|
73
|
+
}, watch.timeoutMs);
|
|
74
|
+
const { observers } = watch;
|
|
75
|
+
for (const observer of observers)
|
|
76
|
+
this.#bus.add(observer);
|
|
27
77
|
const emit = (body, stepIndex) => this.#push(body, stepIndex);
|
|
28
78
|
const { model } = setup;
|
|
29
79
|
const versions = { sdkVersion: SDK_VERSION, specVersion: "v1", defaultsHash: "", capabilities: [] };
|
|
@@ -33,7 +83,15 @@ class RunHandle {
|
|
|
33
83
|
forwardAbort();
|
|
34
84
|
else
|
|
35
85
|
signal?.addEventListener("abort", forwardAbort, { once: true });
|
|
36
|
-
|
|
86
|
+
// The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event
|
|
87
|
+
// after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.
|
|
88
|
+
// The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an
|
|
89
|
+
// abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.
|
|
90
|
+
const drain = () => {
|
|
91
|
+
this.#settled = true;
|
|
92
|
+
return this.#bus.flush();
|
|
93
|
+
};
|
|
94
|
+
const loop = Promise.resolve().then(() => runLoop({ ...setup, signal: this.#controller.signal }, emit, drain));
|
|
37
95
|
// The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.
|
|
38
96
|
this.result = loop;
|
|
39
97
|
// Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration
|
|
@@ -41,11 +99,15 @@ class RunHandle {
|
|
|
41
99
|
loop.then(() => this.#end(signal, forwardAbort, undefined), (error) => this.#end(signal, forwardAbort, { error }));
|
|
42
100
|
}
|
|
43
101
|
abort(reason) {
|
|
44
|
-
if (this.#ended || this.#controller.signal.aborted)
|
|
102
|
+
if (this.#settled || this.#ended || this.#controller.signal.aborted)
|
|
45
103
|
return;
|
|
46
104
|
this.#push(reason === undefined ? { type: "abort" } : { type: "abort", reason }, this.#stepIndex);
|
|
47
105
|
this.#controller.abort(reason);
|
|
48
106
|
}
|
|
107
|
+
on(observer) {
|
|
108
|
+
checkObserver(observer);
|
|
109
|
+
return this.#bus.add(observer);
|
|
110
|
+
}
|
|
49
111
|
[Symbol.asyncIterator]() {
|
|
50
112
|
let cursor = 0;
|
|
51
113
|
return {
|
|
@@ -66,8 +128,12 @@ class RunHandle {
|
|
|
66
128
|
}
|
|
67
129
|
#push(body, stepIndex) {
|
|
68
130
|
this.#stepIndex = stepIndex;
|
|
131
|
+
if (body.type === "run_end")
|
|
132
|
+
this.#closed = true;
|
|
69
133
|
const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };
|
|
70
|
-
|
|
134
|
+
const event = { ...base, ...body };
|
|
135
|
+
this.#events.push(event);
|
|
136
|
+
this.#bus.deliver(event);
|
|
71
137
|
this.#wake();
|
|
72
138
|
}
|
|
73
139
|
#end(signal, forwardAbort, failure) {
|
|
@@ -125,13 +191,24 @@ function setupOf(options, context, input) {
|
|
|
125
191
|
system: context.system,
|
|
126
192
|
history: context.messages,
|
|
127
193
|
input,
|
|
128
|
-
tools
|
|
194
|
+
tools,
|
|
129
195
|
output: options.output,
|
|
130
196
|
maxSteps,
|
|
131
197
|
modelOptions: options.modelOptions ?? {},
|
|
198
|
+
interceptors: checkInterceptors(options.interceptors ?? {}),
|
|
132
199
|
clock: options.clock ?? systemClock,
|
|
133
200
|
};
|
|
134
201
|
}
|
|
202
|
+
function observersOf(options) {
|
|
203
|
+
const observers = options.observers ?? [];
|
|
204
|
+
for (const observer of observers)
|
|
205
|
+
checkObserver(observer);
|
|
206
|
+
const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;
|
|
207
|
+
if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {
|
|
208
|
+
throw new SdkError("invalid_run_options", `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`);
|
|
209
|
+
}
|
|
210
|
+
return { observers, timeoutMs };
|
|
211
|
+
}
|
|
135
212
|
/**
|
|
136
213
|
* Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool
|
|
137
214
|
* call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an
|
|
@@ -142,7 +219,7 @@ export function run(options) {
|
|
|
142
219
|
const content = typeof options.input === "string" ? [{ type: "text", text: options.input }] : options.input;
|
|
143
220
|
const input = { role: "user", content: [...content] };
|
|
144
221
|
const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);
|
|
145
|
-
return new RunHandle(setup, options.signal);
|
|
222
|
+
return new RunHandle(setup, options.signal, observersOf(options));
|
|
146
223
|
}
|
|
147
224
|
/**
|
|
148
225
|
* Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like
|
|
@@ -150,7 +227,7 @@ export function run(options) {
|
|
|
150
227
|
* is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.
|
|
151
228
|
*/
|
|
152
229
|
export function continueRun(context, options) {
|
|
153
|
-
return new RunHandle(setupOf(options, context, []), options.signal);
|
|
230
|
+
return new RunHandle(setupOf(options, context, []), options.signal, observersOf(options));
|
|
154
231
|
}
|
|
155
232
|
/**
|
|
156
233
|
* Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that
|
package/dist/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAExD,OAAO,EAAkB,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAGrD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,C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, and the `Run` object they share (SDK plan §3.3; D10). A run streams\n * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the\n * non-streaming caller drive one loop.\n */\nimport type { ContentBlock, Message, Model, ModelCallOptions } from \"@buildanagent/gateway\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolDefinition } from \"./tools/types.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\nconst systemClock: Clock = { now: () => new Date().toISOString() };\nconst randomIds = (): string => globalThis.crypto.randomUUID();\n\n/** The options `run()` and `continueRun()` share. */\nexport interface RunOptions<S = unknown> {\n /** The model, from `createModel()`. */\n readonly model: Model;\n /** The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent. */\n readonly tools?: readonly ToolDefinition<unknown, unknown>[];\n /**\n * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls\n * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.\n */\n readonly output?: ToolDefinition<S, S>;\n /**\n * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on\n * ends with `stopReason: \"max_steps\"` and emits a `warning` event with `code: \"max_steps\"`.\n */\n readonly maxSteps?: number;\n /** Aborts the run, like `run.abort()`. */\n readonly signal?: AbortSignal;\n /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */\n readonly modelOptions?: Omit<ModelCallOptions, \"signal\">;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /** Makes the run's id. Defaults to `crypto.randomUUID()`. */\n readonly idGenerator?: () => string;\n}\n\n/** What `run()` takes besides the shared options. */\nexport interface RunInput {\n /** The system prompt. */\n readonly system: string;\n /** The user's message that starts the run. */\n readonly input: string | readonly ContentBlock[];\n /** Earlier messages to send before `input`, such as a previous conversation. */\n readonly history?: readonly Message[];\n}\n\n/**\n * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can\n * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a\n * tool that returns a malformed result, and iteration then throws the same error after the last event.\n */\nexport interface Run<S = unknown> extends AsyncIterable<AgentEvent> {\n /** The run's id, which every event carries. */\n readonly id: string;\n /** The outcome, once the run has stopped. */\n readonly result: Promise<RunResult<S>>;\n /**\n * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started\n * get an error result instead. The run then ends with `stopReason: \"aborted\"`. Does nothing once the run has ended.\n */\n abort(reason?: string): void;\n}\n\nfunction reasonOf(reason: unknown): string | undefined {\n if (typeof reason === \"string\") return reason;\n return reason instanceof Error ? reason.message : undefined;\n}\n\nclass RunHandle<S> implements Run<S> {\n readonly id: string;\n readonly result: Promise<RunResult<S>>;\n readonly #events: AgentEvent[] = [];\n readonly #controller = new AbortController();\n readonly #clock: Clock;\n #waiters: (() => void)[] = [];\n #ended = false;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\">, signal: AbortSignal | undefined) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n const emit = (body: AgentEventBody, stepIndex: number) => this.#push(body, stepIndex);\n const { model } = setup;\n const versions = { sdkVersion: SDK_VERSION, specVersion: \"v1\" as const, defaultsHash: \"\", capabilities: [] };\n emit({ type: \"run_start\", ...versions, model: model.ref }, 0);\n const forwardAbort = () => this.abort(reasonOf(signal?.reason));\n if (signal?.aborted) forwardAbort();\n else signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n const loop = runLoop({ ...setup, signal: this.#controller.signal }, emit);\n // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.\n this.result = loop as Promise<RunResult<S>>;\n // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration\n // throws the same error.\n loop.then(\n () => this.#end(signal, forwardAbort, undefined),\n (error: unknown) => this.#end(signal, forwardAbort, { error }),\n );\n }\n\n abort(reason?: string): void {\n if (this.#ended || this.#controller.signal.aborted) return;\n this.#push(reason === undefined ? { type: \"abort\" } : { type: \"abort\", reason }, this.#stepIndex);\n this.#controller.abort(reason);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {\n let cursor = 0;\n return {\n next: async () => {\n while (cursor >= this.#events.length && !this.#ended) {\n await new Promise<void>((resolve) => this.#waiters.push(resolve));\n }\n const event = this.#events[cursor];\n if (event !== undefined) {\n cursor += 1;\n return { value: event, done: false };\n }\n if (this.#failure !== undefined) throw this.#failure.error;\n return { value: undefined, done: true };\n },\n };\n }\n\n #push(body: AgentEventBody, stepIndex: number): void {\n this.#stepIndex = stepIndex;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n this.#events.push({ ...base, ...body });\n this.#wake();\n }\n\n #end(signal: AbortSignal | undefined, forwardAbort: () => void, failure: { readonly error: unknown } | undefined) {\n signal?.removeEventListener(\"abort\", forwardAbort);\n this.#failure = failure;\n this.#ended = true;\n this.#wake();\n }\n\n #wake(): void {\n const waiters = this.#waiters;\n this.#waiters = [];\n for (const wake of waiters) wake();\n }\n}\n\nfunction isModel(model: unknown): model is Model {\n const candidate = model as Partial<Model> | null;\n return (\n typeof candidate === \"object\" &&\n candidate !== null &&\n typeof candidate.stream === \"function\" &&\n typeof candidate.price === \"function\" &&\n typeof candidate.ref === \"object\"\n );\n}\n\n/** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */\nfunction toolsOf(options: RunOptions<unknown>): AnyTool[] {\n const tools = [...(options.tools ?? [])] as AnyTool[];\n const output = options.output as AnyTool | undefined;\n if (output !== undefined && !tools.includes(output)) tools.push(output);\n const names = new Set<string>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (names.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction setupOf(options: RunOptions<unknown>, context: Context, input: readonly Message[]): Omit<LoopSetup, \"signal\"> {\n if (!isModel(options.model)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"the model must come from createModel(), such as createModel({ adapter, id })\",\n );\n }\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n if (!Number.isInteger(maxSteps) || maxSteps < 1) {\n throw new SdkError(\"invalid_run_options\", `maxSteps must be a positive integer, got ${maxSteps}`);\n }\n const tools = toolsOf(options);\n if (options.output !== undefined && (options.output.exposure ?? \"direct\") !== \"direct\") {\n throw new SdkError(\n \"invalid_run_options\",\n `the output tool \"${options.output.name}\" must be sent to the model, so its exposure must be \"direct\"`,\n );\n }\n return {\n runId: (options.idGenerator ?? randomIds)(),\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools: tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\"),\n output: options.output as AnyTool | undefined,\n maxSteps,\n modelOptions: options.modelOptions ?? {},\n clock: options.clock ?? systemClock,\n };\n}\n\n/**\n * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool\n * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an\n * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool\n * that isn't sent to the model, or two tools with one name.\n */\nexport function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S> {\n const content = typeof options.input === \"string\" ? [{ type: \"text\" as const, text: options.input }] : options.input;\n const input: Message = { role: \"user\", content: [...content] };\n const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);\n return new RunHandle<S>(setup, options.signal);\n}\n\n/**\n * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like\n * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context\n * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.\n */\nexport function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S> {\n return new RunHandle<S>(setupOf(options, context, []), options.signal);\n}\n\n/**\n * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that\n * carries the result and the context to continue from.\n */\nexport async function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>> {\n const result = await started.result;\n if (result.stopReason === \"done\") return result;\n throw new RunStoppedError(result);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGxD,OAAO,EAAkB,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAG7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAGrD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,sDAAsD;AACtD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B,0FAA0F;AAC1F,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAC3C,oGAAoG;AACpG,MAAM,YAAY,GAAG,aAAa,CAAC;AAEnC,MAAM,WAAW,GAAU,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;AACnE,MAAM,SAAS,GAAG,GAAW,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;AAoF/D,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,aAAa,CAAC,QAAiB;IACtC,IAAI,OAA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CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams\n * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the\n * non-streaming caller drive one loop.\n */\nimport type { ContentBlock, Message, Model } from \"@buildanagent/gateway\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport type { CallOptions, Interceptors, Observer } from \"./hooks.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport { ObserverBus } from \"./observers.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolDefinition } from \"./tools/types.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\n/** How long the run waits, by default, for an observer to catch up before it drops it. */\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;\n/** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\nconst systemClock: Clock = { now: () => new Date().toISOString() };\nconst randomIds = (): string => globalThis.crypto.randomUUID();\n\n/** The options `run()` and `continueRun()` share. */\nexport interface RunOptions<S = unknown> {\n /** The model, from `createModel()`. */\n readonly model: Model;\n /**\n * The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a\n * `beforeModelCall` interceptor names them in `activeTools`.\n */\n readonly tools?: readonly ToolDefinition<unknown, unknown>[];\n /**\n * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls\n * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.\n */\n readonly output?: ToolDefinition<S, S>;\n /**\n * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on\n * ends with `stopReason: \"max_steps\"` and emits a `warning` event with `code: \"max_steps\"`.\n */\n readonly maxSteps?: number;\n /** Aborts the run, like `run.abort()`. */\n readonly signal?: AbortSignal;\n /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */\n readonly modelOptions?: CallOptions;\n /**\n * The interceptors: hooks that can change the run at six moments. A run takes one object; join several with\n * `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.\n */\n readonly interceptors?: Interceptors;\n /**\n * Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in\n * order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a\n * `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most\n * `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a\n * `hook_error`.\n */\n readonly observers?: readonly Observer[];\n /**\n * The longest the run waits for its observers each time it waits for them: before `agent_settled`, before\n * `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.\n */\n readonly observerTimeoutMs?: number;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /** Makes the run's id. Defaults to `crypto.randomUUID()`. */\n readonly idGenerator?: () => string;\n}\n\n/** What `run()` takes besides the shared options. */\nexport interface RunInput {\n /** The system prompt. */\n readonly system: string;\n /** The user's message that starts the run. */\n readonly input: string | readonly ContentBlock[];\n /** Earlier messages to send before `input`, such as a previous conversation. */\n readonly history?: readonly Message[];\n}\n\n/**\n * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can\n * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a\n * tool that returns a malformed result, and iteration then throws the same error after the last event.\n */\nexport interface Run<S = unknown> extends AsyncIterable<AgentEvent> {\n /** The run's id, which every event carries. */\n readonly id: string;\n /** The outcome, once the run has stopped. */\n readonly result: Promise<RunResult<S>>;\n /**\n * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started\n * get an error result instead. The run then ends with `stopReason: \"aborted\"`. Does nothing once the run has its\n * outcome and is ending, which is before `agent_settled`.\n */\n abort(reason?: string): void;\n /**\n * Adds an observer that receives the events from now on, in order, and returns the function that removes it. An\n * event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to\n * see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer\n * in the `observers` option.\n */\n on(observer: Observer): () => void;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction checkObserver(observer: unknown): void {\n if (typeof observer !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `an observer must be a function, got ${typeof observer}`);\n }\n}\n\nconst HOOK_NAMES = [\n \"transformContext\",\n \"beforeModelCall\",\n \"afterModelCall\",\n \"beforeToolCall\",\n \"afterToolCall\",\n \"shouldStop\",\n] as const;\n\n/** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */\nfunction checkInterceptors(interceptors: Interceptors): Interceptors {\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw new SdkError(\"invalid_run_options\", \"interceptors must be an object of hooks\");\n }\n for (const name of HOOK_NAMES) {\n const hook: unknown = interceptors[name];\n if (hook !== undefined && typeof hook !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.${name} must be a function, got ${typeof hook}`);\n }\n }\n const { onFailure } = interceptors;\n if (onFailure !== undefined && onFailure !== \"fail_closed\" && onFailure !== \"continue\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.onFailure must be \"fail_closed\" or \"continue\"`);\n }\n return interceptors;\n}\n\nfunction reasonOf(reason: unknown): string | undefined {\n if (typeof reason === \"string\") return reason;\n return reason instanceof Error ? reason.message : undefined;\n}\n\nclass RunHandle<S> implements Run<S> {\n readonly id: string;\n readonly result: Promise<RunResult<S>>;\n readonly #events: AgentEvent[] = [];\n readonly #controller = new AbortController();\n readonly #clock: Clock;\n readonly #bus: ObserverBus;\n #waiters: (() => void)[] = [];\n #ended = false;\n /** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */\n #settled = false;\n /** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */\n #closed = false;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\">, signal: AbortSignal | undefined, watch: ObserverSetup) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n this.#bus = new ObserverBus((hook, error) => {\n if (!this.#closed) this.#push({ type: \"hook_error\", hook, error: messageOf(error) }, this.#stepIndex);\n }, watch.timeoutMs);\n const { observers } = watch;\n for (const observer of observers) this.#bus.add(observer);\n const emit = (body: AgentEventBody, stepIndex: number) => this.#push(body, stepIndex);\n const { model } = setup;\n const versions = { sdkVersion: SDK_VERSION, specVersion: \"v1\" as const, defaultsHash: \"\", capabilities: [] };\n emit({ type: \"run_start\", ...versions, model: model.ref }, 0);\n const forwardAbort = () => this.abort(reasonOf(signal?.reason));\n if (signal?.aborted) forwardAbort();\n else signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n // The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event\n // after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.\n // The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an\n // abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.\n const drain = () => {\n this.#settled = true;\n return this.#bus.flush();\n };\n const loop = Promise.resolve().then(() => runLoop({ ...setup, signal: this.#controller.signal }, emit, drain));\n // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.\n this.result = loop as Promise<RunResult<S>>;\n // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration\n // throws the same error.\n loop.then(\n () => this.#end(signal, forwardAbort, undefined),\n (error: unknown) => this.#end(signal, forwardAbort, { error }),\n );\n }\n\n abort(reason?: string): void {\n if (this.#settled || this.#ended || this.#controller.signal.aborted) return;\n this.#push(reason === undefined ? { type: \"abort\" } : { type: \"abort\", reason }, this.#stepIndex);\n this.#controller.abort(reason);\n }\n\n on(observer: Observer): () => void {\n checkObserver(observer);\n return this.#bus.add(observer);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {\n let cursor = 0;\n return {\n next: async () => {\n while (cursor >= this.#events.length && !this.#ended) {\n await new Promise<void>((resolve) => this.#waiters.push(resolve));\n }\n const event = this.#events[cursor];\n if (event !== undefined) {\n cursor += 1;\n return { value: event, done: false };\n }\n if (this.#failure !== undefined) throw this.#failure.error;\n return { value: undefined, done: true };\n },\n };\n }\n\n #push(body: AgentEventBody, stepIndex: number): void {\n this.#stepIndex = stepIndex;\n if (body.type === \"run_end\") this.#closed = true;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n const event = { ...base, ...body } as AgentEvent;\n this.#events.push(event);\n this.#bus.deliver(event);\n this.#wake();\n }\n\n #end(signal: AbortSignal | undefined, forwardAbort: () => void, failure: { readonly error: unknown } | undefined) {\n signal?.removeEventListener(\"abort\", forwardAbort);\n this.#failure = failure;\n this.#ended = true;\n this.#wake();\n }\n\n #wake(): void {\n const waiters = this.#waiters;\n this.#waiters = [];\n for (const wake of waiters) wake();\n }\n}\n\nfunction isModel(model: unknown): model is Model {\n const candidate = model as Partial<Model> | null;\n return (\n typeof candidate === \"object\" &&\n candidate !== null &&\n typeof candidate.stream === \"function\" &&\n typeof candidate.price === \"function\" &&\n typeof candidate.ref === \"object\"\n );\n}\n\n/** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */\nfunction toolsOf(options: RunOptions<unknown>): AnyTool[] {\n const tools = [...(options.tools ?? [])] as AnyTool[];\n const output = options.output as AnyTool | undefined;\n if (output !== undefined && !tools.includes(output)) tools.push(output);\n const names = new Set<string>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (names.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction setupOf(options: RunOptions<unknown>, context: Context, input: readonly Message[]): Omit<LoopSetup, \"signal\"> {\n if (!isModel(options.model)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"the model must come from createModel(), such as createModel({ adapter, id })\",\n );\n }\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n if (!Number.isInteger(maxSteps) || maxSteps < 1) {\n throw new SdkError(\"invalid_run_options\", `maxSteps must be a positive integer, got ${maxSteps}`);\n }\n const tools = toolsOf(options);\n if (options.output !== undefined && (options.output.exposure ?? \"direct\") !== \"direct\") {\n throw new SdkError(\n \"invalid_run_options\",\n `the output tool \"${options.output.name}\" must be sent to the model, so its exposure must be \"direct\"`,\n );\n }\n return {\n runId: (options.idGenerator ?? randomIds)(),\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools,\n output: options.output as AnyTool | undefined,\n maxSteps,\n modelOptions: options.modelOptions ?? {},\n interceptors: checkInterceptors(options.interceptors ?? {}),\n clock: options.clock ?? systemClock,\n };\n}\n\n/** The observers a run starts with, and how long it waits for them. */\ninterface ObserverSetup {\n readonly observers: readonly Observer[];\n readonly timeoutMs: number;\n}\n\nfunction observersOf(options: RunOptions<unknown>): ObserverSetup {\n const observers = options.observers ?? [];\n for (const observer of observers) checkObserver(observer);\n const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {\n throw new SdkError(\n \"invalid_run_options\",\n `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`,\n );\n }\n return { observers, timeoutMs };\n}\n\n/**\n * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool\n * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an\n * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool\n * that isn't sent to the model, or two tools with one name.\n */\nexport function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S> {\n const content = typeof options.input === \"string\" ? [{ type: \"text\" as const, text: options.input }] : options.input;\n const input: Message = { role: \"user\", content: [...content] };\n const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);\n return new RunHandle<S>(setup, options.signal, observersOf(options));\n}\n\n/**\n * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like\n * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context\n * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.\n */\nexport function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S> {\n return new RunHandle<S>(setupOf(options, context, []), options.signal, observersOf(options));\n}\n\n/**\n * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that\n * carries the result and the context to continue from.\n */\nexport async function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>> {\n const result = await started.result;\n if (result.stopReason === \"done\") return result;\n throw new RunStoppedError(result);\n}\n"]}
|
package/dist/tools/define.d.ts
CHANGED
|
@@ -17,8 +17,9 @@ export declare function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>)
|
|
|
17
17
|
*
|
|
18
18
|
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
19
19
|
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
20
|
-
* values,
|
|
21
|
-
* describe itself as JSON
|
|
20
|
+
* values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` is not a function, a raw JSON Schema
|
|
21
|
+
* does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON
|
|
22
|
+
* Schema.
|
|
22
23
|
*/
|
|
23
24
|
export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
|
|
24
25
|
/** The options of `outputTool()`. */
|
package/dist/tools/define.js
CHANGED
|
@@ -6,6 +6,7 @@ import { assertCanonicalName } from "@buildanagent/gateway";
|
|
|
6
6
|
import { SdkError } from "../errors.js";
|
|
7
7
|
import { prepareSchema } from "./schema.js";
|
|
8
8
|
const EXPOSURES = ["direct", "deferred", "hidden"];
|
|
9
|
+
const EXECUTION_MODES = ["parallel", "sequential"];
|
|
9
10
|
// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.
|
|
10
11
|
const prepared = new WeakMap();
|
|
11
12
|
function invalid(message, cause) {
|
|
@@ -39,6 +40,12 @@ export function preparedSchemaOf(tool) {
|
|
|
39
40
|
if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {
|
|
40
41
|
throw invalid(`tool "${name}": exposure must be "direct", "deferred" or "hidden"`);
|
|
41
42
|
}
|
|
43
|
+
if (tool.executionMode !== undefined && !EXECUTION_MODES.includes(tool.executionMode)) {
|
|
44
|
+
throw invalid(`tool "${name}": executionMode must be "parallel" or "sequential"`);
|
|
45
|
+
}
|
|
46
|
+
if (tool.resourceKey !== undefined && typeof tool.resourceKey !== "function") {
|
|
47
|
+
throw invalid(`tool "${name}": resourceKey must be a function`);
|
|
48
|
+
}
|
|
42
49
|
const schema = prepareSchema(name, tool.inputSchema);
|
|
43
50
|
prepared.set(tool, schema);
|
|
44
51
|
return schema;
|
|
@@ -48,8 +55,9 @@ export function preparedSchemaOf(tool) {
|
|
|
48
55
|
*
|
|
49
56
|
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
50
57
|
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
51
|
-
* values,
|
|
52
|
-
* describe itself as JSON
|
|
58
|
+
* values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` is not a function, a raw JSON Schema
|
|
59
|
+
* does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON
|
|
60
|
+
* Schema.
|
|
53
61
|
*/
|
|
54
62
|
export function defineTool(definition) {
|
|
55
63
|
const tool = Object.freeze({ ...definition });
|
package/dist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\n * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,\n * so a broken tool throws when it is defined rather than when the model first calls it.\n */\nimport { assertCanonicalName, type WireTool } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport { type PreparedSchema, prepareSchema } from \"./schema.js\";\nimport type { ToolDefinition, ToolResult } from \"./types.js\";\n\nconst EXPOSURES: readonly string[] = [\"direct\", \"deferred\", \"hidden\"];\n\n// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.\nconst prepared = new WeakMap<object, PreparedSchema>();\n\nfunction invalid(message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", message, cause === undefined ? {} : { cause });\n}\n\nfunction checkName(name: unknown): string {\n if (typeof name !== \"string\") throw invalid(\"a tool's name must be a string\");\n try {\n assertCanonicalName(name);\n } catch (cause) {\n throw invalid(cause instanceof Error ? cause.message : String(cause), cause);\n }\n return name;\n}\n\n/**\n * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code\n * `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable\n * schema.\n */\nexport function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema {\n const known = prepared.get(tool);\n if (known !== undefined) return known;\n const name = checkName(tool.name);\n if (typeof tool.description !== \"string\") throw invalid(`tool \"${name}\": description must be a string`);\n if (typeof tool.execute !== \"function\") throw invalid(`tool \"${name}\": execute must be a function`);\n if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {\n throw invalid(`tool \"${name}\": exposure must be \"direct\", \"deferred\" or \"hidden\"`);\n }\n const schema = prepareSchema(name, tool.inputSchema);\n prepared.set(tool, schema);\n return schema;\n}\n\n/**\n * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.\n *\n * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters\n * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three\n * values, a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot\n * describe itself as JSON Schema.\n */\nexport function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S> {\n const tool = Object.freeze({ ...definition });\n // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.\n preparedSchemaOf(tool as ToolDefinition<unknown, unknown>);\n return tool;\n}\n\n/** The options of `outputTool()`. */\nexport interface OutputToolOptions<S> {\n readonly name: string;\n /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */\n readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;\n /** Defaults to a line asking the model to call the tool once, with its final answer. */\n readonly description?: string;\n}\n\nconst OUTPUT_DESCRIPTION = \"Submit your final answer as this tool's input. Call it once, when the task is done.\";\nconst OUTPUT_ACCEPTED = \"The final answer was accepted.\";\n\n/**\n * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the\n * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model\n * as an error result, so the model can correct the answer and call again.\n */\nexport function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S> {\n return defineTool<S, S>({\n name: options.name,\n description: options.description ?? OUTPUT_DESCRIPTION,\n inputSchema: options.schema,\n async execute(input): Promise<ToolResult<S>> {\n return { content: [{ type: \"text\", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };\n },\n });\n}\n\n/** The options of `clarificationTool()`. */\nexport interface ClarificationToolOptions {\n /** Defaults to `ask_user`. */\n readonly name?: string;\n}\n\nconst CLARIFICATION_SCHEMA = Object.freeze({\n type: \"object\",\n properties: Object.freeze({\n question: Object.freeze({ type: \"string\", minLength: 1, description: \"The question to ask the user.\" }),\n }),\n required: Object.freeze([\"question\"]),\n additionalProperties: false,\n});\n\n/**\n * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind\n * `clarification`, and a run that gets it ends with `stopReason: \"stopped\"` and `stoppedBy: \"clarification\"`.\n */\nexport function clarificationTool(options: ClarificationToolOptions = {}): ToolDefinition<{ question: string }, never> {\n return defineTool<{ question: string }, never>({\n name: options.name ?? \"ask_user\",\n description: \"Ask the user a question when you cannot continue without their answer.\",\n inputSchema: CLARIFICATION_SCHEMA,\n async execute({ question }) {\n return {\n content: [{ type: \"text\", text: \"The question was sent to the user.\" }],\n pause: { kind: \"clarification\", question },\n };\n },\n });\n}\n\n/** The tool as one model call sends it: its name, description and input JSON Schema. */\nexport function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool {\n const { jsonSchema } = preparedSchemaOf(tool);\n // Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.\n return { name: tool.name, description: tool.description, inputSchema: jsonSchema as Record<string, unknown> };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,mBAAmB,EAAiB,MAAM,uBAAuB,CAAC;AAE3E,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAuB,aAAa,EAAE,MAAM,aAAa,CAAC;AAGjE,MAAM,SAAS,GAAsB,CAAC,QAAQ,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC;AACtE,MAAM,eAAe,GAAsB,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;AAEtE,+FAA+F;AAC/F,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA0B,CAAC;AAEvD,SAAS,OAAO,CAAC,OAAe,EAAE,KAAe;IAC/C,OAAO,IAAI,QAAQ,CAAC,yBAAyB,EAAE,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AAChG,CAAC;AAED,SAAS,SAAS,CAAC,I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AQ,EAAE,SAAS,EAAE,CAAC,EAAE,WAAW,EAAE,+BAA+B,EAAE,CAAC;KACxG,CAAC;IACF,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC;IACrC,oBAAoB,EAAE,KAAK;CAC5B,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAO,GAA6B,EAAE;IACtE,OAAO,UAAU,CAA8B;QAC7C,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,UAAU;QAChC,WAAW,EAAE,wEAAwE;QACrF,WAAW,EAAE,oBAAoB;QACjC,KAAK,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE;YACxB,OAAO;gBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oCAAoC,EAAE,CAAC;gBACvE,KAAK,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE;aAC3C,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,UAAU,CAAC,IAAsC;IAC/D,MAAM,EAAE,UAAU,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAC9C,yGAAyG;IACzG,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,WAAW,EAAE,UAAqC,EAAE,CAAC;AAChH,CAAC","sourcesContent":["/**\n * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,\n * so a broken tool throws when it is defined rather than when the model first calls it.\n */\nimport { assertCanonicalName, type WireTool } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport { type PreparedSchema, prepareSchema } from \"./schema.js\";\nimport type { ToolDefinition, ToolResult } from \"./types.js\";\n\nconst EXPOSURES: readonly string[] = [\"direct\", \"deferred\", \"hidden\"];\nconst EXECUTION_MODES: readonly string[] = [\"parallel\", \"sequential\"];\n\n// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.\nconst prepared = new WeakMap<object, PreparedSchema>();\n\nfunction invalid(message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", message, cause === undefined ? {} : { cause });\n}\n\nfunction checkName(name: unknown): string {\n if (typeof name !== \"string\") throw invalid(\"a tool's name must be a string\");\n try {\n assertCanonicalName(name);\n } catch (cause) {\n throw invalid(cause instanceof Error ? cause.message : String(cause), cause);\n }\n return name;\n}\n\n/**\n * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code\n * `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable\n * schema.\n */\nexport function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema {\n const known = prepared.get(tool);\n if (known !== undefined) return known;\n const name = checkName(tool.name);\n if (typeof tool.description !== \"string\") throw invalid(`tool \"${name}\": description must be a string`);\n if (typeof tool.execute !== \"function\") throw invalid(`tool \"${name}\": execute must be a function`);\n if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {\n throw invalid(`tool \"${name}\": exposure must be \"direct\", \"deferred\" or \"hidden\"`);\n }\n if (tool.executionMode !== undefined && !EXECUTION_MODES.includes(tool.executionMode)) {\n throw invalid(`tool \"${name}\": executionMode must be \"parallel\" or \"sequential\"`);\n }\n if (tool.resourceKey !== undefined && typeof tool.resourceKey !== \"function\") {\n throw invalid(`tool \"${name}\": resourceKey must be a function`);\n }\n const schema = prepareSchema(name, tool.inputSchema);\n prepared.set(tool, schema);\n return schema;\n}\n\n/**\n * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.\n *\n * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters\n * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three\n * values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` is not a function, a raw JSON Schema\n * does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON\n * Schema.\n */\nexport function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S> {\n const tool = Object.freeze({ ...definition });\n // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.\n preparedSchemaOf(tool as ToolDefinition<unknown, unknown>);\n return tool;\n}\n\n/** The options of `outputTool()`. */\nexport interface OutputToolOptions<S> {\n readonly name: string;\n /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */\n readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;\n /** Defaults to a line asking the model to call the tool once, with its final answer. */\n readonly description?: string;\n}\n\nconst OUTPUT_DESCRIPTION = \"Submit your final answer as this tool's input. Call it once, when the task is done.\";\nconst OUTPUT_ACCEPTED = \"The final answer was accepted.\";\n\n/**\n * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the\n * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model\n * as an error result, so the model can correct the answer and call again.\n */\nexport function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S> {\n return defineTool<S, S>({\n name: options.name,\n description: options.description ?? OUTPUT_DESCRIPTION,\n inputSchema: options.schema,\n async execute(input): Promise<ToolResult<S>> {\n return { content: [{ type: \"text\", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };\n },\n });\n}\n\n/** The options of `clarificationTool()`. */\nexport interface ClarificationToolOptions {\n /** Defaults to `ask_user`. */\n readonly name?: string;\n}\n\nconst CLARIFICATION_SCHEMA = Object.freeze({\n type: \"object\",\n properties: Object.freeze({\n question: Object.freeze({ type: \"string\", minLength: 1, description: \"The question to ask the user.\" }),\n }),\n required: Object.freeze([\"question\"]),\n additionalProperties: false,\n});\n\n/**\n * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind\n * `clarification`, and a run that gets it ends with `stopReason: \"stopped\"` and `stoppedBy: \"clarification\"`.\n */\nexport function clarificationTool(options: ClarificationToolOptions = {}): ToolDefinition<{ question: string }, never> {\n return defineTool<{ question: string }, never>({\n name: options.name ?? \"ask_user\",\n description: \"Ask the user a question when you cannot continue without their answer.\",\n inputSchema: CLARIFICATION_SCHEMA,\n async execute({ question }) {\n return {\n content: [{ type: \"text\", text: \"The question was sent to the user.\" }],\n pause: { kind: \"clarification\", question },\n };\n },\n });\n}\n\n/** The tool as one model call sends it: its name, description and input JSON Schema. */\nexport function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool {\n const { jsonSchema } = preparedSchemaOf(tool);\n // Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.\n return { name: tool.name, description: tool.description, inputSchema: jsonSchema as Record<string, unknown> };\n}\n"]}
|