@dawn-ai/langchain 0.1.5 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dawn contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,10 +1,13 @@
1
+ <p>
2
+ <img src="https://raw.githubusercontent.com/cacheplane/dawnai/main/docs/brand/dawn-logo-horizontal-black-on-white.png" alt="Dawn" width="180" />
3
+ </p>
4
+
1
5
  # @dawn-ai/langchain
2
6
 
3
- LangChain backend adapter for Dawn `chain` route kind.
7
+ LangChain backend adapters Dawn uses to materialize `chain` and `agent` routes (tool conversion, streaming, retry).
8
+
9
+ This is an internal Dawn workspace package. For Dawn documentation, see <https://dawn-ai.org>.
4
10
 
5
- Public surface:
6
- - `ChainAdapter` — `BackendAdapter` implementation for LCEL runnables
7
- - `convertTools()` — converts Dawn tools to LangChain `DynamicStructuredTool`
8
- - `toolLoop()` — Dawn-owned ReAct tool execution loop (no AgentExecutor dependency)
11
+ ## License
9
12
 
10
- This package enables Dawn routes to use LangChain LCEL chains with filesystem-driven tool discovery and Dawn-owned execution semantics.
13
+ MIT
@@ -1,8 +1,10 @@
1
+ import type { RetryConfig } from "@dawn-ai/sdk";
1
2
  import { type ResolvedStateField } from "./state-adapter.js";
