@librechat/agents 3.3.6 → 3.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/main.cjs CHANGED
@@ -222,6 +222,7 @@ Object.defineProperty(exports, "HumanMessage", {
222
222
  exports.IMAGE_TOKEN_SAFETY_MARGIN = require_tokens.IMAGE_TOKEN_SAFETY_MARGIN;
223
223
  exports.INTENT_ARG = require_intentArg.INTENT_ARG;
224
224
  exports.INTENT_DESCRIPTION = require_intentArg.INTENT_DESCRIPTION;
225
+ exports.INTENT_LABEL_MARKER = require_intentArg.INTENT_LABEL_MARKER;
225
226
  exports.INTENT_PROPERTY = require_intentArg.INTENT_PROPERTY;
226
227
  Object.defineProperty(exports, "INTERRUPT", {
227
228
  enumerable: true,
@@ -681,3 +682,4 @@ exports.videosSchema = require_schema$2.videosSchema;
681
682
  exports.withClientTimeout = require_CloudflareSandboxExecutionEngine.withClientTimeout;
682
683
  exports.withIntent = require_intentArg.withIntent;
683
684
  exports.withMessageRole = require_format.withMessageRole;
685
+ exports.withoutIntent = require_intentArg.withoutIntent;
@@ -1,8 +1,29 @@
1
1
  //#region src/tools/intentArg.ts
2
2
  /** Argument carrying the model-authored label for a tool call. */
3
3
  const INTENT_ARG = "intent";
4
- /** Model-facing instruction for the injected `intent` property. */
5
- const INTENT_DESCRIPTION = "ALWAYS write this field FIRST, before any other argument. One short sentence, present progressive, stating what this specific call is about to do: \"Searching for OAuth handling in the callback router\". It is shown to the user as the live status label for this call while it runs, so write it for a human reading a progress line. Do not restate the tool name. Do not exceed one sentence. When you make several calls to the same tool in one turn, each intent must distinguish that call from its siblings.";
4
+ /**
5
+ * Opening words of {@link INTENT_DESCRIPTION}, and the discriminator that
6
+ * tells the injected LABEL apart from a tool's own business parameter that
7
+ * merely shares the name `intent`.
8
+ *
9
+ * Exported because host applications reimplement the same strip/sanitize
10
+ * passes and would otherwise duplicate this as a string literal: if the two
11
+ * copies drift, the host silently stops recognizing SDK-native labels and
12
+ * fails OPEN (labels stay in schemas, opt-outs stop working) with no error.
13
+ * Any edit to the description must preserve this prefix verbatim.
14
+ */
15
+ const INTENT_LABEL_MARKER = "ALWAYS write this field FIRST";
16
+ /**
17
+ * Model-facing instruction for the injected `intent` property.
18
+ *
19
+ * Deliberately terse — it is repeated on every opted-in tool schema, on every
20
+ * request, so each sentence is paid for many times over. What remains is
21
+ * load-bearing: first-position placement (the entire streaming mechanism),
22
+ * the one-sentence present-progressive form, who reads it, and the sibling
23
+ * rule, without which models emit identical labels for parallel calls to one
24
+ * tool and defeat the feature's headline case.
25
+ */
26
+ const INTENT_DESCRIPTION = `${INTENT_LABEL_MARKER}, before any other argument. One present-progressive sentence saying what THIS call is about to do: "Searching for OAuth handling in the callback router". Shown to the user as this call's live status. Never name the tool. Sibling calls to one tool must differ.`;
6
27
  /**
7
28
  * Canonical (frozen) shape of the injected property. Always embed a COPY
8
29
  * (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a
@@ -26,6 +47,38 @@ function isIntentLabelProperty(property) {
26
47
  return record.type === "string" && typeof record.description === "string" && record.description.startsWith("ALWAYS write this field FIRST");
27
48
  }
28
49
  /**
50
+ * Returns a copy of `parameters` without the injected intent LABEL — the
51
+ * opt-out for consumers that render no status label and should not pay for
52
+ * the property.
53
+ *
54
+ * The SDK's native schemas carry the label unconditionally, so without this
55
+ * an embedder has no lever at all: `withIntent` is applied at module scope.
56
+ * Marker-guarded, so a tool's own business parameter named `intent` is never
57
+ * removed. Returns the input unchanged when there is nothing to strip.
58
+ *
59
+ * `required` is pruned alongside the property: a schema that lists `intent`
60
+ * as required (strict-mode normalization does exactly that, since OpenAI
61
+ * strict function schemas require every property to appear in `required`)
62
+ * would otherwise be left naming a property it no longer declares, which is
63
+ * invalid JSON Schema and gets rejected by the provider instead of quietly
64
+ * opting out.
65
+ */
66
+ function withoutIntent(parameters) {
67
+ const props = parameters?.properties;
68
+ if (parameters == null || props == null || !isIntentLabelProperty(props["intent"])) return parameters;
69
+ const { [INTENT_ARG]: _omit, ...rest } = props;
70
+ const next = {
71
+ ...parameters,
72
+ properties: rest
73
+ };
74
+ if (parameters.required != null) {
75
+ const required = parameters.required.filter((key) => key !== INTENT_ARG);
76
+ if (required.length > 0) next.required = required;
77
+ else delete next.required;
78
+ }
79
+ return next;
80
+ }
81
+ /**
29
82
  * Returns a copy of the parameters schema with `intent` prepended as the
30
83
  * FIRST property (object key order is insertion order and every provider
31
84
  * serializer preserves it — first key in the schema means first key in the
@@ -79,54 +132,24 @@ function stripIntent(args) {
79
132
  return rest;
80
133
  }
81
134
  /**
82
- * Leading-verb map for the mechanical outcome transform, keyed by the
83
- * lowercased first word of the intent. Deliberately small: an unknown leading
84
- * word leaves the intent unchanged rather than mangling it.
85
- */
86
- const OUTCOME_VERB_MAP = new Map([
87
- ["searching", "Searched"],
88
- ["reading", "Read"],
89
- ["writing", "Wrote"],
90
- ["editing", "Edited"],
91
- ["running", "Ran"],
92
- ["creating", "Created"],
93
- ["checking", "Checked"],
94
- ["fetching", "Fetched"],
95
- ["listing", "Listed"],
96
- ["looking", "Looked"],
97
- ["building", "Built"],
98
- ["deleting", "Deleted"],
99
- ["updating", "Updated"],
100
- ["adding", "Added"],
101
- ["removing", "Removed"],
102
- ["verifying", "Verified"],
103
- ["analyzing", "Analyzed"],
104
- ["generating", "Generated"],
105
- ["delegating", "Delegated"],
106
- ["spawning", "Spawned"],
107
- ["compiling", "Compiled"],
108
- ["grepping", "Grepped"]
109
- ]);
110
- function matchLeadingCase(replacement, original) {
111
- if (original.charAt(0) === original.charAt(0).toLowerCase()) return replacement.charAt(0).toLowerCase() + replacement.slice(1);
112
- return replacement;
113
- }
114
- function transformLeadingVerb(intent) {
115
- const spaceIdx = intent.search(/\s/);
116
- const leading = spaceIdx === -1 ? intent : intent.slice(0, spaceIdx);
117
- const mapped = OUTCOME_VERB_MAP.get(leading.toLowerCase());
118
- if (mapped == null) return intent;
119
- return matchLeadingCase(mapped, leading) + intent.slice(leading.length);
120
- }
121
- /**
122
135
  * Resolves the settled label for a call from its model-authored `intent` and
123
136
  * the tool's result fields, in precedence order:
124
137
  *
125
138
  * 1. `outcome` — full replacement authored by the tool.
126
139
  * 2. `outcome_patch` — first occurrence of `from` in the intent replaced
127
140
  * with `to` (case-sensitive); no-op when `from` is absent or empty.
128
- * 3. Mechanical transform — the leading word mapped present-progressive →
129
- * past tense; an unknown leading word leaves the intent unchanged.
141
+ * 3. Otherwise the intent is returned UNCHANGED.
142
+ *
143
+ * There is deliberately no mechanical present-progressive→past-tense rewrite.
144
+ * Such a transform can only be a closed list of English verbs, which makes it
145
+ * wrong in three ways at once: it never fires for the non-English labels this
146
+ * feature expects (the model answers in the user's language), it fires for
147
+ * some sibling calls and not others inside one group — "Searched…" beside
148
+ * "Recording…" — and it quietly enumerates a vocabulary in a feature whose
149
+ * premise is that the sentence is free-form. Completion is conveyed by UI
150
+ * state (the shimmer stopping, the icon settling), which is language-neutral
151
+ * and always consistent; a tool that wants past tense says so explicitly via
152
+ * `outcome` or `outcome_patch`.
130
153
  *
131
154
  * Returns undefined when there is neither an intent nor an outcome, so
132
155
  * callers fall back to their default label. Pure and dependency-free — host
@@ -142,7 +165,7 @@ function applyOutcome(intent, result) {
142
165
  * argument would interpret `$&`/`$'`-style tokens in tool-authored
143
166
  * text (e.g. labels derived from shell syntax). */
144
167
  return intent.replace(patch.from, () => patch.to);
145
- return transformLeadingVerb(intent);
168
+ return intent;
146
169
  }
147
170
  /**
148
171
  * Hard cap on an emitted outcome label. The label is a single progress line
@@ -160,15 +183,16 @@ function boundOutcomeLabel(label) {
160
183
  /**
161
184
  * Resolves the settled label to emit on a completion event: only when the
162
185
  * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined
163
- * otherwise the mechanical transform of a bare intent is left to the host
164
- * so the wire never carries a label the host can derive itself. The result
165
- * is collapsed to a bounded single line before emission.
186
+ * otherwise, so the wire never carries a label the host already has a bare
187
+ * intent needs no settled form, because it is displayed unchanged and the UI
188
+ * conveys completion through its own state. Hosts must NOT rewrite it (see
189
+ * {@link applyOutcome} for why a tense transform is deliberately absent). The
190
+ * result is collapsed to a bounded single line before emission.
166
191
  *
167
192
  * For failed calls (`isError`), only tool-AUTHORED text may label the call:
168
- * an explicit `outcome`, or a patch whose `from` actually matches the
169
- * intent. An unmatched patch must not fall through to the mechanical
170
- * past-tense transform wording drift in a failure patch would otherwise
171
- * render a success-looking label for an error.
193
+ * an explicit `outcome`, or a patch whose `from` actually matches the intent.
194
+ * An unmatched patch resolves to undefined rather than silently reusing the
195
+ * in-flight intent, so a failure is never labelled as though it succeeded.
172
196
  */
173
197
  function resolveToolOutcome(args, fields, options) {
174
198
  if (fields == null || fields.outcome == null && fields.outcome_patch == null) return;
@@ -217,6 +241,7 @@ function readOutcomeFields(source) {
217
241
  //#endregion
218
242
  exports.INTENT_ARG = INTENT_ARG;
219
243
  exports.INTENT_DESCRIPTION = INTENT_DESCRIPTION;
244
+ exports.INTENT_LABEL_MARKER = INTENT_LABEL_MARKER;
220
245
  exports.INTENT_PROPERTY = INTENT_PROPERTY;
221
246
  exports.applyOutcome = applyOutcome;
222
247
  exports.isIntentLabelProperty = isIntentLabelProperty;
@@ -226,5 +251,6 @@ exports.readOutcomeFields = readOutcomeFields;
226
251
  exports.resolveToolOutcome = resolveToolOutcome;
227
252
  exports.stripIntent = stripIntent;
228
253
  exports.withIntent = withIntent;
254
+ exports.withoutIntent = withoutIntent;
229
255
 
230
256
  //# sourceMappingURL=intentArg.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intentArg.cjs","names":[],"sources":["../../../src/tools/intentArg.ts"],"sourcesContent":["/**\n * @fileoverview Tool intent labels.\n *\n * Lets a tool declare, as the FIRST property of its input schema, an `intent`\n * string: one model-authored sentence stating what that specific call is about\n * to do (\"Searching for OAuth handling in the callback router\"). Because the\n * property is first, it is the first key providers stream in the tool-call\n * args, so a host UI can render it as the call's live status label before the\n * rest of the args exist. When the call settles, {@link applyOutcome} edits\n * the sentence in place into its outcome form — a tool-supplied replacement\n * (`outcome`), a tool-supplied span edit (`outcome_patch`), or a mechanical\n * present-progressive→past-tense transform of the leading verb.\n *\n * The arg is always optional (never listed in `required`): the same schemas\n * are callable from programmatic tool calling, where no UI renders a label\n * and forcing generated code to fabricate one would be pure cost. Tool bodies\n * must call {@link stripIntent} before using their args so no tool receives a\n * parameter it did not declare.\n */\n\nimport type { JsonSchemaType, OutcomePatch } from '@/types';\n\n/** Argument carrying the model-authored label for a tool call. */\nexport const INTENT_ARG = 'intent';\n\n/** Model-facing instruction for the injected `intent` property. */\nexport const INTENT_DESCRIPTION =\n 'ALWAYS write this field FIRST, before any other argument. One short sentence, ' +\n 'present progressive, stating what this specific call is about to do: ' +\n '\"Searching for OAuth handling in the callback router\". It is shown to the user ' +\n 'as the live status label for this call while it runs, so write it for a human ' +\n 'reading a progress line. Do not restate the tool name. Do not exceed one sentence. ' +\n 'When you make several calls to the same tool in one turn, each intent must ' +\n 'distinguish that call from its siblings.';\n\n/**\n * Canonical (frozen) shape of the injected property. Always embed a COPY\n * (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a\n * `__absolute_uri__` marker onto every subschema it dereferences, which\n * throws on a frozen object — and a single shared instance would be stamped\n * with one schema's URI while embedded in many.\n */\nexport const INTENT_PROPERTY: JsonSchemaType = Object.freeze<JsonSchemaType>({\n type: 'string',\n description: INTENT_DESCRIPTION,\n});\n\n/**\n * Discriminates the intent LABEL property from a tool's own business\n * parameter that merely shares the name: the label contract always opens\n * with the same instruction. Removal/sanitize passes must never strip a\n * parameter the tool actually needs.\n */\nexport function isIntentLabelProperty(property: unknown): boolean {\n if (property == null || typeof property !== 'object') {\n return false;\n }\n const record = property as { type?: unknown; description?: unknown };\n return (\n record.type === 'string' &&\n typeof record.description === 'string' &&\n record.description.startsWith('ALWAYS write this field FIRST')\n );\n}\n\n/**\n * Returns a copy of the parameters schema with `intent` prepended as the\n * FIRST property (object key order is insertion order and every provider\n * serializer preserves it — first key in the schema means first key in the\n * streamed input). Never mutates the input; no-op when the schema already\n * declares `intent`. The property is not added to `required`.\n */\nexport function withIntent(parameters?: JsonSchemaType): JsonSchemaType {\n const existingProps = parameters?.properties ?? {};\n if (INTENT_ARG in existingProps) {\n return parameters as JsonSchemaType;\n }\n return {\n ...parameters,\n type: 'object',\n properties: { [INTENT_ARG]: { ...INTENT_PROPERTY }, ...existingProps },\n };\n}\n\n/**\n * Coerces tool-call args to an object, parsing a stringified JSON object\n * (some providers deliver args as a string). Returns undefined otherwise.\n */\nfunction coerceArgsObject(args: unknown): Record<string, unknown> | undefined {\n if (typeof args === 'object' && args !== null && !Array.isArray(args)) {\n return args as Record<string, unknown>;\n }\n if (typeof args === 'string' && args.trim().startsWith('{')) {\n try {\n const parsed = JSON.parse(args) as unknown;\n if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Reads the model-authored intent from tool-call args (handles stringified\n * args). Returns undefined when absent, empty, or not a string.\n */\nexport function readIntent(args: unknown): string | undefined {\n const value = coerceArgsObject(args)?.[INTENT_ARG];\n if (typeof value !== 'string') {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\n/**\n * Returns the args without the `intent` key so downstream consumers that did\n * not declare it never receive it. Parses stringified JSON object args;\n * returns the value unchanged when the key is absent.\n */\nexport function stripIntent(args: unknown): unknown {\n const obj = coerceArgsObject(args);\n if (!obj || !(INTENT_ARG in obj)) {\n return args;\n }\n const { [INTENT_ARG]: _omit, ...rest } = obj;\n return rest;\n}\n\n/**\n * Leading-verb map for the mechanical outcome transform, keyed by the\n * lowercased first word of the intent. Deliberately small: an unknown leading\n * word leaves the intent unchanged rather than mangling it.\n */\nconst OUTCOME_VERB_MAP: ReadonlyMap<string, string> = new Map([\n ['searching', 'Searched'],\n ['reading', 'Read'],\n ['writing', 'Wrote'],\n ['editing', 'Edited'],\n ['running', 'Ran'],\n ['creating', 'Created'],\n ['checking', 'Checked'],\n ['fetching', 'Fetched'],\n ['listing', 'Listed'],\n ['looking', 'Looked'],\n ['building', 'Built'],\n ['deleting', 'Deleted'],\n ['updating', 'Updated'],\n ['adding', 'Added'],\n ['removing', 'Removed'],\n ['verifying', 'Verified'],\n ['analyzing', 'Analyzed'],\n ['generating', 'Generated'],\n ['delegating', 'Delegated'],\n ['spawning', 'Spawned'],\n ['compiling', 'Compiled'],\n ['grepping', 'Grepped'],\n]);\n\nfunction matchLeadingCase(replacement: string, original: string): string {\n if (original.charAt(0) === original.charAt(0).toLowerCase()) {\n return replacement.charAt(0).toLowerCase() + replacement.slice(1);\n }\n return replacement;\n}\n\nfunction transformLeadingVerb(intent: string): string {\n const spaceIdx = intent.search(/\\s/);\n const leading = spaceIdx === -1 ? intent : intent.slice(0, spaceIdx);\n const mapped = OUTCOME_VERB_MAP.get(leading.toLowerCase());\n if (mapped == null) {\n return intent;\n }\n return matchLeadingCase(mapped, leading) + intent.slice(leading.length);\n}\n\n/**\n * Resolves the settled label for a call from its model-authored `intent` and\n * the tool's result fields, in precedence order:\n *\n * 1. `outcome` — full replacement authored by the tool.\n * 2. `outcome_patch` — first occurrence of `from` in the intent replaced\n * with `to` (case-sensitive); no-op when `from` is absent or empty.\n * 3. Mechanical transform — the leading word mapped present-progressive →\n * past tense; an unknown leading word leaves the intent unchanged.\n *\n * Returns undefined when there is neither an intent nor an outcome, so\n * callers fall back to their default label. Pure and dependency-free — host\n * UIs needing identical logic can import or mirror it.\n */\nexport function applyOutcome(\n intent: string | undefined,\n result?: { outcome?: string; outcome_patch?: OutcomePatch },\n): string | undefined {\n const outcome = result?.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return outcome;\n }\n if (intent == null || intent === '') {\n return undefined;\n }\n const patch = result?.outcome_patch;\n if (patch != null && patch.from !== '' && intent.includes(patch.from)) {\n /** Replacement callback keeps `to` verbatim — a direct string second\n * argument would interpret `$&`/`$'`-style tokens in tool-authored\n * text (e.g. labels derived from shell syntax). */\n return intent.replace(patch.from, () => patch.to);\n }\n return transformLeadingVerb(intent);\n}\n\n/**\n * Hard cap on an emitted outcome label. The label is a single progress line\n * in UI chrome; a tool that derives it from data (or a malformed patch)\n * must not be able to inflate completion events or persisted parts.\n */\nconst MAX_OUTCOME_CHARS = 256;\n\nfunction boundOutcomeLabel(label: string | undefined): string | undefined {\n if (label == null) {\n return undefined;\n }\n const singleLine = label.replace(/\\s+/g, ' ').trim();\n if (singleLine === '') {\n return undefined;\n }\n if (singleLine.length <= MAX_OUTCOME_CHARS) {\n return singleLine;\n }\n return `${singleLine.slice(0, MAX_OUTCOME_CHARS - 1)}…`;\n}\n\n/**\n * Resolves the settled label to emit on a completion event: only when the\n * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined\n * otherwise — the mechanical transform of a bare intent is left to the host\n * so the wire never carries a label the host can derive itself. The result\n * is collapsed to a bounded single line before emission.\n *\n * For failed calls (`isError`), only tool-AUTHORED text may label the call:\n * an explicit `outcome`, or a patch whose `from` actually matches the\n * intent. An unmatched patch must not fall through to the mechanical\n * past-tense transform — wording drift in a failure patch would otherwise\n * render a success-looking label for an error.\n */\nexport function resolveToolOutcome(\n args: unknown,\n fields?: { outcome?: string; outcome_patch?: OutcomePatch } | null,\n options?: { isError?: boolean },\n): string | undefined {\n if (fields == null || (fields.outcome == null && fields.outcome_patch == null)) {\n return undefined;\n }\n if (options?.isError !== true) {\n return boundOutcomeLabel(applyOutcome(readIntent(args), fields));\n }\n const outcome = fields.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return boundOutcomeLabel(outcome);\n }\n const intent = readIntent(args);\n const patch = fields.outcome_patch;\n if (\n intent != null &&\n patch != null &&\n patch.from !== '' &&\n intent.includes(patch.from)\n ) {\n return boundOutcomeLabel(intent.replace(patch.from, () => patch.to));\n }\n return undefined;\n}\n\n/**\n * Reads the outcome fields off a tool-execution result: the typed\n * `outcome`/`outcome_patch` fields when present, else the artifact channel\n * (see {@link readOutcomeFields}) — so a `content_and_artifact` tool authors\n * its label the same way on the direct and event-driven paths.\n */\nexport function outcomeFieldsFromResult(result: {\n outcome?: string;\n outcome_patch?: OutcomePatch;\n artifact?: unknown;\n}): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (result.outcome != null || result.outcome_patch != null) {\n return result;\n }\n return readOutcomeFields(result.artifact);\n}\n\n/**\n * Extracts validated `outcome`/`outcome_patch` fields from an arbitrary\n * value — the artifact channel through which an in-process\n * `content_and_artifact` tool authors its settled label. Returns undefined\n * when neither field is usable.\n */\nexport function readOutcomeFields(\n source: unknown,\n): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (source == null || typeof source !== 'object' || Array.isArray(source)) {\n return undefined;\n }\n const record = source as Record<string, unknown>;\n const outcome =\n typeof record.outcome === 'string' && record.outcome.trim() !== ''\n ? record.outcome\n : undefined;\n let outcome_patch: OutcomePatch | undefined;\n const rawPatch = record.outcome_patch;\n if (rawPatch != null && typeof rawPatch === 'object' && !Array.isArray(rawPatch)) {\n const patch = rawPatch as Record<string, unknown>;\n if (typeof patch.from === 'string' && typeof patch.to === 'string') {\n outcome_patch = { from: patch.from, to: patch.to };\n }\n }\n if (outcome == null && outcome_patch == null) {\n return undefined;\n }\n return { outcome, outcome_patch };\n}\n"],"mappings":";;AAuBA,MAAa,aAAa;;AAG1B,MAAa,qBACX;;;;;;;;AAeF,MAAa,kBAAkC,OAAO,OAAuB;CAC3E,MAAM;CACN,aAAa;AACf,CAAC;;;;;;;AAQD,SAAgB,sBAAsB,UAA4B;CAChE,IAAI,YAAY,QAAQ,OAAO,aAAa,UAC1C,OAAO;CAET,MAAM,SAAS;CACf,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,gBAAgB,YAC9B,OAAO,YAAY,WAAW,+BAA+B;AAEjE;;;;;;;;AASA,SAAgB,WAAW,YAA6C;CACtE,MAAM,gBAAgB,YAAY,cAAc,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js","names":[],"sources":["../../../src/tools/intentArg.ts"],"sourcesContent":["/**\n * @fileoverview Tool intent labels.\n *\n * Lets a tool declare, as the FIRST property of its input schema, an `intent`\n * string: one model-authored sentence stating what that specific call is about\n * to do (\"Searching for OAuth handling in the callback router\"). Because the\n * property is first, it is the first key providers stream in the tool-call\n * args, so a host UI can render it as the call's live status label before the\n * rest of the args exist. When the call settles, {@link applyOutcome} edits\n * the sentence in place into its outcome form — a tool-supplied replacement\n * (`outcome`) or a tool-supplied span edit (`outcome_patch`). Absent either,\n * the label is left exactly as the model wrote it: completion is a UI state\n * (the shimmer stopping, the icon settling), not a tense change.\n *\n * The arg is always optional (never listed in `required`): the same schemas\n * are callable from programmatic tool calling, where no UI renders a label\n * and forcing generated code to fabricate one would be pure cost. Tool bodies\n * must call {@link stripIntent} before using their args so no tool receives a\n * parameter it did not declare.\n */\n\nimport type { JsonSchemaType, OutcomePatch } from '@/types';\n\n/** Argument carrying the model-authored label for a tool call. */\nexport const INTENT_ARG = 'intent';\n\n/**\n * Opening words of {@link INTENT_DESCRIPTION}, and the discriminator that\n * tells the injected LABEL apart from a tool's own business parameter that\n * merely shares the name `intent`.\n *\n * Exported because host applications reimplement the same strip/sanitize\n * passes and would otherwise duplicate this as a string literal: if the two\n * copies drift, the host silently stops recognizing SDK-native labels and\n * fails OPEN (labels stay in schemas, opt-outs stop working) with no error.\n * Any edit to the description must preserve this prefix verbatim.\n */\nexport const INTENT_LABEL_MARKER = 'ALWAYS write this field FIRST';\n\n/**\n * Model-facing instruction for the injected `intent` property.\n *\n * Deliberately terse — it is repeated on every opted-in tool schema, on every\n * request, so each sentence is paid for many times over. What remains is\n * load-bearing: first-position placement (the entire streaming mechanism),\n * the one-sentence present-progressive form, who reads it, and the sibling\n * rule, without which models emit identical labels for parallel calls to one\n * tool and defeat the feature's headline case.\n */\nexport const INTENT_DESCRIPTION =\n `${INTENT_LABEL_MARKER}, before any other argument. One present-progressive ` +\n 'sentence saying what THIS call is about to do: \"Searching for OAuth handling ' +\n 'in the callback router\". Shown to the user as this call\\'s live status. ' +\n 'Never name the tool. Sibling calls to one tool must differ.';\n\n/**\n * Canonical (frozen) shape of the injected property. Always embed a COPY\n * (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a\n * `__absolute_uri__` marker onto every subschema it dereferences, which\n * throws on a frozen object — and a single shared instance would be stamped\n * with one schema's URI while embedded in many.\n */\nexport const INTENT_PROPERTY: JsonSchemaType = Object.freeze<JsonSchemaType>({\n type: 'string',\n description: INTENT_DESCRIPTION,\n});\n\n/**\n * Discriminates the intent LABEL property from a tool's own business\n * parameter that merely shares the name: the label contract always opens\n * with the same instruction. Removal/sanitize passes must never strip a\n * parameter the tool actually needs.\n */\nexport function isIntentLabelProperty(property: unknown): boolean {\n if (property == null || typeof property !== 'object') {\n return false;\n }\n const record = property as { type?: unknown; description?: unknown };\n return (\n record.type === 'string' &&\n typeof record.description === 'string' &&\n record.description.startsWith(INTENT_LABEL_MARKER)\n );\n}\n\n/**\n * Schema shape accepted by {@link withoutIntent}.\n *\n * `required` is widened to `readonly string[]` because the SDK's own native\n * schemas are declared `as const` — their `required` is a readonly tuple, and\n * a mutable `string[]` parameter would reject the very schemas this helper\n * exists for (TS2345), forcing embedders to cast to use the advertised API.\n */\nexport type IntentStrippableSchema = Omit<JsonSchemaType, 'required'> & {\n required?: readonly string[];\n};\n\n/**\n * Returns a copy of `parameters` without the injected intent LABEL — the\n * opt-out for consumers that render no status label and should not pay for\n * the property.\n *\n * The SDK's native schemas carry the label unconditionally, so without this\n * an embedder has no lever at all: `withIntent` is applied at module scope.\n * Marker-guarded, so a tool's own business parameter named `intent` is never\n * removed. Returns the input unchanged when there is nothing to strip.\n *\n * `required` is pruned alongside the property: a schema that lists `intent`\n * as required (strict-mode normalization does exactly that, since OpenAI\n * strict function schemas require every property to appear in `required`)\n * would otherwise be left naming a property it no longer declares, which is\n * invalid JSON Schema and gets rejected by the provider instead of quietly\n * opting out.\n */\nexport function withoutIntent(parameters?: IntentStrippableSchema): JsonSchemaType | undefined {\n const props = parameters?.properties;\n if (parameters == null || props == null || !isIntentLabelProperty(props[INTENT_ARG])) {\n return parameters as JsonSchemaType | undefined;\n }\n const { [INTENT_ARG]: _omit, ...rest } = props;\n const next: JsonSchemaType = {\n ...(parameters as JsonSchemaType),\n properties: rest,\n };\n if (parameters.required != null) {\n const required = parameters.required.filter((key) => key !== INTENT_ARG);\n if (required.length > 0) {\n next.required = required;\n } else {\n delete next.required;\n }\n }\n return next;\n}\n\n/**\n * Returns a copy of the parameters schema with `intent` prepended as the\n * FIRST property (object key order is insertion order and every provider\n * serializer preserves it — first key in the schema means first key in the\n * streamed input). Never mutates the input; no-op when the schema already\n * declares `intent`. The property is not added to `required`.\n */\nexport function withIntent(parameters?: JsonSchemaType): JsonSchemaType {\n const existingProps = parameters?.properties ?? {};\n if (INTENT_ARG in existingProps) {\n return parameters as JsonSchemaType;\n }\n return {\n ...parameters,\n type: 'object',\n properties: { [INTENT_ARG]: { ...INTENT_PROPERTY }, ...existingProps },\n };\n}\n\n/**\n * Coerces tool-call args to an object, parsing a stringified JSON object\n * (some providers deliver args as a string). Returns undefined otherwise.\n */\nfunction coerceArgsObject(args: unknown): Record<string, unknown> | undefined {\n if (typeof args === 'object' && args !== null && !Array.isArray(args)) {\n return args as Record<string, unknown>;\n }\n if (typeof args === 'string' && args.trim().startsWith('{')) {\n try {\n const parsed = JSON.parse(args) as unknown;\n if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Reads the model-authored intent from tool-call args (handles stringified\n * args). Returns undefined when absent, empty, or not a string.\n */\nexport function readIntent(args: unknown): string | undefined {\n const value = coerceArgsObject(args)?.[INTENT_ARG];\n if (typeof value !== 'string') {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\n/**\n * Returns the args without the `intent` key so downstream consumers that did\n * not declare it never receive it. Parses stringified JSON object args;\n * returns the value unchanged when the key is absent.\n */\nexport function stripIntent(args: unknown): unknown {\n const obj = coerceArgsObject(args);\n if (!obj || !(INTENT_ARG in obj)) {\n return args;\n }\n const { [INTENT_ARG]: _omit, ...rest } = obj;\n return rest;\n}\n\n/**\n * Resolves the settled label for a call from its model-authored `intent` and\n * the tool's result fields, in precedence order:\n *\n * 1. `outcome` — full replacement authored by the tool.\n * 2. `outcome_patch` — first occurrence of `from` in the intent replaced\n * with `to` (case-sensitive); no-op when `from` is absent or empty.\n * 3. Otherwise the intent is returned UNCHANGED.\n *\n * There is deliberately no mechanical present-progressive→past-tense rewrite.\n * Such a transform can only be a closed list of English verbs, which makes it\n * wrong in three ways at once: it never fires for the non-English labels this\n * feature expects (the model answers in the user's language), it fires for\n * some sibling calls and not others inside one group — \"Searched…\" beside\n * \"Recording…\" — and it quietly enumerates a vocabulary in a feature whose\n * premise is that the sentence is free-form. Completion is conveyed by UI\n * state (the shimmer stopping, the icon settling), which is language-neutral\n * and always consistent; a tool that wants past tense says so explicitly via\n * `outcome` or `outcome_patch`.\n *\n * Returns undefined when there is neither an intent nor an outcome, so\n * callers fall back to their default label. Pure and dependency-free — host\n * UIs needing identical logic can import or mirror it.\n */\nexport function applyOutcome(\n intent: string | undefined,\n result?: { outcome?: string; outcome_patch?: OutcomePatch },\n): string | undefined {\n const outcome = result?.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return outcome;\n }\n if (intent == null || intent === '') {\n return undefined;\n }\n const patch = result?.outcome_patch;\n if (patch != null && patch.from !== '' && intent.includes(patch.from)) {\n /** Replacement callback keeps `to` verbatim — a direct string second\n * argument would interpret `$&`/`$'`-style tokens in tool-authored\n * text (e.g. labels derived from shell syntax). */\n return intent.replace(patch.from, () => patch.to);\n }\n return intent;\n}\n\n/**\n * Hard cap on an emitted outcome label. The label is a single progress line\n * in UI chrome; a tool that derives it from data (or a malformed patch)\n * must not be able to inflate completion events or persisted parts.\n */\nconst MAX_OUTCOME_CHARS = 256;\n\nfunction boundOutcomeLabel(label: string | undefined): string | undefined {\n if (label == null) {\n return undefined;\n }\n const singleLine = label.replace(/\\s+/g, ' ').trim();\n if (singleLine === '') {\n return undefined;\n }\n if (singleLine.length <= MAX_OUTCOME_CHARS) {\n return singleLine;\n }\n return `${singleLine.slice(0, MAX_OUTCOME_CHARS - 1)}…`;\n}\n\n/**\n * Resolves the settled label to emit on a completion event: only when the\n * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined\n * otherwise, so the wire never carries a label the host already has — a bare\n * intent needs no settled form, because it is displayed unchanged and the UI\n * conveys completion through its own state. Hosts must NOT rewrite it (see\n * {@link applyOutcome} for why a tense transform is deliberately absent). The\n * result is collapsed to a bounded single line before emission.\n *\n * For failed calls (`isError`), only tool-AUTHORED text may label the call:\n * an explicit `outcome`, or a patch whose `from` actually matches the intent.\n * An unmatched patch resolves to undefined rather than silently reusing the\n * in-flight intent, so a failure is never labelled as though it succeeded.\n */\nexport function resolveToolOutcome(\n args: unknown,\n fields?: { outcome?: string; outcome_patch?: OutcomePatch } | null,\n options?: { isError?: boolean },\n): string | undefined {\n if (fields == null || (fields.outcome == null && fields.outcome_patch == null)) {\n return undefined;\n }\n if (options?.isError !== true) {\n return boundOutcomeLabel(applyOutcome(readIntent(args), fields));\n }\n const outcome = fields.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return boundOutcomeLabel(outcome);\n }\n const intent = readIntent(args);\n const patch = fields.outcome_patch;\n if (\n intent != null &&\n patch != null &&\n patch.from !== '' &&\n intent.includes(patch.from)\n ) {\n return boundOutcomeLabel(intent.replace(patch.from, () => patch.to));\n }\n return undefined;\n}\n\n/**\n * Reads the outcome fields off a tool-execution result: the typed\n * `outcome`/`outcome_patch` fields when present, else the artifact channel\n * (see {@link readOutcomeFields}) — so a `content_and_artifact` tool authors\n * its label the same way on the direct and event-driven paths.\n */\nexport function outcomeFieldsFromResult(result: {\n outcome?: string;\n outcome_patch?: OutcomePatch;\n artifact?: unknown;\n}): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (result.outcome != null || result.outcome_patch != null) {\n return result;\n }\n return readOutcomeFields(result.artifact);\n}\n\n/**\n * Extracts validated `outcome`/`outcome_patch` fields from an arbitrary\n * value — the artifact channel through which an in-process\n * `content_and_artifact` tool authors its settled label. Returns undefined\n * when neither field is usable.\n */\nexport function readOutcomeFields(\n source: unknown,\n): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (source == null || typeof source !== 'object' || Array.isArray(source)) {\n return undefined;\n }\n const record = source as Record<string, unknown>;\n const outcome =\n typeof record.outcome === 'string' && record.outcome.trim() !== ''\n ? record.outcome\n : undefined;\n let outcome_patch: OutcomePatch | undefined;\n const rawPatch = record.outcome_patch;\n if (rawPatch != null && typeof rawPatch === 'object' && !Array.isArray(rawPatch)) {\n const patch = rawPatch as Record<string, unknown>;\n if (typeof patch.from === 'string' && typeof patch.to === 'string') {\n outcome_patch = { from: patch.from, to: patch.to };\n }\n }\n if (outcome == null && outcome_patch == null) {\n return undefined;\n }\n return { outcome, outcome_patch };\n}\n"],"mappings":";;AAwBA,MAAa,aAAa;;;;;;;;;;;;AAa1B,MAAa,sBAAsB;;;;;;;;;;;AAYnC,MAAa,qBACX,GAAG,oBAAoB;;;;;;;;AAYzB,MAAa,kBAAkC,OAAO,OAAuB;CAC3E,MAAM;CACN,aAAa;AACf,CAAC;;;;;;;AAQD,SAAgB,sBAAsB,UAA4B;CAChE,IAAI,YAAY,QAAQ,OAAO,aAAa,UAC1C,OAAO;CAET,MAAM,SAAS;CACf,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,gBAAgB,YAC9B,OAAO,YAAY,WAAA,+BAA8B;AAErD;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,cAAc,YAAiE;CAC7F,MAAM,QAAQ,YAAY;CAC1B,IAAI,cAAc,QAAQ,SAAS,QAAQ,CAAC,sBAAsB,MAAA,SAAiB,GACjF,O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QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACtE;CAEF,MAAM,SAAS;CACf,MAAM,UACJ,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,KAAK,MAAM,KAC5D,OAAO,UACP,KAAA;CACN,IAAI;CACJ,MAAM,WAAW,OAAO;CACxB,IAAI,YAAY,QAAQ,OAAO,aAAa,YAAY,CAAC,MAAM,QAAQ,QAAQ,GAAG;EAChF,MAAM,QAAQ;EACd,IAAI,OAAO,MAAM,SAAS,YAAY,OAAO,MAAM,OAAO,UACxD,gBAAgB;GAAE,MAAM,MAAM;GAAM,IAAI,MAAM;EAAG;CAErD;CACA,IAAI,WAAW,QAAQ,iBAAiB,MACtC;CAEF,OAAO;EAAE;EAAS;CAAc;AAClC"}
@@ -24,12 +24,12 @@ let _langchain_core_tools = require("@langchain/core/tools");
24
24
  *
25
25
  * A caught provider or processing failure is reported through `data.error`
26
26
  * while the tool still returns NORMALLY, so that case must author its own
27
- * label: the `ToolMessage` carries success status, and a bare intent would
28
- * otherwise settle mechanically from "Searching…" to "Searched…" and present
29
- * a failed search as a successful one.
27
+ * label: the `ToolMessage` carries success status, so without an authored
28
+ * outcome the in-flight intent ("Searching…") would stand as the settled
29
+ * label and present a failed search as an ordinary one.
30
30
  *
31
- * Returns undefined for a genuine zero-result search, leaving the host's
32
- * mechanical past-tense transform to label it.
31
+ * Returns undefined for a genuine zero-result search, leaving the
32
+ * model-authored intent to stand unchanged as the label.
33
33
  */
34
34
  function resolveSearchOutcome(data, query) {
35
35
  if (data.error != null && data.error !== "") return `Search failed for "${query}"`;
@@ -1 +1 @@
1
- {"version":3,"file":"tool.cjs","names":["expandHighlights","params","formatResultsForLLM","WebSearchToolName","WebSearchToolDescription","createDefaultLogger","INTENT_PROPERTY","querySchema","dateSchema","imagesSchema","videosSchema","newsSchema","countrySchema","createSearchAPI","createSerperScraper","createTavilyScraper","createCrwScraper","createKeenableScraper","createFirecrawlScraper","createReranker","createSourceProcessor"],"sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["import { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from './types';\nimport {\n WebSearchToolDescription,\n WebSearchToolName,\n countrySchema,\n imagesSchema,\n videosSchema,\n querySchema,\n dateSchema,\n newsSchema,\n DATE_RANGE,\n} from './schema';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createKeenableScraper } from './keenable-scraper';\nimport { createSerperScraper } from './serper-scraper';\nimport { createTavilyScraper } from './tavily-scraper';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { INTENT_PROPERTY } from '@/tools/intentArg';\nimport { createCrwScraper } from './crw-scraper';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createDefaultLogger } from './utils';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\n/**\n * Settled label for a `web_search` call's intent (see `intentArg.ts`).\n *\n * Counts the result kinds `formatResultsForLLM` actually renders —\n * `references` only tracks links embedded in extracted highlights, so it\n * undercounts ordinary results and can overcount when one highlight embeds\n * several links.\n *\n * A caught provider or processing failure is reported through `data.error`\n * while the tool still returns NORMALLY, so that case must author its own\n * label: the `ToolMessage` carries success status, and a bare intent would\n * otherwise settle mechanically from \"Searching…\" to \"Searched…\" and present\n * a failed search as a successful one.\n *\n * Returns undefined for a genuine zero-result search, leaving the host's\n * mechanical past-tense transform to label it.\n */\nexport function resolveSearchOutcome(\n data: t.SearchResultData,\n query: string\n): string | undefined {\n if (data.error != null && data.error !== '') {\n return `Search failed for \"${query}\"`;\n }\n const count =\n (data.organic?.length ?? 0) +\n (data.topStories?.length ?? 0) +\n (data.news?.length ?? 0) +\n (data.images?.length ?? 0) +\n (data.videos?.length ?? 0) +\n (data.places?.length ?? 0) +\n (data.peopleAlsoAsk?.length ?? 0) +\n (data.knowledgeGraph != null ? 1 : 0) +\n (data.answerBox != null ? 1 : 0);\n if (count === 0) {\n return undefined;\n }\n return `Found ${count} result${count === 1 ? '' : 's'} for \"${query}\"`;\n}\n\n/**\n * Executes parallel searches and merges the results,\n * deduplicating top stories by link\n */\nexport async function executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images,\n videos,\n news,\n logger,\n}: {\n searchAPI: ReturnType<typeof createSearchAPI>;\n query: string;\n date?: DATE_RANGE;\n country?: string;\n safeSearch: t.SearchToolConfig['safeSearch'];\n images: boolean;\n videos: boolean;\n news: boolean;\n logger: t.Logger;\n}): Promise<t.SearchResult> {\n // Prepare all search tasks to run in parallel\n const searchTasks: Promise<t.SearchResult>[] = [\n // Main search\n searchAPI.getSources({\n query,\n date,\n country,\n safeSearch,\n }),\n ];\n\n if (images) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'images',\n })\n .catch((error) => {\n logger.error('Error fetching images:', error);\n return {\n success: false,\n error: `Images search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (videos) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'videos',\n })\n .catch((error) => {\n logger.error('Error fetching videos:', error);\n return {\n success: false,\n error: `Videos search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (news) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'news',\n })\n .catch((error) => {\n logger.error('Error fetching news:', error);\n return {\n success: false,\n error: `News search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n\n // Run all searches in parallel\n const results = await Promise.all(searchTasks);\n\n // Get the main search result (first result)\n const mainResult = results[0];\n if (!mainResult.success) {\n throw new Error(mainResult.error ?? 'Search failed');\n }\n\n // Merge additional results with the main results\n const mergedResults = { ...mainResult.data };\n\n // Convert existing news to topStories if present\n if (mergedResults.news !== undefined && mergedResults.news.length > 0) {\n const existingNewsAsTopStories = mergedResults.news\n .filter((newsItem) => newsItem.link !== undefined && newsItem.link !== '')\n .map((newsItem) => ({\n title: newsItem.title ?? '',\n link: newsItem.link ?? '',\n source: newsItem.source ?? '',\n date: newsItem.date ?? '',\n imageUrl: newsItem.imageUrl ?? '',\n processed: false,\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...existingNewsAsTopStories,\n ];\n delete mergedResults.news;\n }\n\n results.slice(1).forEach((result) => {\n if (result.success && result.data !== undefined) {\n if (result.data.images !== undefined && result.data.images.length > 0) {\n mergedResults.images = [\n ...(mergedResults.images ?? []),\n ...result.data.images,\n ];\n }\n if (result.data.videos !== undefined && result.data.videos.length > 0) {\n mergedResults.videos = [\n ...(mergedResults.videos ?? []),\n ...result.data.videos,\n ];\n }\n if (result.data.news !== undefined && result.data.news.length > 0) {\n const newsAsTopStories = result.data.news.map((newsItem) => ({\n ...newsItem,\n link: newsItem.link ?? '',\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...newsAsTopStories,\n ];\n }\n }\n });\n\n if (\n mergedResults.topStories !== undefined &&\n mergedResults.topStories.length > 1\n ) {\n /** The main search's own news results and the parallel news sub-search\n * frequently return the same stories — keep the first occurrence of each\n * link so duplicates aren't scraped, reranked, and formatted repeatedly */\n const seenLinks = new Set<string>();\n mergedResults.topStories = mergedResults.topStories.filter((story) => {\n if (!story.link || seenLinks.has(story.link)) {\n return false;\n }\n seenLinks.add(story.link);\n return true;\n });\n }\n\n return { success: true, data: mergedResults };\n}\n\nfunction createSearchProcessor({\n searchAPI,\n safeSearch,\n supportsImages,\n supportsVideos,\n supportsNews,\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n}: {\n safeSearch: t.SearchToolConfig['safeSearch'];\n supportsImages: boolean;\n supportsVideos: boolean;\n supportsNews: boolean;\n searchAPI: ReturnType<typeof createSearchAPI>;\n sourceProcessor: ReturnType<typeof createSourceProcessor>;\n onGetHighlights: t.SearchToolConfig['onGetHighlights'];\n mainExpandBy: t.SearchToolConfig['mainExpandBy'];\n separatorExpandBy: t.SearchToolConfig['separatorExpandBy'];\n logger: t.Logger;\n}) {\n return async function ({\n query,\n date,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n images = false,\n videos = false,\n news = false,\n }: {\n query: string;\n country?: string;\n date?: DATE_RANGE;\n proMode?: boolean;\n maxSources?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n }): Promise<t.SearchResultData> {\n try {\n // Execute parallel searches and merge results\n const searchResult = await executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images: supportsImages && images,\n videos: supportsVideos && videos,\n news: supportsNews && news,\n logger,\n });\n\n onSearchResults?.(searchResult);\n\n const processedSources = await sourceProcessor.processSources({\n query,\n news,\n result: searchResult,\n proMode,\n onGetHighlights,\n numElements: maxSources,\n });\n\n return expandHighlights(\n processedSources,\n mainExpandBy,\n separatorExpandBy\n );\n } catch (error) {\n logger.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n videos: [],\n news: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n}\n\nfunction createOnSearchResults({\n runnableConfig,\n onSearchResults,\n}: {\n runnableConfig: RunnableConfig;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}) {\n return function (results: t.SearchResult): void {\n if (!onSearchResults) {\n return;\n }\n onSearchResults(results, runnableConfig);\n };\n}\n\nfunction createTool({\n schema,\n search,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n}: {\n schema: Record<string, unknown>;\n search: ReturnType<typeof createSearchProcessor>;\n maxOutputChars?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}): DynamicStructuredTool {\n return tool(\n async (rawParams, runnableConfig) => {\n const params = rawParams as SearchToolParams;\n const { query, date, country: _c, images, videos, news } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n date,\n country,\n images,\n videos,\n news,\n onSearchResults: createOnSearchResults({\n runnableConfig,\n onSearchResults: _onSearchResults,\n }),\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(\n turn,\n searchResult,\n maxOutputChars\n );\n const data: t.SearchResultData = { turn, ...searchResult, references };\n const outcome = resolveSearchOutcome(data, query);\n return [\n output,\n { [Constants.WEB_SEARCH]: data, ...(outcome != null && { outcome }) },\n ];\n },\n {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Creates a search tool with configurable search and scraper providers.\n *\n * Search providers: Serper (Google results), SearXNG (self-hosted meta-search), Tavily (AI-optimized), fastCRW (Firecrawl-compatible, self-host or cloud).\n * Scraper providers: Firecrawl (default, full-featured), Serper (lightweight), Tavily (batch extraction), fastCRW (Firecrawl-compatible, self-host or cloud).\n *\n * The country schema field is exposed to the LLM for providers that support localized results.\n */\n/** Input params type for search tool */\ninterface SearchToolParams {\n query: string;\n date?: DATE_RANGE;\n country?: string;\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n}\n\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilyExtractUrl,\n tavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n keenableScraperOptions,\n rerankerType = 'cohere',\n rerankerTimeout,\n topResults = 5,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n mainExpandBy,\n separatorExpandBy,\n maxOutputChars,\n strategies = ['no_extraction'],\n filterContent = true,\n safeSearch = 1,\n scraperProvider = 'firecrawl',\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlVersion,\n firecrawlOptions,\n serperScraperOptions,\n tavilyScraperOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n crwScraperOptions,\n scraperTimeout,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n onGetHighlights,\n } = config;\n\n const logger = config.logger || createDefaultLogger();\n const effectiveTavilySearchOptions =\n searchProvider === 'tavily' && config.safeSearch != null\n ? {\n ...tavilySearchOptions,\n safeSearch: config.safeSearch !== 0,\n }\n : tavilySearchOptions;\n\n const schemaProperties: Record<string, unknown> = {\n intent: { ...INTENT_PROPERTY },\n query: querySchema,\n date: dateSchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n };\n\n if (searchProvider === 'serper' || searchProvider === 'tavily') {\n schemaProperties.country = countrySchema;\n }\n\n const toolSchema = {\n type: 'object',\n properties: schemaProperties,\n required: ['query'],\n };\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilySearchOptions: effectiveTavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n });\n\n /** Create scraper based on scraperProvider */\n let scraperInstance: t.BaseScraper;\n\n if (scraperProvider === 'serper') {\n scraperInstance = createSerperScraper({\n ...serperScraperOptions,\n apiKey: serperApiKey,\n timeout: scraperTimeout ?? serperScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'tavily') {\n scraperInstance = createTavilyScraper({\n ...tavilyScraperOptions,\n apiKey:\n tavilyScraperOptions?.apiKey ??\n tavilyApiKey ??\n process.env.TAVILY_API_KEY,\n apiUrl: tavilyScraperOptions?.apiUrl ?? tavilyExtractUrl,\n timeout: scraperTimeout ?? tavilyScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'crw') {\n scraperInstance = createCrwScraper({\n ...crwScraperOptions,\n apiKey: crwScraperOptions?.apiKey ?? crwApiKey ?? process.env.CRW_API_KEY,\n apiUrl: crwScraperOptions?.apiUrl ?? crwApiUrl,\n timeout: scraperTimeout ?? crwScraperOptions?.timeout,\n formats: crwScraperOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n } else if (scraperProvider === 'keenable') {\n scraperInstance = createKeenableScraper({\n ...keenableScraperOptions,\n apiKey: keenableScraperOptions?.apiKey ?? keenableApiKey,\n timeout: scraperTimeout ?? keenableScraperOptions?.timeout,\n attributionTitle:\n keenableScraperOptions?.attributionTitle ??\n keenableSearchOptions?.attributionTitle,\n logger,\n });\n } else {\n scraperInstance = createFirecrawlScraper({\n ...firecrawlOptions,\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n version: firecrawlVersion,\n timeout: scraperTimeout ?? firecrawlOptions?.timeout,\n formats: firecrawlOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n }\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n rerankerTimeout,\n logger,\n });\n\n if (!selectedReranker) {\n logger.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n strategies,\n filterContent,\n logger,\n },\n scraperInstance\n );\n\n const search = createSearchProcessor({\n searchAPI,\n safeSearch,\n // Keenable is organic-only: its API ignores `type`, so image/news\n // sub-searches would spend rate limit and merge nothing.\n supportsImages: searchProvider !== 'keenable',\n supportsVideos:\n searchProvider !== 'tavily' &&\n searchProvider !== 'keenable' &&\n searchProvider !== 'crw',\n supportsNews: searchProvider !== 'keenable',\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n });\n\n return createTool({\n search,\n schema: toolSchema,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,qBACd,MACA,OACoB;CACpB,IAAI,KAAK,SAAS,QA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AC,YAAY,SAAS;EAC5D;CACF,CAAC;CAGH,MAAM,mBAAmBC,kBAAAA,eAAe;EACtC;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,IAAI,CAAC,kBACH,OAAO,KAAK,8CAA8C;CAG5D,MAAM,kBAAkBC,eAAAA,sBACtB;EACE,UAAU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;CACF,GACA,eACF;CAoBA,OAAO,WAAW;EAChB,QAnBa,sBAAsB;GACnC;GACA;GAGA,gBAAgB,mBAAmB;GACnC,gBACE,mBAAmB,YACnB,mBAAmB,cACnB,mBAAmB;GACrB,cAAc,mBAAmB;GACjC;GACA;GACA;GACA;GACA;EACF,CAGO;EACL,QAAQ;EACR;EACA,iBAAiB;CACnB,CAAC;AACH"}
1
+ {"version":3,"file":"tool.cjs","names":["expandHighlights","params","formatResultsForLLM","WebSearchToolName","WebSearchToolDescription","createDefaultLogger","INTENT_PROPERTY","querySchema","dateSchema","imagesSchema","videosSchema","newsSchema","countrySchema","createSearchAPI","createSerperScraper","createTavilyScraper","createCrwScraper","createKeenableScraper","createFirecrawlScraper","createReranker","createSourceProcessor"],"sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["import { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from './types';\nimport {\n WebSearchToolDescription,\n WebSearchToolName,\n countrySchema,\n imagesSchema,\n videosSchema,\n querySchema,\n dateSchema,\n newsSchema,\n DATE_RANGE,\n} from './schema';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createKeenableScraper } from './keenable-scraper';\nimport { createSerperScraper } from './serper-scraper';\nimport { createTavilyScraper } from './tavily-scraper';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { INTENT_PROPERTY } from '@/tools/intentArg';\nimport { createCrwScraper } from './crw-scraper';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createDefaultLogger } from './utils';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\n/**\n * Settled label for a `web_search` call's intent (see `intentArg.ts`).\n *\n * Counts the result kinds `formatResultsForLLM` actually renders —\n * `references` only tracks links embedded in extracted highlights, so it\n * undercounts ordinary results and can overcount when one highlight embeds\n * several links.\n *\n * A caught provider or processing failure is reported through `data.error`\n * while the tool still returns NORMALLY, so that case must author its own\n * label: the `ToolMessage` carries success status, so without an authored\n * outcome the in-flight intent (\"Searching…\") would stand as the settled\n * label and present a failed search as an ordinary one.\n *\n * Returns undefined for a genuine zero-result search, leaving the\n * model-authored intent to stand unchanged as the label.\n */\nexport function resolveSearchOutcome(\n data: t.SearchResultData,\n query: string\n): string | undefined {\n if (data.error != null && data.error !== '') {\n return `Search failed for \"${query}\"`;\n }\n const count =\n (data.organic?.length ?? 0) +\n (data.topStories?.length ?? 0) +\n (data.news?.length ?? 0) +\n (data.images?.length ?? 0) +\n (data.videos?.length ?? 0) +\n (data.places?.length ?? 0) +\n (data.peopleAlsoAsk?.length ?? 0) +\n (data.knowledgeGraph != null ? 1 : 0) +\n (data.answerBox != null ? 1 : 0);\n if (count === 0) {\n return undefined;\n }\n return `Found ${count} result${count === 1 ? '' : 's'} for \"${query}\"`;\n}\n\n/**\n * Executes parallel searches and merges the results,\n * deduplicating top stories by link\n */\nexport async function executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images,\n videos,\n news,\n logger,\n}: {\n searchAPI: ReturnType<typeof createSearchAPI>;\n query: string;\n date?: DATE_RANGE;\n country?: string;\n safeSearch: t.SearchToolConfig['safeSearch'];\n images: boolean;\n videos: boolean;\n news: boolean;\n logger: t.Logger;\n}): Promise<t.SearchResult> {\n // Prepare all search tasks to run in parallel\n const searchTasks: Promise<t.SearchResult>[] = [\n // Main search\n searchAPI.getSources({\n query,\n date,\n country,\n safeSearch,\n }),\n ];\n\n if (images) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'images',\n })\n .catch((error) => {\n logger.error('Error fetching images:', error);\n return {\n success: false,\n error: `Images search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (videos) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'videos',\n })\n .catch((error) => {\n logger.error('Error fetching videos:', error);\n return {\n success: false,\n error: `Videos search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (news) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'news',\n })\n .catch((error) => {\n logger.error('Error fetching news:', error);\n return {\n success: false,\n error: `News search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n\n // Run all searches in parallel\n const results = await Promise.all(searchTasks);\n\n // Get the main search result (first result)\n const mainResult = results[0];\n if (!mainResult.success) {\n throw new Error(mainResult.error ?? 'Search failed');\n }\n\n // Merge additional results with the main results\n const mergedResults = { ...mainResult.data };\n\n // Convert existing news to topStories if present\n if (mergedResults.news !== undefined && mergedResults.news.length > 0) {\n const existingNewsAsTopStories = mergedResults.news\n .filter((newsItem) => newsItem.link !== undefined && newsItem.link !== '')\n .map((newsItem) => ({\n title: newsItem.title ?? '',\n link: newsItem.link ?? '',\n source: newsItem.source ?? '',\n date: newsItem.date ?? '',\n imageUrl: newsItem.imageUrl ?? '',\n processed: false,\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...existingNewsAsTopStories,\n ];\n delete mergedResults.news;\n }\n\n results.slice(1).forEach((result) => {\n if (result.success && result.data !== undefined) {\n if (result.data.images !== undefined && result.data.images.length > 0) {\n mergedResults.images = [\n ...(mergedResults.images ?? []),\n ...result.data.images,\n ];\n }\n if (result.data.videos !== undefined && result.data.videos.length > 0) {\n mergedResults.videos = [\n ...(mergedResults.videos ?? []),\n ...result.data.videos,\n ];\n }\n if (result.data.news !== undefined && result.data.news.length > 0) {\n const newsAsTopStories = result.data.news.map((newsItem) => ({\n ...newsItem,\n link: newsItem.link ?? '',\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...newsAsTopStories,\n ];\n }\n }\n });\n\n if (\n mergedResults.topStories !== undefined &&\n mergedResults.topStories.length > 1\n ) {\n /** The main search's own news results and the parallel news sub-search\n * frequently return the same stories — keep the first occurrence of each\n * link so duplicates aren't scraped, reranked, and formatted repeatedly */\n const seenLinks = new Set<string>();\n mergedResults.topStories = mergedResults.topStories.filter((story) => {\n if (!story.link || seenLinks.has(story.link)) {\n return false;\n }\n seenLinks.add(story.link);\n return true;\n });\n }\n\n return { success: true, data: mergedResults };\n}\n\nfunction createSearchProcessor({\n searchAPI,\n safeSearch,\n supportsImages,\n supportsVideos,\n supportsNews,\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n}: {\n safeSearch: t.SearchToolConfig['safeSearch'];\n supportsImages: boolean;\n supportsVideos: boolean;\n supportsNews: boolean;\n searchAPI: ReturnType<typeof createSearchAPI>;\n sourceProcessor: ReturnType<typeof createSourceProcessor>;\n onGetHighlights: t.SearchToolConfig['onGetHighlights'];\n mainExpandBy: t.SearchToolConfig['mainExpandBy'];\n separatorExpandBy: t.SearchToolConfig['separatorExpandBy'];\n logger: t.Logger;\n}) {\n return async function ({\n query,\n date,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n images = false,\n videos = false,\n news = false,\n }: {\n query: string;\n country?: string;\n date?: DATE_RANGE;\n proMode?: boolean;\n maxSources?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n }): Promise<t.SearchResultData> {\n try {\n // Execute parallel searches and merge results\n const searchResult = await executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images: supportsImages && images,\n videos: supportsVideos && videos,\n news: supportsNews && news,\n logger,\n });\n\n onSearchResults?.(searchResult);\n\n const processedSources = await sourceProcessor.processSources({\n query,\n news,\n result: searchResult,\n proMode,\n onGetHighlights,\n numElements: maxSources,\n });\n\n return expandHighlights(\n processedSources,\n mainExpandBy,\n separatorExpandBy\n );\n } catch (error) {\n logger.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n videos: [],\n news: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n}\n\nfunction createOnSearchResults({\n runnableConfig,\n onSearchResults,\n}: {\n runnableConfig: RunnableConfig;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}) {\n return function (results: t.SearchResult): void {\n if (!onSearchResults) {\n return;\n }\n onSearchResults(results, runnableConfig);\n };\n}\n\nfunction createTool({\n schema,\n search,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n}: {\n schema: Record<string, unknown>;\n search: ReturnType<typeof createSearchProcessor>;\n maxOutputChars?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}): DynamicStructuredTool {\n return tool(\n async (rawParams, runnableConfig) => {\n const params = rawParams as SearchToolParams;\n const { query, date, country: _c, images, videos, news } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n date,\n country,\n images,\n videos,\n news,\n onSearchResults: createOnSearchResults({\n runnableConfig,\n onSearchResults: _onSearchResults,\n }),\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(\n turn,\n searchResult,\n maxOutputChars\n );\n const data: t.SearchResultData = { turn, ...searchResult, references };\n const outcome = resolveSearchOutcome(data, query);\n return [\n output,\n { [Constants.WEB_SEARCH]: data, ...(outcome != null && { outcome }) },\n ];\n },\n {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Creates a search tool with configurable search and scraper providers.\n *\n * Search providers: Serper (Google results), SearXNG (self-hosted meta-search), Tavily (AI-optimized), fastCRW (Firecrawl-compatible, self-host or cloud).\n * Scraper providers: Firecrawl (default, full-featured), Serper (lightweight), Tavily (batch extraction), fastCRW (Firecrawl-compatible, self-host or cloud).\n *\n * The country schema field is exposed to the LLM for providers that support localized results.\n */\n/** Input params type for search tool */\ninterface SearchToolParams {\n query: string;\n date?: DATE_RANGE;\n country?: string;\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n}\n\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilyExtractUrl,\n tavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n keenableScraperOptions,\n rerankerType = 'cohere',\n rerankerTimeout,\n topResults = 5,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n mainExpandBy,\n separatorExpandBy,\n maxOutputChars,\n strategies = ['no_extraction'],\n filterContent = true,\n safeSearch = 1,\n scraperProvider = 'firecrawl',\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlVersion,\n firecrawlOptions,\n serperScraperOptions,\n tavilyScraperOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n crwScraperOptions,\n scraperTimeout,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n onGetHighlights,\n } = config;\n\n const logger = config.logger || createDefaultLogger();\n const effectiveTavilySearchOptions =\n searchProvider === 'tavily' && config.safeSearch != null\n ? {\n ...tavilySearchOptions,\n safeSearch: config.safeSearch !== 0,\n }\n : tavilySearchOptions;\n\n const schemaProperties: Record<string, unknown> = {\n intent: { ...INTENT_PROPERTY },\n query: querySchema,\n date: dateSchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n };\n\n if (searchProvider === 'serper' || searchProvider === 'tavily') {\n schemaProperties.country = countrySchema;\n }\n\n const toolSchema = {\n type: 'object',\n properties: schemaProperties,\n required: ['query'],\n };\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilySearchOptions: effectiveTavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n });\n\n /** Create scraper based on scraperProvider */\n let scraperInstance: t.BaseScraper;\n\n if (scraperProvider === 'serper') {\n scraperInstance = createSerperScraper({\n ...serperScraperOptions,\n apiKey: serperApiKey,\n timeout: scraperTimeout ?? serperScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'tavily') {\n scraperInstance = createTavilyScraper({\n ...tavilyScraperOptions,\n apiKey:\n tavilyScraperOptions?.apiKey ??\n tavilyApiKey ??\n process.env.TAVILY_API_KEY,\n apiUrl: tavilyScraperOptions?.apiUrl ?? tavilyExtractUrl,\n timeout: scraperTimeout ?? tavilyScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'crw') {\n scraperInstance = createCrwScraper({\n ...crwScraperOptions,\n apiKey: crwScraperOptions?.apiKey ?? crwApiKey ?? process.env.CRW_API_KEY,\n apiUrl: crwScraperOptions?.apiUrl ?? crwApiUrl,\n timeout: scraperTimeout ?? crwScraperOptions?.timeout,\n formats: crwScraperOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n } else if (scraperProvider === 'keenable') {\n scraperInstance = createKeenableScraper({\n ...keenableScraperOptions,\n apiKey: keenableScraperOptions?.apiKey ?? keenableApiKey,\n timeout: scraperTimeout ?? keenableScraperOptions?.timeout,\n attributionTitle:\n keenableScraperOptions?.attributionTitle ??\n keenableSearchOptions?.attributionTitle,\n logger,\n });\n } else {\n scraperInstance = createFirecrawlScraper({\n ...firecrawlOptions,\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n version: firecrawlVersion,\n timeout: scraperTimeout ?? firecrawlOptions?.timeout,\n formats: firecrawlOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n }\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n rerankerTimeout,\n logger,\n });\n\n if (!selectedReranker) {\n logger.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n strategies,\n filterContent,\n logger,\n },\n scraperInstance\n );\n\n const search = createSearchProcessor({\n searchAPI,\n safeSearch,\n // Keenable is organic-only: its API ignores `type`, so image/news\n // sub-searches would spend rate limit and merge nothing.\n supportsImages: searchProvider !== 'keenable',\n supportsVideos:\n searchProvider !== 'tavily' &&\n searchProvider !== 'keenable' &&\n searchProvider !== 'crw',\n supportsNews: searchProvider !== 'keenable',\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n });\n\n return createTool({\n search,\n schema: toolSchema,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,qBACd,MACA,OACoB;CACpB,IAAI,KAAK,SAAS,QAAQ,KAAK,UAAU,IACvC,OAAO,sBAAsB,MAAM;CAErC,MAAM,SACH,KAAK,SAAS,UAAU,MACxB,KAAK,YAAY,UAAU,MAC3B,KAAK,MAAM,UAAU,MACrB,KAAK,QAAQ,UAAU,MACvB,KAAK,QAAQ,UAAU,MACvB,KAAK,QAAQ,UAAU,MACvB,KAAK,eAAe,UAAU,MAC9B,KAAK,kBAAkB,OAAO,IAAI,MAClC,KAAK,aAAa,OAAO,IAAI;CAChC,IAAI,UAAU,GACZ;CAEF,OAAO,SAAS,MAAM,SAAS,UAAU,IAAI,KAAK,IAAI,QAAQ,MAAM;AACtE;;;;;AAMA,eAAsB,wBAAwB,EAC5C,WACA,OACA,MACA,SACA,YACA,QACA,QACA,MACA,UAW0B;CAE1B,MAAM,cAAyC,CAE7C,UAAU,WAAW;EACnB;EACA;EACA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import "./messages/index.mjs";
25
25
  import { joinKeys, resetIfNotEmpty } from "./utils/graph.mjs";
26
26
  import { isAnthropicLike, isGoogleLike, isOpenAILike } from "./utils/llm.mjs";
27
27
  import { handleServerToolResult, handleToolCallChunks, handleToolCalls, toolResultTypes } from "./tools/handlers.mjs";
28
- import { INTENT_ARG, INTENT_DESCRIPTION, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent } from "./tools/intentArg.mjs";
28
+ import { INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent, withoutIntent } from "./tools/intentArg.mjs";
29
29
  import { ChatModelStreamHandler, SDK_STREAM_DISPATCH, createContentAggregator, dispatchesChatModelStream, getChunkContent } from "./stream.mjs";
30
30
  import { HandlerRegistry, LLMStreamHandler, ModelEndHandler, TestChatStreamHandler, TestLLMStreamHandler, ToolEndHandler, composeEventHandlers, createMetadataAggregator } from "./events.mjs";
31
31
  import { createHandlers } from "./utils/handlers.mjs";
@@ -102,4 +102,4 @@ import { Runnable, RunnableLambda, RunnableSequence } from "./langchain/runnable
102
102
  import { DynamicStructuredTool, StructuredTool, Tool, tool } from "./langchain/tools.mjs";
103
103
  import "./langchain/index.mjs";
104
104
  import { BaseCheckpointSaver, Command, INTERRUPT, MemorySaver, interrupt, isInterrupted } from "@langchain/langgraph";
105
- export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeEventHandlers, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldTriggerSummarization, sleep, spawnLocalProcess, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole };
105
+ export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeEventHandlers, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldTriggerSummarization, sleep, spawnLocalProcess, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole, withoutIntent };