2
3
  interface DawnToolDefinition {
3
4
  readonly description?: string;
4
5
  readonly name: string;
5
6
  readonly run: (input: unknown, context: {
7
+ readonly middleware?: Readonly<Record<string, unknown>>;
6
8
  readonly signal: AbortSignal;
7
9
  }) => Promise<unknown> | unknown;
8
10
  readonly schema?: unknown;
@@ -14,6 +16,8 @@ export interface AgentStreamChunk {
14
16
  export interface AgentOptions {
15
17
  readonly entry: unknown;
16
18
  readonly input: unknown;
19
+ readonly middlewareContext?: Readonly<Record<string, unknown>>;
20
+ readonly retry?: RetryConfig;
17
21
  readonly routeParamNames: readonly string[];
18
22
  readonly signal: AbortSignal;
19
23
  readonly stateFields?: readonly ResolvedStateField[];
@@ -1 +1 @@
1
- {"version":3,"file":"agent-adapter.d.ts","sourceRoot":"","sources":["../src/agent-adapter.ts"],"names":[],"mappings":"AAGA,OAAO,EAA0B,KAAK,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAGpF,UAAU,kBAAkB;IAC1B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,CACZ,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;KAAE,KACtC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAC1B;AAuDD,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,OAAO,GAAG,WAAW,GAAG,aAAa,GAAG,MAAM,CAAA;IAC7D,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CACvB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;IACvB,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAA;IAC3C,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;IAC5B,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,kBAAkB,EAAE,CAAA;IACpD,QAAQ,CAAC,KAAK,EAAE,SAAS,kBAAkB,EAAE,CAAA;CAC9C;AAED,wBAAsB,YAAY,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAQ1E;AAED,wBAAuB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,cAAc,CAAC,gBAAgB,CAAC,CAwB1F"}
1
+ {"version":3,"file":"agent-adapter.d.ts","sourceRoot":"","sources":["../src/agent-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,cAAc,CAAA;AAI1D,OAAO,EAA0B,KAAK,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAGpF,UAAU,kBAAkB;IAC1B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,CACZ,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QACP,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;QACvD,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;KAC7B,KACE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAC1B;AAwDD,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,OAAO,GAAG,WAAW,GAAG,aAAa,GAAG,MAAM,CAAA;IAC7D,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CACvB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;IACvB,QAAQ,CAAC,iBAAiB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;IAC9D,QAAQ,CAAC,KAAK,CAAC,EAAE,WAAW,CAAA;IAC5B,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAA;IAC3C,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;IAC5B,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,kBAAkB,EAAE,CAAA;IACpD,QAAQ,CAAC,KAAK,EAAE,SAAS,kBAAkB,EAAE,CAAA;CAC9C;AAED,wBAAsB,YAAY,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAQ1E;AAED,wBAAuB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,cAAc,CAAC,gBAAgB,CAAC,CA4B1F"}
@@ -1,5 +1,6 @@
1
1
  import { isDawnAgent } from "@dawn-ai/sdk";
2
2
  import { HumanMessage } from "@langchain/core/messages";
3
+ import { isRetryableError, withRetry } from "./retry.js";
3
4
  import { materializeStateSchema } from "./state-adapter.js";
4
5
  import { convertToolToLangChain } from "./tool-converter.js";
5
6
  function assertAgentLike(entry) {
@@ -11,14 +12,14 @@ function assertAgentLike(entry) {
11
12
  }
12
13
  }
13
14
  const materializedAgents = new WeakMap();
14
- async function materializeAgent(descriptor, tools, stateFields) {
15
+ async function materializeAgent(descriptor, tools, stateFields, middlewareContext) {
15
16
  const cached = materializedAgents.get(descriptor);
16
17
  if (cached) {
17
18
  return cached;
18
19
  }
19
20
  const { createReactAgent } = await import("@langchain/langgraph/prebuilt");
20
21
  const { ChatOpenAI } = await import("@langchain/openai");
21
- const langchainTools = tools.map((tool) => convertToolToLangChain(tool));
22
+ const langchainTools = tools.map((tool) => convertToolToLangChain(tool, middlewareContext));
22
23
  const llm = new ChatOpenAI({
23
24
  model: descriptor.model,
24
25
  });
@@ -49,17 +50,18 @@ export async function* streamAgent(options) {
49
50
  const messages = extractMessages(agentInput);
50
51
  // DawnAgent descriptor path — materialize on first use
51
52
  if (isDawnAgent(options.entry)) {
52
- const materializedAgent = await materializeAgent(options.entry, options.tools, options.stateFields);
53
- yield* streamFromRunnable(materializedAgent, { messages }, config);
53
+ const materializedAgent = await materializeAgent(options.entry, options.tools, options.stateFields, options.middlewareContext);
54
+ const retryConfig = options.entry.retry;
55
+ yield* streamFromRunnable(materializedAgent, { messages }, config, retryConfig);
54
56
  return;
55
57
  }
56
58
  // Legacy path — raw Runnable with .invoke()
57
59
  assertAgentLike(options.entry);
58
- const langchainTools = options.tools.map((tool) => convertToolToLangChain(tool));
60
+ const langchainTools = options.tools.map((tool) => convertToolToLangChain(tool, options.middlewareContext));
59
61
  if (langchainTools.length > 0) {
60
62
  config.tools = langchainTools;
61
63
  }
62
- yield* streamFromRunnable(options.entry, { messages }, config);
64
+ yield* streamFromRunnable(options.entry, { messages }, config, options.retry);
63
65
  }
64
66
  function prepareAgentCall(options) {
65
67
  const inputRecord = (options.input ?? {});
@@ -81,44 +83,83 @@ function prepareAgentCall(options) {
81
83
  }
82
84
  return { agentInput, config };
83
85
  }
84
- async function* streamFromRunnable(runnable, input, config) {
86
+ async function* streamFromRunnable(runnable, input, config, retryConfig) {
85
87
  const streamable = runnable;
86
88
  if (typeof streamable.streamEvents !== "function") {
87
- // Fallback: invoke and emit a single done event
88
- const result = await runnable.invoke(input, config);
89
+ // Fallback: invoke with retry and emit a single done event
90
+ const signal = config.signal;
91
+ const retryOptions = {
92
+ ...(retryConfig?.maxAttempts ? { maxAttempts: retryConfig.maxAttempts } : {}),
93
+ ...(retryConfig?.baseDelay ? { baseDelayMs: retryConfig.baseDelay } : {}),
94
+ ...(signal ? { signal } : {}),
95
+ };
96
+ const result = await withRetry(() => runnable.invoke(input, config), Object.keys(retryOptions).length > 0 ? retryOptions : undefined);
89
97
  yield { type: "done", data: result };
90
98
  return;
91
99
  }
92
100
  let finalOutput;
93
- for await (const event of streamable.streamEvents(input, { ...config, version: "v2" })) {
94
- switch (event.event) {
95
- case "on_chat_model_stream": {
96
- const content = event.data.chunk?.content;
97
- if (content && typeof content === "string" && content.length > 0) {
98
- yield { type: "token", data: content };
101
+ let hasYielded = false;
102
+ let lastStreamError;
103
+ // Retry the entire stream if it fails before producing any output
104
+ const maxStreamAttempts = retryConfig?.maxAttempts ?? 3;
105
+ for (let attempt = 0; attempt < maxStreamAttempts; attempt++) {
106
+ hasYielded = false;
107
+ lastStreamError = undefined;
108
+ finalOutput = undefined;
109
+ try {
110
+ for await (const event of streamable.streamEvents(input, {
111
+ ...config,
112
+ version: "v2",
113
+ })) {
114
+ switch (event.event) {
115
+ case "on_chat_model_stream": {
116
+ const content = event.data.chunk?.content;
117
+ if (content && typeof content === "string" && content.length > 0) {
118
+ hasYielded = true;
119
+ yield { type: "token", data: content };
120
+ }
121
+ break;
122
+ }
123
+ case "on_tool_start": {
124
+ hasYielded = true;
125
+ yield {
126
+ type: "tool_call",
127
+ data: {
128
+ name: event.name,
129
+ input: event.data.chunk ?? event.data.output,
130
+ },
131
+ };
132
+ break;
133
+ }
134
+ case "on_tool_end": {
135
+ hasYielded = true;
136
+ yield {
137
+ type: "tool_result",
138
+ data: { name: event.name, output: event.data.output },
139
+ };
140
+ break;
141
+ }
142
+ case "on_chain_end": {
143
+ if (event.name === "LangGraph") {
144
+ finalOutput = event.data.output;
145
+ }
146
+ break;
147
+ }
99
148
  }
100
- break;
101
149
  }
102
- case "on_tool_start": {
103
- yield {
104
- type: "tool_call",
105
- data: { name: event.name, input: event.data.chunk ?? event.data.output },
106
- };
107
- break;
108
- }
109
- case "on_tool_end": {
110
- yield {
111
- type: "tool_result",
112
- data: { name: event.name, output: event.data.output },
113
- };
114
- break;
115
- }
116
- case "on_chain_end": {
117
- if (event.name === "LangGraph") {
118
- finalOutput = event.data.output;
119
- }
120
- break;
150
+ // Stream completed successfully
151
+ break;
152
+ }
153
+ catch (error) {
154
+ lastStreamError = error instanceof Error ? error : new Error(String(error));
155
+ // If we already yielded chunks, we can't retry (client has partial data)
156
+ // Or if the error isn't retryable, rethrow immediately
157
+ if (hasYielded || !isRetryableError(error) || attempt === maxStreamAttempts - 1) {
158
+ throw lastStreamError;
121
159
  }
160
+ // Backoff before retry
161
+ const delay = Math.min(1000 * 2 ** attempt + Math.random() * 500, 10_000);
162
+ await new Promise((resolve) => setTimeout(resolve, delay));
122
163
  }
123
164
  }
124
165
  yield { type: "done", data: finalOutput };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export type { AgentStreamChunk } from "./agent-adapter.js";
2
2
  export { executeAgent, streamAgent } from "./agent-adapter.js";
3
3
  export { chainAdapter } from "./chain-adapter.js";
4
+ export type { RetryOptions } from "./retry.js";
5
+ export { isRetryableError, withRetry } from "./retry.js";
4
6
  export { materializeStateSchema } from "./state-adapter.js";
5
7
  export { convertToolToLangChain } from "./tool-converter.js";
6
8
  export { executeWithToolLoop } from "./tool-loop.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAA;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAC9C,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAA;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA"}
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { executeAgent, streamAgent } from "./agent-adapter.js";
2
2
  export { chainAdapter } from "./chain-adapter.js";
3
+ export { isRetryableError, withRetry } from "./retry.js";
3
4
  export { materializeStateSchema } from "./state-adapter.js";
4
5
  export { convertToolToLangChain } from "./tool-converter.js";
5
6
  export { executeWithToolLoop } from "./tool-loop.js";
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Retry with exponential backoff for transient LLM and tool failures.
3
+ */
4
+ export interface RetryOptions {
5
+ /** Maximum number of retry attempts (default: 3) */
6
+ readonly maxAttempts?: number;
7
+ /** Base delay in ms before first retry (default: 1000) */
8
+ readonly baseDelayMs?: number;
9
+ /** Maximum delay in ms (default: 10000) */
10
+ readonly maxDelayMs?: number;
11
+ /** Abort signal to cancel retries */
12
+ readonly signal?: AbortSignal;
13
+ }
14
+ /**
15
+ * Returns true if the error is transient and the operation should be retried.
16
+ * Retries on: rate limits (429), server errors (5xx), network errors, timeouts.
17
+ */
18
+ export declare function isRetryableError(error: unknown): boolean;
19
+ /**
20
+ * Execute an async function with retry and exponential backoff.
21
+ * Only retries on transient errors (rate limits, server errors, network issues).
22
+ */
23
+ export declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
24
+ //# sourceMappingURL=retry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../src/retry.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,WAAW,YAAY;IAC3B,oDAAoD;IACpD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,0DAA0D;IAC1D,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,2CAA2C;IAC3C,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,qCAAqC;IACrC,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAC9B;AAMD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAyBxD;AAED;;;GAGG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,CAAC,CAwC3F"}
package/dist/retry.js ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Retry with exponential backoff for transient LLM and tool failures.
3
+ */
4
+ const DEFAULT_MAX_ATTEMPTS = 3;
5
+ const DEFAULT_BASE_DELAY_MS = 1000;
6
+ const DEFAULT_MAX_DELAY_MS = 10_000;
7
+ /**
8
+ * Returns true if the error is transient and the operation should be retried.
9
+ * Retries on: rate limits (429), server errors (5xx), network errors, timeouts.
10
+ */
11
+ export function isRetryableError(error) {
12
+ if (!(error instanceof Error))
13
+ return false;
14
+ const message = error.message.toLowerCase();
15
+ // Rate limit errors
16
+ if (message.includes("429") || message.includes("rate limit"))
17
+ return true;
18
+ // Server errors (5xx)
19
+ if (message.includes("500") || message.includes("502") || message.includes("503"))
20
+ return true;
21
+ // Network/timeout errors
22
+ if (message.includes("econnreset") ||
23
+ message.includes("econnrefused") ||
24
+ message.includes("etimedout") ||
25
+ message.includes("timeout") ||
26
+ message.includes("network"))
27
+ return true;
28
+ // OpenAI-specific transient errors
29
+ if (message.includes("overloaded") || message.includes("server_error"))
30
+ return true;
31
+ return false;
32
+ }
33
+ /**
34
+ * Execute an async function with retry and exponential backoff.
35
+ * Only retries on transient errors (rate limits, server errors, network issues).
36
+ */
37
+ export async function withRetry(fn, options) {
38
+ const maxAttempts = options?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
39
+ const baseDelayMs = options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
40
+ const maxDelayMs = options?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
41
+ const signal = options?.signal;
42
+ let lastError;
43
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
44
+ if (signal?.aborted) {
45
+ throw new Error("Operation aborted");
46
+ }
47
+ try {
48
+ return await fn();
49
+ }
50
+ catch (error) {
51
+ lastError = error instanceof Error ? error : new Error(String(error));
52
+ // Don't retry non-transient errors or on the last attempt
53
+ if (!isRetryableError(error) || attempt === maxAttempts - 1) {
54
+ throw lastError;
55
+ }
56
+ // Exponential backoff with jitter
57
+ const delay = Math.min(baseDelayMs * 2 ** attempt + Math.random() * 500, maxDelayMs);
58
+ await new Promise((resolve, reject) => {
59
+ const timeout = setTimeout(resolve, delay);
60
+ if (signal) {
61
+ const onAbort = () => {
62
+ clearTimeout(timeout);
63
+ reject(new Error("Operation aborted"));
64
+ };
65
+ signal.addEventListener("abort", onAbort, { once: true });
66
+ }
67
+ });
68
+ }
69
+ }
70
+ throw lastError ?? new Error("Retry exhausted");
71
+ }
@@ -3,10 +3,11 @@ interface DawnToolDefinition {
3
3
  readonly description?: string;
4
4
  readonly name: string;
5
5
  readonly run: (input: unknown, context: {
6
+ readonly middleware?: Readonly<Record<string, unknown>>;
6
7
  readonly signal: AbortSignal;
7
8
  }) => Promise<unknown> | unknown;
8
9
  readonly schema?: unknown;
9
10
  }
10
- export declare function convertToolToLangChain(tool: DawnToolDefinition): DynamicStructuredTool;
11
+ export declare function convertToolToLangChain(tool: DawnToolDefinition, middlewareContext?: Readonly<Record<string, unknown>>): DynamicStructuredTool;
11
12
  export {};
12
13
  //# sourceMappingURL=tool-converter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-converter.d.ts","sourceRoot":"","sources":["../src/tool-converter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,UAAU,kBAAkB;IAC1B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,CACZ,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;KAAE,KACtC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,kBAAkB,GAAG,qBAAqB,CAetF"}
1
+ {"version":3,"file":"tool-converter.d.ts","sourceRoot":"","sources":["../src/tool-converter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,UAAU,kBAAkB;IAC1B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,CACZ,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QACP,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;QACvD,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;KAC7B,KACE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,kBAAkB,EACxB,iBAAiB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GACpD,qBAAqB,CAkBvB"}
@@ -1,6 +1,6 @@
1
1
  import { DynamicStructuredTool } from "@langchain/core/tools";
2
2
  import { z } from "zod";
3
- export function convertToolToLangChain(tool) {
3
+ export function convertToolToLangChain(tool, middlewareContext) {
4
4
  const schema = toZodSchema(tool.schema);
5
5
  // Cast through unknown to bridge the dual-Zod version type incompatibility
6
6
  // (package uses zod@3.24.4; @langchain/core uses zod@3.25.x — structurally identical at runtime)
@@ -10,7 +10,10 @@ export function convertToolToLangChain(tool) {
10
10
  schema: schema,
11
11
  func: async (input, _runManager, config) => {
12
12
  const signal = config?.signal ?? new AbortController().signal;
13
- const result = await tool.run(input, { signal });
13
+ const result = await tool.run(input, {
14
+ ...(middlewareContext ? { middleware: middlewareContext } : {}),
15
+ signal,
16
+ });
14
17
  return JSON.stringify(result);
15
18
  },
16
19
  });
@@ -1,6 +1,7 @@
1
1
  interface ToolExecutor {
2
2
  readonly name: string;
3
3
  readonly run: (input: unknown, context: {
4
+ readonly middleware?: Readonly<Record<string, unknown>>;
4
5
  readonly signal: AbortSignal;
5
6
  }) => Promise<unknown> | unknown;
6
7
  }
@@ -9,6 +10,7 @@ export interface ExecuteWithToolLoopOptions {
9
10
  readonly invoke: (input: unknown) => Promise<unknown>;
10
11
  };
11
12
  readonly input: unknown;
13
+ readonly middlewareContext?: Readonly<Record<string, unknown>>;
12
14
  readonly tools: readonly ToolExecutor[];
13
15
  readonly signal: AbortSignal;
14
16
  readonly maxIterations?: number;
@@ -1 +1 @@
1
- {"version":3,"file":"tool-loop.d.ts","sourceRoot":"","sources":["../src/tool-loop.ts"],"names":[],"mappings":"AAIA,UAAU,YAAY;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,CACZ,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;KAAE,KACtC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;CAChC;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,KAAK,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;KAAE,CAAA;IACzE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,YAAY,EAAE,CAAA;IACvC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;IAC5B,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAChC;AAED,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,OAAO,CAAC,CA8C/F"}
1
+ {"version":3,"file":"tool-loop.d.ts","sourceRoot":"","sources":["../src/tool-loop.ts"],"names":[],"mappings":"AAIA,UAAU,YAAY;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,CACZ,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QACP,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;QACvD,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;KAC7B,KACE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;CAChC;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,KAAK,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;KAAE,CAAA;IACzE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;IACvB,QAAQ,CAAC,iBAAiB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;IAC9D,QAAQ,CAAC,KAAK,EAAE,SAAS,YAAY,EAAE,CAAA;IACvC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;IAC5B,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAChC;AAED,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,OAAO,CAAC,CAwD/F"}
package/dist/tool-loop.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { AIMessage, ToolMessage } from "@langchain/core/messages";
2
2
  const DEFAULT_MAX_ITERATIONS = 10;
3
3
  export async function executeWithToolLoop(options) {
4
- const { chain, input, tools, signal, maxIterations = DEFAULT_MAX_ITERATIONS } = options;
4
+ const { chain, input, middlewareContext, tools, signal, maxIterations = DEFAULT_MAX_ITERATIONS, } = options;
5
5
  const toolMap = new Map(tools.map((t) => [t.name, t]));
6
6
  let currentInput = input;
7
7
  for (let i = 0; i < maxIterations; i++) {
@@ -18,7 +18,10 @@ export async function executeWithToolLoop(options) {
18
18
  });
19
19
  }
20
20
  try {
21
- const output = await tool.run(call.args, { signal });
21
+ const output = await tool.run(call.args, {
22
+ ...(middlewareContext ? { middleware: middlewareContext } : {}),
23
+ signal,
24
+ });
22
25
  return new ToolMessage({
23
26
  content: JSON.stringify(output),
24
27
  tool_call_id: call.id ?? "",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dawn-ai/langchain",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "dependencies": {
33
33
  "@langchain/langgraph": "^0.2.71",
34
34
  "@langchain/openai": "^0.3.17",
35
- "@dawn-ai/sdk": "0.1.5"
35
+ "@dawn-ai/sdk": "0.1.7"
36
36
  },
37
37
  "peerDependencies": {
38
38
  "@langchain/core": ">=0.3.0"
@@ -43,7 +43,7 @@
43
43
  "@langchain/openai": "0.3.17",
44
44
  "@types/node": "25.6.0",
45
45
  "zod": "3.24.4",
46
- "@dawn-ai/config-typescript": "0.1.5"
46
+ "@dawn-ai/config-typescript": "0.1.7"
47
47
  },
48
48
  "scripts": {
49
49
  "build": "tsc -b tsconfig.json",