@skroyc/ag-ui-middleware-callbacks 1.0.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -106
- package/dist/adapter.cjs +4 -0
- package/dist/adapter.d.cts +18 -0
- package/dist/adapter.d.ts +18 -0
- package/dist/adapter.js +4 -0
- package/dist/backend.cjs +4 -0
- package/dist/backend.d.cts +24 -0
- package/dist/backend.d.ts +24 -0
- package/dist/backend.js +4 -0
- package/dist/callbacks.cjs +2 -0
- package/dist/callbacks.d.cts +177 -0
- package/dist/callbacks.d.ts +177 -0
- package/dist/callbacks.js +2 -0
- package/dist/create-agui-adapter-B6ZmSEvX.d.cts +34 -0
- package/dist/create-agui-adapter-C3WiiO-D.d.ts +34 -0
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +2 -3
- package/dist/middleware.cjs +1 -0
- package/dist/middleware.d.cts +59 -0
- package/dist/middleware.d.ts +59 -0
- package/dist/middleware.js +1 -0
- package/dist/publication.cjs +3 -0
- package/dist/publication.d.cts +29 -0
- package/dist/publication.d.ts +29 -0
- package/dist/publication.js +3 -0
- package/package.json +40 -16
- package/dist/index.d.mts +0 -223
- package/dist/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,139 +1,137 @@
|
|
|
1
|
-
# ag-ui-middleware-callbacks
|
|
1
|
+
# @skroyc/ag-ui-middleware-callbacks
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AG-UI backend, adapter, and producer primitives for LangChain.js.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Status
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
The frozen MVP contract is recorded in
|
|
8
|
+
[docs/ContractFreeze.md](./docs/ContractFreeze.md). The current shipped package
|
|
9
|
+
now goes further and includes the extracted adapter boundary described in
|
|
10
|
+
`docs/TechSpec.md`.
|
|
8
11
|
|
|
9
|
-
|
|
10
|
-
- Intercept LangChain execution via middleware + callbacks
|
|
11
|
-
- Emit AG-UI events as JavaScript objects (using `@ag-ui/core` types)
|
|
12
|
+
Current implementation status:
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
|
|
14
|
+
- published runtime surface: programmatic adapter, backend wrapper,
|
|
15
|
+
run-scoped publisher, and low-level producers
|
|
16
|
+
- validated example set: CLI verifier plus GUI-backed default backend example
|
|
17
|
+
and advanced custom-host example under `example/`, both reusing the same
|
|
18
|
+
adapter semantics
|
|
19
|
+
- `createAGUIAgent`: still present in source for transition work, but no longer
|
|
20
|
+
treated as public package API
|
|
18
21
|
|
|
19
|
-
##
|
|
22
|
+
## Install
|
|
20
23
|
|
|
21
24
|
```bash
|
|
22
|
-
bun install ag-ui-middleware-callbacks
|
|
25
|
+
bun install @skroyc/ag-ui-middleware-callbacks
|
|
23
26
|
```
|
|
24
27
|
|
|
25
|
-
##
|
|
28
|
+
## Public Imports
|
|
26
29
|
|
|
27
|
-
|
|
30
|
+
Prefer explicit subpath imports:
|
|
28
31
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
32
|
+
```ts
|
|
33
|
+
import { AGUICallbackHandler } from "@skroyc/ag-ui-middleware-callbacks/callbacks";
|
|
34
|
+
import { createAGUIAdapter } from "@skroyc/ag-ui-middleware-callbacks/adapter";
|
|
35
|
+
import { createAGUIBackend } from "@skroyc/ag-ui-middleware-callbacks/backend";
|
|
36
|
+
import { createAGUIMiddleware } from "@skroyc/ag-ui-middleware-callbacks/middleware";
|
|
37
|
+
import { createAGUIRunPublisher } from "@skroyc/ag-ui-middleware-callbacks/publication";
|
|
38
|
+
```
|
|
33
39
|
|
|
34
|
-
|
|
40
|
+
The root export remains intentionally minimal:
|
|
35
41
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
42
|
+
```ts
|
|
43
|
+
import {
|
|
44
|
+
AGUICallbackHandler,
|
|
45
|
+
createAGUIMiddleware,
|
|
46
|
+
} from "@skroyc/ag-ui-middleware-callbacks";
|
|
47
|
+
```
|
|
39
48
|
|
|
40
|
-
##
|
|
49
|
+
## Programmatic Adapter Path
|
|
41
50
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
import { EventType } from "@ag-ui/core";
|
|
51
|
+
Use the adapter subpath when your host wants to own auth, routing, or transport
|
|
52
|
+
but still reuse the package's canonical run orchestration:
|
|
45
53
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
};
|
|
54
|
+
```ts
|
|
55
|
+
import { createAgent } from "langchain";
|
|
56
|
+
import { createAGUIAdapter } from "@skroyc/ag-ui-middleware-callbacks/adapter";
|
|
50
57
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
58
|
+
const adapter = createAGUIAdapter({
|
|
59
|
+
agentFactory: ({ input, middleware }) =>
|
|
60
|
+
createAgent({
|
|
61
|
+
model,
|
|
62
|
+
tools,
|
|
63
|
+
middleware: [middleware],
|
|
64
|
+
}),
|
|
56
65
|
});
|
|
57
66
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
version: "v2",
|
|
63
|
-
callbacks: [new AGUICallbackHandler({ onEvent: handleEvent })]
|
|
64
|
-
}
|
|
65
|
-
);
|
|
66
|
-
|
|
67
|
-
for await (const event of eventStream) {
|
|
68
|
-
// Events automatically emitted via callback
|
|
67
|
+
const events = await adapter.stream(input, { signal });
|
|
68
|
+
|
|
69
|
+
for await (const event of events) {
|
|
70
|
+
console.log(event);
|
|
69
71
|
}
|
|
70
72
|
```
|
|
71
73
|
|
|
72
|
-
##
|
|
74
|
+
## Default Backend Path
|
|
73
75
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
76
|
+
Use the backend subpath for the batteries-included serving path:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { createAgent } from "langchain";
|
|
80
|
+
import { createAGUIBackend } from "@skroyc/ag-ui-middleware-callbacks/backend";
|
|
81
|
+
|
|
82
|
+
const backend = createAGUIBackend({
|
|
83
|
+
agentFactory: ({ middleware }) =>
|
|
84
|
+
createAgent({
|
|
85
|
+
model,
|
|
86
|
+
tools,
|
|
87
|
+
middleware: [middleware],
|
|
88
|
+
}),
|
|
87
89
|
});
|
|
88
|
-
```
|
|
89
90
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|-------|--------|-------------|
|
|
94
|
-
| `RUN_STARTED` | Middleware | Agent execution started |
|
|
95
|
-
| `RUN_FINISHED` | Middleware | Agent execution completed |
|
|
96
|
-
| `RUN_ERROR` | Middleware | Agent execution failed |
|
|
97
|
-
| `STEP_STARTED` | Middleware | Model turn started |
|
|
98
|
-
| `STEP_FINISHED` | Middleware | Model turn completed |
|
|
99
|
-
| `TEXT_MESSAGE_START` | Callback | Text message streaming started |
|
|
100
|
-
| `TEXT_MESSAGE_CONTENT` | Callback | Text message chunk |
|
|
101
|
-
| `TEXT_MESSAGE_END` | Callback | Text message streaming ended |
|
|
102
|
-
| `TOOL_CALL_START` | Callback | Tool execution started |
|
|
103
|
-
| `TOOL_CALL_ARGS` | Callback | Tool call arguments chunk |
|
|
104
|
-
| `TOOL_CALL_END` | Callback | Tool execution ended |
|
|
105
|
-
| `TOOL_CALL_RESULT` | Callback | Tool execution result |
|
|
106
|
-
| `STATE_SNAPSHOT` | Middleware | State snapshot (after streaming) |
|
|
107
|
-
| `MESSAGES_SNAPSHOT` | Middleware | Messages snapshot |
|
|
108
|
-
| `ACTIVITY_SNAPSHOT` | Middleware | New activity detected |
|
|
109
|
-
| `ACTIVITY_DELTA` | Middleware | Activity update |
|
|
110
|
-
|
|
111
|
-
## Wire Formatting (Developer Responsibility)
|
|
112
|
-
|
|
113
|
-
Developers must implement their own transport/wire formatting:
|
|
114
|
-
|
|
115
|
-
### SSE Example
|
|
116
|
-
|
|
117
|
-
```typescript
|
|
118
|
-
const handleEvent = (event) => {
|
|
119
|
-
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
120
|
-
};
|
|
91
|
+
export function handle(request: Request) {
|
|
92
|
+
return backend.handle(request);
|
|
93
|
+
}
|
|
121
94
|
```
|
|
122
95
|
|
|
123
|
-
|
|
96
|
+
`handle(request)` expects a strict AG-UI `RunAgentInput` JSON payload and
|
|
97
|
+
returns a streamed `text/event-stream` response. Internally, the backend now
|
|
98
|
+
wraps `createAGUIAdapter()` rather than owning run orchestration itself.
|
|
124
99
|
|
|
125
|
-
|
|
126
|
-
import { encode, decode } from "@ag-ui/proto";
|
|
100
|
+
## Low-Level Example
|
|
127
101
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
102
|
+
```ts
|
|
103
|
+
import { AGUICallbackHandler } from "@skroyc/ag-ui-middleware-callbacks/callbacks";
|
|
104
|
+
import { createAGUIMiddleware } from "@skroyc/ag-ui-middleware-callbacks/middleware";
|
|
105
|
+
|
|
106
|
+
const publish = (event: unknown) => {
|
|
107
|
+
console.log(event);
|
|
132
108
|
};
|
|
133
|
-
```
|
|
134
109
|
|
|
135
|
-
|
|
110
|
+
const middleware = createAGUIMiddleware({
|
|
111
|
+
publish,
|
|
112
|
+
emitStateSnapshots: "initial",
|
|
113
|
+
errorDetailLevel: "message",
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const callbacks = [
|
|
117
|
+
new AGUICallbackHandler({
|
|
118
|
+
publish,
|
|
119
|
+
reasoningEventMode: "reasoning",
|
|
120
|
+
}),
|
|
121
|
+
];
|
|
122
|
+
```
|
|
136
123
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
- `
|
|
124
|
+
## Notes
|
|
125
|
+
|
|
126
|
+
- Reasoning events can be emitted as legacy `THINKING_*` or newer
|
|
127
|
+
`REASONING_*` families.
|
|
128
|
+
- New adapter-facing code should prefer `REASONING_*`; `THINKING_*` remains a
|
|
129
|
+
compatibility mode.
|
|
130
|
+
- Thinking/reasoning content is derived from LangChain content blocks after the
|
|
131
|
+
response is available; callback-only concurrent reasoning streaming is not
|
|
132
|
+
currently possible.
|
|
133
|
+
- The backend contract is `agentFactory({ input, middleware })`, not the older
|
|
134
|
+
frozen `{ agent }` shape. This is intentional because LangChain middleware is
|
|
135
|
+
attached at agent construction time.
|
|
136
|
+
- Repo-level package builds should use
|
|
137
|
+
`bun run --filter @skroyc/ag-ui-middleware-callbacks build`.
|
package/dist/adapter.cjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var core=require('@ag-ui/core'),base=require('@langchain/core/callbacks/base'),langchain=require('langchain'),zod=require('zod'),messages=require('@langchain/core/messages'),fastJsonPatch=require('fast-json-patch');function H(t){return typeof t=="object"&&t!==null}function b(t){if(t==null)return t;if(Array.isArray(t))return t.map(b);if(H(t)){if((t.lc===1||t.lc_serializable===true)&&(t.kwargs||t.lc_kwargs)){let n=t.kwargs||t.lc_kwargs;return b(n)}let e={};for(let[n,s]of Object.entries(t))n==="lc"||n==="type"||n==="id"||n.startsWith("lc_")||(e[n]=b(s));return e}return t}function V(t){if(t==null)return "";let e=t;if(typeof t=="string")try{e=JSON.parse(t);}catch{return t}if(!H(e))return String(e);let n=e.kwargs||e.lc_kwargs||e;return H(n)&&n.content!==void 0?typeof n.content=="string"?n.content:JSON.stringify(n.content):e.result!==void 0?typeof e.result=="string"?e.result:JSON.stringify(e.result):e.output!==void 0?typeof e.output=="string"?e.output:JSON.stringify(e.output):JSON.stringify(b(e))}function w(){return crypto.randomUUID()}function C(t,e){if(!t)throw new Error("baseId is required for deterministic ID generation");let n=`${t}-${e}`,s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s*31+l)%2147483647;}let r=Math.abs(s).toString(16).padStart(8,"0");return `${t}-${r}`}function he(t,e){let n=e.messageId||w(),s=[];return e.role&&s.push({type:core.EventType.TEXT_MESSAGE_START,messageId:n,role:e.role}),e.delta&&s.push({type:core.EventType.TEXT_MESSAGE_CONTENT,messageId:n,delta:e.delta}),e.role&&e.delta&&s.push({type:core.EventType.TEXT_MESSAGE_END,messageId:n}),s.length>0?s:[t]}function Ie(t,e){let n=e.toolCallId||w(),s=[];return e.toolCallName&&s.push({type:core.EventType.TOOL_CALL_START,toolCallId:n,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId}),e.delta&&s.push({type:core.EventType.TOOL_CALL_ARGS,toolCallId:n,delta:e.delta}),e.toolCallName&&e.delta&&s.push({type:core.EventType.TOOL_CALL_END,toolCallId:n,parentMessageId:e.parentMessageId}),s.length>0?s:[t]}function F(t){switch(t.type){case core.EventType.TEXT_MESSAGE_CHUNK:return he(t,t);case core.EventType.TOOL_CALL_CHUNK:return Ie(t,t);default:return [t]}}function ye(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="reasoning"}function z(t){let e=t;if(e._getType()!=="ai")return [];let n=e.contentBlocks;return Array.isArray(n)?n.filter(ye):[]}function X(t){let e=z(t),n=new Map;for(let s of e){let r=s.index??0,i=n.get(r)??[];i.push(s),n.set(r,i);}return n}var L=class extends base.BaseCallbackHandler{name="ag-ui-callback";messageIds=new Map;latestMessageIds=new Map;startedMessageIds=new Set;agentRunIds=new Map;parentToAuthoritativeId=new Map;toolCallInfo=new Map;toolCallNames=new Map;agentTurnTracker=new Map;pendingToolCalls=new Map;accumulatedToolArgs=new Map;streamingToolCallIds=new Map;streamedReasoningRuns=new Set;openReasoningStates=new Map;warnedMissingStreamingContentBlocks=new Set;emitCallback;_enabled;_emitTextMessages;_emitToolCalls;_emitToolResults;_emitThinking;_reasoningEventMode;maxUIPayloadSize;chunkLargeResults;constructor(e){if(super({raiseError:false}),typeof e.publish!="function")throw new TypeError("publish must be a function");this.emitCallback=e.publish,this._enabled=e?.enabled??true,this._emitTextMessages=e?.emitTextMessages??true,this._emitToolCalls=e?.emitToolCalls??true,this._emitToolResults=e?.emitToolResults??true,this._emitThinking=e?.emitThinking??true,this._reasoningEventMode=e?.reasoningEventMode??"thinking",this.maxUIPayloadSize=e?.maxUIPayloadSize??50*1024,this.chunkLargeResults=e?.chunkLargeResults??false;}get enabled(){return this._enabled}set enabled(e){this._enabled=e;}get emitTextMessages(){return this._emitTextMessages}set emitTextMessages(e){this._emitTextMessages=e;}get emitToolCalls(){return this._emitToolCalls}set emitToolCalls(e){this._emitToolCalls=e;}get emitToolResults(){return this._emitToolResults}set emitToolResults(e){this._emitToolResults=e;}get emitThinking(){return this._emitThinking}set emitThinking(e){this._emitThinking=e;}get reasoningEventMode(){return this._reasoningEventMode}set reasoningEventMode(e){this._reasoningEventMode=e;}dispose(){this.messageIds.clear(),this.latestMessageIds.clear(),this.startedMessageIds.clear(),this.agentRunIds.clear(),this.parentToAuthoritativeId.clear(),this.toolCallInfo.clear(),this.toolCallNames.clear(),this.agentTurnTracker.clear(),this.pendingToolCalls.clear(),this.accumulatedToolArgs.clear(),this.streamingToolCallIds.clear(),this.streamedReasoningRuns.clear(),this.openReasoningStates.clear(),this.warnedMissingStreamingContentBlocks.clear();}emitTextChunk(e,n,s){if(!(this.enabled&&this.emitTextMessages))return;let r=F({type:core.EventType.TEXT_MESSAGE_CHUNK,messageId:e,role:n,delta:s});for(let i of r)this.emitCallback(i);}emitToolChunk(e,n,s,r){if(!(this.enabled&&this.emitToolCalls))return;let i=F({type:core.EventType.TOOL_CALL_CHUNK,toolCallId:e,toolCallName:n,delta:s,parentMessageId:r});for(let l of i)this.emitCallback(l);}handleLLMStart(e,n,s,r,i,l,a,g){if(!(this.enabled&&this.emitTextMessages))return;let d=this.getContext(i),c=this.resolveCallbackAgentRunId(s,r,a,d);this.agentRunIds.set(s,c),r&&this.parentToAuthoritativeId.set(r,c),this.prepareAssistantMessage(s,c,this.getString(a,"agui_messageId"));}handleLLMNewToken(e,n,s,r,i,l){if(!this.enabled)return;let a=this.messageIds.get(s);if(a)try{let g=this.resolveAgentRunId(s,r);this.emitStreamingReasoning(l,a,s),e&&e.length>0&&(this.closeStreamingReasoning(s),this.ensureAssistantMessageStarted(a,g)),this.emitStreamingToken(e,a),this.emitToolCalls&&this.trackStreamingToolCallArgs(l,g);}catch{}}handleLLMEnd(e,n,s,r,i){let l=this.resolveAgentRunId(n,s);if(this.collectToolCallsFromOutput(e,l),!this.enabled){let g=this.messageIds.get(n);this.cleanupOpenLifecycles(n,g),g&&this.startedMessageIds.delete(g),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.messageIds.delete(n),this.clearStreamingToolCallIds(l);return}let a=this.messageIds.get(n);this.streamedReasoningRuns.has(n)||this.emitThinkingFromOutput(e,a??n),this.closeStreamingReasoning(n),this.emitAssistantMessageFromOutput(e,a,l),this.emitTextMessageEnd(a),a&&this.startedMessageIds.delete(a),this.messageIds.delete(n),this.clearStreamingToolCallIds(l),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n);}detectAndEmitThinking(e,n){if(!(this.emitThinking&&this.emitTextMessages)||z(e).length===0)return;let r=X(e);for(let[i,l]of r){let a=C(`${n}-reasoning-phase`,i),g=C(`${n}-reasoning-message`,i);this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_START,messageId:a,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_MESSAGE_START,messageId:g,role:"reasoning",timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_START,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_START,timestamp:Date.now()}));let d=l.map(c=>c.reasoning).filter(c=>c.trim().length>0).join("");d&&(this.reasoningEventMode==="reasoning"?this.emitCallback({type:core.EventType.REASONING_MESSAGE_CONTENT,messageId:g,delta:d,timestamp:Date.now()}):this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:d,timestamp:Date.now()})),this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_MESSAGE_END,messageId:g,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_END,messageId:a,timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_END,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_END,timestamp:Date.now()}));}}handleLLMError(e,n,s){let r=this.messageIds.get(n),i=this.resolveAgentRunId(n,s);if(!this.enabled){this.cleanupOpenLifecycles(n,r),r&&this.startedMessageIds.delete(r),this.messageIds.delete(n),this.pendingToolCalls.delete(i),this.agentRunIds.delete(n),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.clearStreamingToolCallIds(i);return}r&&this.startedMessageIds.delete(r),this.messageIds.delete(n),this.pendingToolCalls.delete(i),this.agentRunIds.delete(n),this.closeStreamingReasoning(n),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.clearStreamingToolCallIds(i);}handleToolStart(e,n,s,r,i,l,a){if(!(this.enabled&&this.emitToolCalls))return;let g=this.resolveToolInput(e,n,s,l,a),d={id:g.toolCallId??s,name:g.toolCallName??this.getToolCallName(e,a)};this.toolCallInfo.set(s,d);let c=this.resolveParentAgentRunId(r),m=this.latestMessageIds.get(c);this.emitToolStartSequence(d,m,g.argsDelta);}handleToolEnd(e,n,s){if(!(this.enabled&&this.emitToolCalls))return;let r=this.toolCallInfo.get(n);this.toolCallInfo.delete(n),r?.id&&this.toolCallNames.delete(r.id);let i=this.latestMessageIds.get(this.resolveParentAgentRunId(s));try{let l=r?.id??n;this.emitCallback({type:core.EventType.TOOL_CALL_END,toolCallId:l,timestamp:Date.now()}),this.emitToolResults&&this.emitToolResultWithPolicy(e,l,i,r?.name);}catch{}}handleToolError(e,n,s){if(!(this.enabled&&this.emitToolCalls))return;let r=this.toolCallInfo.get(n);this.toolCallInfo.delete(n),r?.id&&this.accumulatedToolArgs.delete(r.id);try{this.emitCallback({type:core.EventType.TOOL_CALL_END,toolCallId:r?.id??n,timestamp:Date.now()});}catch{}}chunkString(e,n){let s=[],r=e;for(;r.length>0;){if(new Blob([r]).size<=n){s.push(r);break}let i=n,l=r.lastIndexOf(" ",n),a=r.lastIndexOf(`
|
|
2
|
+
`,n),g=Math.max(l,a);if(g>n*.5)i=g;else {for(;i>0&&r.charCodeAt(i-1)>127;)i--;i===0&&(i=n);}s.push(r.substring(0,i)),r=r.substring(i).trim();}return s}emitToolResultWithPolicy(e,n,s,r){let i=V(e),l=w(),a=new Blob([i]).size;if(a<=this.maxUIPayloadSize){this.emitCallback({type:core.EventType.TOOL_CALL_RESULT,messageId:l,toolCallId:n,content:i,role:"tool",timestamp:Date.now()});return}if(this.chunkLargeResults){let m=this.chunkString(i,this.maxUIPayloadSize);for(let u=0;u<m.length;u++)this.emitCallback({type:core.EventType.CUSTOM,name:"LARGE_RESULT_CHUNK",value:{toolCallId:n,chunk:m[u],index:u,total:m.length}});return}let g=` [Truncated: ${a-this.maxUIPayloadSize+50} bytes]`,d=this.maxUIPayloadSize-g.length,c=i.substring(0,Math.max(0,d))+g;this.emitCallback({type:core.EventType.TOOL_CALL_RESULT,messageId:l,toolCallId:n,content:c,role:"tool",timestamp:Date.now()});}asRecord(e){if(typeof e=="object"&&e!==null)return e}getString(e,n){let s=e?.[n];return typeof s=="string"?s:void 0}getContext(e){return this.asRecord(this.asRecord(e)?.options)?.context}resolveCallbackAgentRunId(e,n,s,r){return this.getString(s,"run_id")||this.getString(s,"runId")||this.getString(r,"run_id")||this.getString(r,"runId")||this.getString(s,"agui_runId")||n||e}resolveAgentRunId(e,n){return this.agentRunIds.get(e)||(n?this.parentToAuthoritativeId.get(n):void 0)||n||e}resolveParentAgentRunId(e){return (e?this.parentToAuthoritativeId.get(e):void 0)||e||""}prepareAssistantMessage(e,n,s){let r=s??this.createAssistantMessageId(n);this.messageIds.set(e,r);}ensureAssistantMessageStarted(e,n){this.startedMessageIds.has(e)||(this.startedMessageIds.add(e),this.latestMessageIds.set(n,e),this.emitCallback({type:core.EventType.TEXT_MESSAGE_START,messageId:e,role:"assistant",timestamp:Date.now()}));}createAssistantMessageId(e){let n=this.agentTurnTracker.get(e)||0;return this.agentTurnTracker.set(e,n+1),C(e,n)}emitStreamingToken(e,n){e&&e.length>0&&this.emitTextMessages&&this.emitCallback({type:core.EventType.TEXT_MESSAGE_CONTENT,messageId:n,delta:e,timestamp:Date.now()});}emitAssistantMessageFromOutput(e,n,s){if(!(n&&this.emitTextMessages)||this.startedMessageIds.has(n))return;let r=this.getOutputTextContent(e);typeof r=="string"&&r.length>0&&(this.ensureAssistantMessageStarted(n,s),this.emitStreamingToken(r,n));}trackStreamingToolCallArgs(e,n){let s=this.getToolCallChunks(e);if(s.length===0)return;let r=[...this.pendingToolCalls.get(n)||[]],i=false;for(let l of s){let a=this.resolveStreamingToolCallId(n,l);if(a){if(l.name&&this.toolCallNames.set(a,l.name),typeof l.args=="string"){let g=this.accumulatedToolArgs.get(a)||"",d=g+l.args;d!==g&&this.accumulatedToolArgs.set(a,d);}r.includes(a)||(r.push(a),i=true);}}i&&this.pendingToolCalls.set(n,r);}emitStreamingReasoning(e,n,s){if(!(this.emitThinking&&this.emitTextMessages))return;let r=this.getStreamingReasoningChunks(e,s);if(r.length!==0){this.streamedReasoningRuns.add(s);for(let i of r){let l=this.ensureStreamingReasoningState(s,n,i.index);typeof i.reasoning=="string"&&i.reasoning.length>0&&(this.reasoningEventMode==="reasoning"?this.emitCallback({type:core.EventType.REASONING_MESSAGE_CONTENT,messageId:l.messageId,delta:i.reasoning,timestamp:Date.now()}):this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:i.reasoning,timestamp:Date.now()}));}}}getStreamingReasoningChunks(e,n){let r=this.asRecord(this.asRecord(e)?.chunk)?.message,i=this.asRecord(r),l=this.getStreamingContentBlocks(r);return l.length===0&&this.hasRawStreamingReasoning(i)&&this.warnMissingStreamingContentBlocks(n),l.map(a=>this.asRecord(a)).flatMap(a=>{let g=this.getString(a,"reasoning");return a?.type!=="reasoning"?[]:[{index:typeof a.index=="number"?a.index:0,reasoning:g}]})}getStreamingContentBlocks(e){let n=this.asRecord(e);return Array.isArray(n?.contentBlocks)?n.contentBlocks:[]}hasRawStreamingReasoning(e){return Array.isArray(e?.content)?e.content.some(n=>{let s=this.asRecord(n);return s?.type==="reasoning"&&typeof s.reasoning=="string"}):false}warnMissingStreamingContentBlocks(e){!e||this.warnedMissingStreamingContentBlocks.has(e)||(this.warnedMissingStreamingContentBlocks.add(e),console.warn("[AG-UI] Stream chunk exposed reasoning outside LangChain contentBlocks; reasoning events were skipped for this chunk."));}ensureStreamingReasoningState(e,n,s){let r=`${e}:${s}`,i=this.openReasoningStates.get(r);if(i)return i;let l={phaseId:C(`${n}-reasoning-phase`,s),messageId:C(`${n}-reasoning-message`,s)};return this.openReasoningStates.set(r,l),this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_START,messageId:l.phaseId,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_MESSAGE_START,messageId:l.messageId,role:"reasoning",timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_START,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_START,timestamp:Date.now()})),l}closeStreamingReasoning(e){let n=`${e}:`;for(let[s,r]of this.openReasoningStates)s.startsWith(n)&&(this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_MESSAGE_END,messageId:r.messageId,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_END,messageId:r.phaseId,timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_END,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_END,timestamp:Date.now()})),this.openReasoningStates.delete(s));}getToolCallChunks(e){let n=this.asRecord(this.asRecord(e)?.chunk),s=this.asRecord(n?.message),r=this.asRecord(s?.kwargs),i=s?.tool_call_chunks??r?.tool_call_chunks;return Array.isArray(i)?i.map(l=>{let a=this.asRecord(l);return {id:this.getString(a,"id"),name:this.getString(a,"name"),args:this.getString(a,"args"),index:typeof a?.index=="number"?a.index:void 0}}):[]}resolveStreamingToolCallId(e,n){if(n.id){let r=this.getStreamingToolCallKey(e,n.index);return r&&this.streamingToolCallIds.set(r,n.id),n.id}let s=this.getStreamingToolCallKey(e,n.index);if(s)return this.streamingToolCallIds.get(s)}getStreamingToolCallKey(e,n){if(typeof n=="number")return `${e}:${n}`}clearStreamingToolCallIds(e){let n=`${e}:`;for(let s of this.streamingToolCallIds.keys())s.startsWith(n)&&this.streamingToolCallIds.delete(s);}collectToolCallsFromOutput(e,n){try{let s=this.getOutputToolCalls(e);if(s.length===0)return;let r=[...this.pendingToolCalls.get(n)||[]];for(let i of s)i.id&&!r.includes(i.id)&&(r.push(i.id),i.function?.name&&this.toolCallNames.set(i.id,i.function.name),i.function?.arguments&&this.accumulatedToolArgs.set(i.id,i.function.arguments));this.pendingToolCalls.set(n,r);}catch{}}getOutputToolCalls(e){let n=this.asRecord(e),s=this.asRecord(n?.kwargs),r=n?.tool_calls??s?.tool_calls;if(Array.isArray(r))return r.map(g=>{let d=this.asRecord(g),c=this.asRecord(d?.function);return {id:this.getString(d,"id"),function:{name:this.getString(c,"name"),arguments:this.getString(c,"arguments")}}});let i=this.getOutputMessage(e),a=this.asRecord(i)?.tool_calls;return Array.isArray(a)?a.map(g=>{let d=this.asRecord(g),c=this.asRecord(d?.function);return {id:this.getString(d,"id"),function:{name:this.getString(c,"name")??this.getString(d,"name"),arguments:this.getString(c,"arguments")??this.stringifyIfDefined(d?.args)}}}):[]}emitThinkingFromOutput(e,n){try{let r=this.asRecord(e)?.generations;if(!Array.isArray(r)||r.length===0)return;let i=r[0];if(!Array.isArray(i)||i.length===0)return;let a=this.asRecord(i[0])?.message;if(!a)return;this.detectAndEmitThinking(a,n);}catch{}}emitTextMessageEnd(e){e&&this.startedMessageIds.has(e)&&this.emitCallback({type:core.EventType.TEXT_MESSAGE_END,messageId:e,timestamp:Date.now()});}cleanupOpenLifecycles(e,n){this.closeStreamingReasoning(e),this.emitTextMessageEnd(n);}resolveToolInput(e,n,s,r,i){let l=s,a=this.getToolCallName(e,i),g=n||void 0,d=this.getString(r,"tool_call_id");if(d)return {toolCallId:d,toolCallName:this.resolveStoredToolName(d,a),argsDelta:g};let c=this.parseToolInput(n);c&&(l=this.getString(c,"tool_call_id")||this.getString(c,"id")||l,a=this.getString(c,"name")||a,g=this.resolveToolArgsDelta(c,n));let m=l===s?this.findMatchingAccumulatedToolCallId(n):void 0;return m&&(l=m),{toolCallId:l,toolCallName:this.resolveStoredToolName(l,a),argsDelta:g}}getToolCallName(e,n){if(n)return n;let s=this.asRecord(e);if(!s)return "unknown_tool";let r=s.getName?.();return typeof r=="string"&&r.length>0?r:s.kwargs?.name||s.name||s.func?.name||s.toolName||s._name||"unknown_tool"}parseToolInput(e){if(e)try{return this.asRecord(JSON.parse(e))}catch{return}}findMatchingAccumulatedToolCallId(e){if(e){for(let[n,s]of this.accumulatedToolArgs)if(e.includes(s)||s.includes(e))return n}}resolveStoredToolName(e,n){let s=this.toolCallNames.get(e);return s&&s!=="unknown_tool"?s:n}emitToolStartSequence(e,n,s){try{this.emitCallback({type:core.EventType.TOOL_CALL_START,toolCallId:e.id,toolCallName:e.name,parentMessageId:n,timestamp:Date.now()});let r=s??this.accumulatedToolArgs.get(e.id);if(!r)return;this.emitCallback({type:core.EventType.TOOL_CALL_ARGS,toolCallId:e.id,delta:r,timestamp:Date.now()}),this.accumulatedToolArgs.delete(e.id);}catch{}}getOutputMessage(e){let s=this.asRecord(e)?.generations;if(!Array.isArray(s)||s.length===0)return;let r=s[0];if(!(!Array.isArray(r)||r.length===0))return this.asRecord(r[0])?.message}getOutputTextContent(e){let n=this.asRecord(e),s=this.getOutputMessage(e),r=this.asRecord(s),i=r?.content;if(typeof i=="string"&&i.length>0)return i;let l=this.getString(this.asRecord(r?.kwargs),"text");if(l&&l.length>0)return l;let a=r?.contentBlocks;if(Array.isArray(a)){let u=a.map(p=>this.asRecord(p)).filter(p=>p?.type==="text").map(p=>this.getString(p,"text")).filter(p=>!!(p&&p.length>0)).join("");if(u.length>0)return u}let g=Array.isArray(n?.generations)?n.generations:void 0,d=Array.isArray(g?.[0])?g[0]:void 0,m=this.asRecord(d?.[0])?.text;return typeof m=="string"&&m.length>0?m:void 0}resolveToolArgsDelta(e,n){if(typeof e.args=="string")return e.args;let s=this.stringifyIfDefined(e.args);if(s)return s;if(typeof e.arguments=="string")return e.arguments;let r=this.stringifyIfDefined(e.arguments);return r||n||void 0}stringifyIfDefined(e){if(!(typeof e>"u")){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}};var Re="[unserializable content]",we="{}";function W(t){return typeof t=="object"&&t!==null}function J(t){try{return JSON.stringify(t)}catch{return}}function _(t){if(typeof t>"u")return "";if(typeof t=="string")return t;let e=J(t);return typeof e=="string"?e:Re}function Ce(t){return W(t)?t.type==="text"&&typeof t.text=="string":false}function be(t){return !W(t)||t.type!=="binary"||typeof t.mimeType!="string"||t.id!==void 0&&typeof t.id!="string"||t.url!==void 0&&typeof t.url!="string"||t.data!==void 0&&typeof t.data!="string"||t.filename!==void 0&&typeof t.filename!="string"?false:typeof t.id=="string"||typeof t.url=="string"||typeof t.data=="string"}function Me(t){return Array.isArray(t)?t.every(e=>Ce(e)||be(e)):false}function j(t){switch(t){case "assistant":case "user":case "system":case "developer":case "tool":case "reasoning":return t;default:return}}function _e(t,e){return typeof e=="string"||t==="user"&&Me(e)?e:_(e)}function xe(t,e){let n=e._getType?.(),s=j(e.role),r="assistant",i,l;if(t instanceof messages.HumanMessage||s==="user"||n==="human")return {role:"user"};if(t instanceof messages.AIMessage||s==="assistant"||n==="ai"){let a=e.tool_calls||e.kwargs?.tool_calls;return a&&a.length>0&&(i=a.map(g=>({id:g.id||w(),type:"function",function:{name:String(g.name??"unknown_tool"),arguments:typeof g.args=="string"?g.args:J(g.args)??we}}))),{role:"assistant",toolCalls:i}}return t instanceof messages.ToolMessage||s==="tool"||n==="tool"?(l=e.tool_call_id||e.kwargs?.tool_call_id,{role:"tool",toolCallId:l}):t instanceof messages.SystemMessage||s==="system"||n==="system"?{role:"system"}:t instanceof messages.ChatMessage?(r=j(t.role)??"assistant",{role:r}):s?{role:s}:{role:r}}function q(t){let e=t,n=e.id||w(),{role:s,toolCalls:r,toolCallId:i}=xe(t,e);if(s==="assistant")return {id:n,role:s,content:_(e.content),toolCalls:r,name:e.name};if(s==="tool"){if(!i)throw new Error("Cannot map a tool-role message without a toolCallId.");return {id:n,role:s,content:_(e.content),toolCallId:i}}return s==="user"?{id:n,role:s,content:_e(s,e.content),name:e.name}:s==="system"?{id:n,role:s,content:_(e.content),name:e.name}:s==="developer"?{id:n,role:s,content:_(e.content),name:e.name}:{id:n,role:s,content:_(e.content)}}function Q(t,e){return fastJsonPatch.compare(t,e)}function N(t){try{let e=core.EventSchemas.safeParse(t);return e.success?{success:!0,data:t}:{success:!1,error:{message:"Event validation failed",issues:e.error.issues.map(n=>({path:n.path,message:n.message}))}}}catch(e){return {success:false,error:{message:e instanceof Error?e.message:"Unknown validation error",issues:[]}}}}function Y(t){return N(t).success}function x(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Z(t){let e=t.context,n=x(e?.thread_id)||x(e?.threadId),s=x(e?.run_id)||x(e?.runId),r=x(t.threadIdOverride),i=x(t.runIdOverride);return {threadId:n||r||"",runId:s||i||t.createFallbackRunId()}}var ee=zod.z.object({publish:zod.z.custom(t=>typeof t=="function",{message:"publish must be a function"}),emitStateSnapshots:zod.z.enum(["initial","final","all","none"]).default("initial"),emitActivities:zod.z.boolean().default(false),threadIdOverride:zod.z.string().optional(),runIdOverride:zod.z.string().optional(),errorDetailLevel:zod.z.enum(["full","message","code","none"]).default("message"),stateMapper:zod.z.custom().optional(),activityMapper:zod.z.custom().optional(),validateEvents:zod.z.union([zod.z.boolean(),zod.z.literal("strict")]).default(false)});function Oe(t){return t===true||t==="strict"}function T(t){return typeof t=="object"&&t!==null}function Ue(t){return T(t)&&!Array.isArray(t)}function Le(t){return T(t)&&"content"in t}function D(t){return T(t)&&Array.isArray(t.messages)?t.messages.filter(Le):[]}function De(t){if(T(t))return t.error}function Pe(t){if(T(t))return t.context}function He(t){if(T(t)&&T(t.config))return t.config.input}function Fe(t){if(T(t)&&T(t.config)&&T(t.config.model))return typeof t.config.model._modelType=="string"?t.config.model._modelType:void 0}function ze(t){return T(t)&&typeof t.type=="string"?t.type:"[unknown]"}function Ke(t){let e=D(t).at(-1);return e&&typeof e.content=="string"?e.content.substring(0,100)+(e.content.length>100?"...":""):"[no input preview]"}function $e(t){let e=D(t).at(-1);return Array.isArray(e?.toolCalls)&&e.toolCalls.length>0?"tool_calls":e?.content?"text":"unknown"}function Ve(t){return D(t).some(e=>Array.isArray(e.toolCalls)&&e.toolCalls.length>0)}function te(t,e,n,s,r,i,l){if(!e)return;let a=`activity-${e}-${n}`,g={status:r,timestamp:Date.now(),...l},d=i?i(g):g;if(!s.currentActivityId||s.currentActivityId!==a)s.currentActivityId=a,s.currentActivityType="AGENT_STEP",s.activityContent=d,t({type:core.EventType.ACTIVITY_SNAPSHOT,messageId:a,activityType:"AGENT_STEP",content:d,replace:true});else {let c=Q(s.activityContent,d);c.length>0&&(s.activityContent=d,t({type:core.EventType.ACTIVITY_DELTA,messageId:a,activityType:"AGENT_STEP",patch:c}));}}function ne(t){let e=ee.parse(t),n=c=>{if(Oe(e.validateEvents)&&!Y(c)){let u=N(c).error;if(e.validateEvents==="strict")throw new Error(`Invalid AG-UI event: ${u?.message}`);console.warn("[AG-UI Validation] Invalid event:",ze(c),u);}e.publish(c);},s=(c,m)=>c==="none"?false:c==="all"?true:c===m,r=c=>{let m=b(c),u=e.stateMapper?e.stateMapper(m):m;if(!e.stateMapper&&Ue(u)){let{messages:p,...I}=u;return I}return u},i=(c,m)=>{if(!s(e.emitStateSnapshots,c))return;let u=r(m);n({type:core.EventType.STATE_SNAPSHOT,snapshot:u,timestamp:Date.now()});},l=new Map,a=new WeakMap,g=zod.z.object({run_id:zod.z.string().optional(),runId:zod.z.string().optional(),thread_id:zod.z.string().optional(),threadId:zod.z.string().optional()}),d=c=>{let m=T(c)?c:void 0,u=m?a.get(m):void 0,p=Z({context:Pe(c),threadIdOverride:e.threadIdOverride,runIdOverride:e.runIdOverride,createFallbackRunId:()=>u??crypto.randomUUID()});m&&!a.has(m)&&a.set(m,p.runId);let I=l.get(p.runId);if(I)return !I.threadId&&p.threadId&&(I.threadId=p.threadId),I;let S={threadId:p.threadId,runId:p.runId,modelTurnIndex:0,activityTracker:{currentActivityId:void 0,currentActivityType:"AGENT_STEP",activityContent:{}}};return l.set(S.runId,S),S};return langchain.createMiddleware({name:"ag-ui-lifecycle",contextSchema:g,beforeAgent:(c,m)=>{let u=d(m);u.modelTurnIndex=0,u.currentStepName=void 0,u.activityTracker.currentActivityId=void 0,u.activityTracker.currentActivityType="AGENT_STEP",u.activityTracker.activityContent={};try{n({type:core.EventType.RUN_STARTED,threadId:u.threadId,runId:u.runId,input:b(He(m)),timestamp:Date.now()}),i("initial",c);let p=D(c);p.length>0&&n({type:core.EventType.MESSAGES_SNAPSHOT,messages:p.map(q),timestamp:Date.now()});}catch{}return {}},beforeModel:(c,m)=>{let u=d(m),p=u.modelTurnIndex++,S=`model_call_${C(u.runId,p)}`;u.currentStepName=S;try{n({type:core.EventType.STEP_STARTED,stepName:S,timestamp:Date.now()}),e.emitActivities&&te(n,u.runId,p,u.activityTracker,"started",e.activityMapper,{stepName:S,modelName:Fe(m)??"unknown",inputPreview:Ke(c)});}catch{}return {}},afterModel:(c,m)=>{let u=d(m);try{if(n({type:core.EventType.STEP_FINISHED,stepName:u.currentStepName||"",timestamp:Date.now()}),e.emitActivities&&u.currentStepName){let p=u.modelTurnIndex-1;te(n,u.runId,p,u.activityTracker,"completed",e.activityMapper,{stepName:u.currentStepName,outputType:$e(c),hasToolCalls:Ve(c)});}}catch{}return u.currentStepName=void 0,{}},afterAgent:(c,m)=>{let u=d(m);try{i("final",c);let p=De(c);if(p){let I=p instanceof Error?p.message:String(p);n({type:core.EventType.RUN_ERROR,message:e.errorDetailLevel==="full"||e.errorDetailLevel==="message"?I:"",code:"AGENT_EXECUTION_ERROR",timestamp:Date.now()});}else n({type:core.EventType.RUN_FINISHED,threadId:u.threadId,runId:u.runId,timestamp:Date.now()});}catch{}return l.delete(u.runId),T(m)&&a.delete(m),{}}})}var Xe=new TextEncoder;function se(t){return Xe.encode(`data: ${JSON.stringify(t)}
|
|
3
|
+
|
|
4
|
+
`)}var re=se;function ie(t,e="sse"){return t||re}function je(t){return t===true||t==="strict"}function oe(t){return typeof t=="object"&&t!==null}function M(t,e){if(!oe(t))return;let n=t[e];return typeof n=="string"?n:void 0}function ae(t){let e=M(t,"runId"),n=M(t,"threadId");if(!(!e||typeof n>"u"))return {runId:e,threadId:n}}function We(t){if(typeof t=="string")return {message:t};if(t instanceof Error){let e=typeof t.code=="string"?t.code:void 0;return {message:t.message,code:e}}if(oe(t)){let e=typeof t.message=="string"?t.message:"Agent execution failed",n=typeof t.code=="string"?t.code:void 0;return {message:e,code:n}}return {message:"Agent execution failed"}}function le(t={}){let e=ie(t.serializer,t.transport??"sse"),n=t.validateEvents??false,s=new Set,r=new Set,i=[],l=[],a=new Set,g=new Set,d=new Set,c=new Set,m=false,u=false,p,I=o=>{if(je(n)){let A=N(o);if(!A.success){if(n==="strict")throw new Error(`Invalid AG-UI event: ${A.error?.message}`);console.warn("[AG-UI Validation] Invalid event:",o.type,A.error);}}i.push(o);for(let A of s)A(o);let h=e(o);for(let A of r)A.enqueue(h);},S=()=>{for(let o of [...a])a.delete(o),I({type:core.EventType.TEXT_MESSAGE_END,messageId:o,timestamp:Date.now()});for(let o of [...g])g.delete(o),I({type:core.EventType.TOOL_CALL_END,toolCallId:o,timestamp:Date.now()});for(let o of [...d])d.delete(o),I({type:core.EventType.REASONING_MESSAGE_END,messageId:o,timestamp:Date.now()});for(let o of [...c])c.delete(o),I({type:core.EventType.REASONING_END,messageId:o,timestamp:Date.now()});},K=()=>{for(let o of r)o.close();r.clear();},B=o=>{u||(S(),u=true,I(o),K());},ce=()=>{u||(u=true,K());},ge=o=>{if(!(u||m))for(m=true,p=ae(o),I(o);l.length>0&&!u;){let h=l.shift();h&&$(h);}},O=(o,h,A)=>{let E=M(o,A);return E&&!h.has(E)?(h.add(E),I(o),true):false},P=(o,h,A)=>{let E=M(o,A);return E&&h.has(E)?(I(o),true):false},U=(o,h,A)=>{let E=M(o,A);return E&&h.has(E)?(h.delete(E),I(o),true):false},ue=o=>{switch(o.type){case core.EventType.TEXT_MESSAGE_START:return O(o,a,"messageId");case core.EventType.TEXT_MESSAGE_CONTENT:return P(o,a,"messageId");case core.EventType.TEXT_MESSAGE_END:return U(o,a,"messageId");default:return false}},me=o=>{switch(o.type){case core.EventType.TOOL_CALL_START:return O(o,g,"toolCallId");case core.EventType.TOOL_CALL_ARGS:return P(o,g,"toolCallId");case core.EventType.TOOL_CALL_END:return U(o,g,"toolCallId");default:return false}},pe=o=>{switch(o.type){case core.EventType.REASONING_START:return O(o,c,"messageId");case core.EventType.REASONING_END:return U(o,c,"messageId");case core.EventType.REASONING_MESSAGE_START:return O(o,d,"messageId");case core.EventType.REASONING_MESSAGE_CONTENT:return P(o,d,"messageId");case core.EventType.REASONING_MESSAGE_END:return U(o,d,"messageId");default:return false}},fe=o=>{if(o.type===core.EventType.RUN_ERROR)return B(o),true;if(o.type!==core.EventType.RUN_FINISHED)return false;let h=ae(o)??p;return B({...o,runId:h?.runId??M(o,"runId"),threadId:h?.threadId??M(o,"threadId")}),true},$=o=>{if(!u){if(o.type===core.EventType.RUN_STARTED){ge(o);return}if(!m){l.push(o);return}ue(o)||me(o)||pe(o)||fe(o)||I(o);}};return {publish(o){$(o);},complete(o){if(!u){if(!p)throw new Error("Cannot complete a run that has not been started. A `RUN_STARTED` event must be published first.");B({type:core.EventType.RUN_FINISHED,threadId:p.threadId,runId:p.runId,result:o,timestamp:Date.now()});}},error(o){if(u)return;let h=We(o);B({type:core.EventType.RUN_ERROR,message:h.message,code:h.code,timestamp:Date.now()});},close(){ce();},subscribe(o){return s.add(o),()=>{s.delete(o);}},toReadableStream(){let o;return new ReadableStream({start(h){o=h;for(let A of i)h.enqueue(e(A));if(u){h.close();return}r.add(h);},cancel(){o&&r.delete(o);}})}}}function qe(t){return t instanceof DOMException&&t.name==="AbortError"||t instanceof Error&&t.name==="AbortError"}function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ye(t){return Qe(t.state)?{...t.state,messages:t.messages}:{messages:t.messages,state:t.state}}function Ze(t){return e=>{e.type!==core.EventType.RUN_FINISHED&&t.publish(e);}}async function et(t){let e;for await(let n of t)e=n;return e}function tt(){let t=[],e=[],n=false,s,r=false,i=()=>{for(;t.length>0&&e.length>0;){let d=e.shift(),c=t.shift();d&&typeof c<"u"&&d.resolve({value:c,done:false});}},l=()=>{if(!(typeof s>"u"))for(let d of e.splice(0))d.reject(s);},a=()=>{if(n)for(let d of e.splice(0))d.resolve({value:void 0,done:true});},g=()=>{i(),!(t.length>0||e.length===0)&&(l(),a());};return {push(d){n||typeof s<"u"||(t.push(d),g());},close(){n||typeof s<"u"||(n=true,g());},error(d){n||typeof s<"u"||(s=d,g());},iterable:{async*[Symbol.asyncIterator](){if(r)throw new Error("AGUI adapter event streams support a single consumer.");for(r=true;;){if(t.length>0){yield t.shift();continue}if(typeof s<"u")throw s;if(n)return;let d=await new Promise((c,m)=>{e.push({resolve:c,reject:m});});if(d.done)return;yield d.value;}}}}}function de(t){if(typeof t.agentFactory!="function")throw new TypeError("agentFactory must be a function that accepts { input, middleware } and returns an agent with a stream() method");return {stream(e,n={}){let s=le({validateEvents:t.validateEvents}),r=tt(),i=s.subscribe(d=>{r.push(d);}),l=new L({publish:s.publish,...t.callbackOptions}),a=ne({publish:Ze(s),validateEvents:t.validateEvents??false,emitStateSnapshots:t.emitStateSnapshots??"initial",emitActivities:t.emitActivities??false,errorDetailLevel:t.errorDetailLevel??"message",runIdOverride:e.runId,threadIdOverride:e.threadId});return (async()=>{try{let c=await(await t.agentFactory({input:e,middleware:a})).stream(Ye(e),{callbacks:[l],signal:n.signal,streamMode:"values",configurable:{run_id:e.runId,thread_id:e.threadId},context:{run_id:e.runId,thread_id:e.threadId,signal:n.signal}}),m=await et(c);n.signal?.aborted?s.close():s.complete(m);}catch(d){n.signal?.aborted||qe(d)?s.close():s.error(d);}finally{try{l.dispose();}catch(d){console.error("Failed to dispose AG-UI callback handler.",d);}try{i();}catch(d){console.error("Failed to unsubscribe AG-UI adapter listener.",d);}r.close();}})().catch(d=>{r.error(d);}),Promise.resolve(r.iterable)}}}function tn(t){return de(t)}exports.createAGUIAdapter=tn;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { A as AGUIAdapter$1, a as AGUIAdapterConfig$1, b as AGUIAdapterRunOptions$1, c as AGUIAgentFactory$1, d as AGUIAgentLike$1, e as AGUIAgentRunOptions$1 } from './create-agui-adapter-B6ZmSEvX.cjs';
|
|
2
|
+
import '@ag-ui/core';
|
|
3
|
+
import './callbacks.cjs';
|
|
4
|
+
import '@langchain/core/callbacks/base';
|
|
5
|
+
import './middleware.cjs';
|
|
6
|
+
import 'langchain';
|
|
7
|
+
import '@langchain/core/tools';
|
|
8
|
+
import 'zod';
|
|
9
|
+
|
|
10
|
+
type AGUIAdapter = AGUIAdapter$1;
|
|
11
|
+
type AGUIAdapterConfig = AGUIAdapterConfig$1;
|
|
12
|
+
type AGUIAdapterRunOptions = AGUIAdapterRunOptions$1;
|
|
13
|
+
type AGUIAgentFactory = AGUIAgentFactory$1;
|
|
14
|
+
type AGUIAgentLike = AGUIAgentLike$1;
|
|
15
|
+
type AGUIAgentRunOptions = AGUIAgentRunOptions$1;
|
|
16
|
+
declare function createAGUIAdapter(config: AGUIAdapterConfig): AGUIAdapter;
|
|
17
|
+
|
|
18
|
+
export { type AGUIAdapter, type AGUIAdapterConfig, type AGUIAdapterRunOptions, type AGUIAgentFactory, type AGUIAgentLike, type AGUIAgentRunOptions, createAGUIAdapter };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { A as AGUIAdapter$1, a as AGUIAdapterConfig$1, b as AGUIAdapterRunOptions$1, c as AGUIAgentFactory$1, d as AGUIAgentLike$1, e as AGUIAgentRunOptions$1 } from './create-agui-adapter-C3WiiO-D.js';
|
|
2
|
+
import '@ag-ui/core';
|
|
3
|
+
import './callbacks.js';
|
|
4
|
+
import '@langchain/core/callbacks/base';
|
|
5
|
+
import './middleware.js';
|
|
6
|
+
import 'langchain';
|
|
7
|
+
import '@langchain/core/tools';
|
|
8
|
+
import 'zod';
|
|
9
|
+
|
|
10
|
+
type AGUIAdapter = AGUIAdapter$1;
|
|
11
|
+
type AGUIAdapterConfig = AGUIAdapterConfig$1;
|
|
12
|
+
type AGUIAdapterRunOptions = AGUIAdapterRunOptions$1;
|
|
13
|
+
type AGUIAgentFactory = AGUIAgentFactory$1;
|
|
14
|
+
type AGUIAgentLike = AGUIAgentLike$1;
|
|
15
|
+
type AGUIAgentRunOptions = AGUIAgentRunOptions$1;
|
|
16
|
+
declare function createAGUIAdapter(config: AGUIAdapterConfig): AGUIAdapter;
|
|
17
|
+
|
|
18
|
+
export { type AGUIAdapter, type AGUIAdapterConfig, type AGUIAdapterRunOptions, type AGUIAgentFactory, type AGUIAgentLike, type AGUIAgentRunOptions, createAGUIAdapter };
|
package/dist/adapter.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {EventType,EventSchemas}from'@ag-ui/core';import {BaseCallbackHandler}from'@langchain/core/callbacks/base';import {createMiddleware}from'langchain';import {z as z$1}from'zod';import {HumanMessage,AIMessage,ToolMessage,SystemMessage,ChatMessage}from'@langchain/core/messages';import {compare}from'fast-json-patch';function H(t){return typeof t=="object"&&t!==null}function b(t){if(t==null)return t;if(Array.isArray(t))return t.map(b);if(H(t)){if((t.lc===1||t.lc_serializable===true)&&(t.kwargs||t.lc_kwargs)){let n=t.kwargs||t.lc_kwargs;return b(n)}let e={};for(let[n,s]of Object.entries(t))n==="lc"||n==="type"||n==="id"||n.startsWith("lc_")||(e[n]=b(s));return e}return t}function V(t){if(t==null)return "";let e=t;if(typeof t=="string")try{e=JSON.parse(t);}catch{return t}if(!H(e))return String(e);let n=e.kwargs||e.lc_kwargs||e;return H(n)&&n.content!==void 0?typeof n.content=="string"?n.content:JSON.stringify(n.content):e.result!==void 0?typeof e.result=="string"?e.result:JSON.stringify(e.result):e.output!==void 0?typeof e.output=="string"?e.output:JSON.stringify(e.output):JSON.stringify(b(e))}function w(){return crypto.randomUUID()}function C(t,e){if(!t)throw new Error("baseId is required for deterministic ID generation");let n=`${t}-${e}`,s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s*31+l)%2147483647;}let r=Math.abs(s).toString(16).padStart(8,"0");return `${t}-${r}`}function he(t,e){let n=e.messageId||w(),s=[];return e.role&&s.push({type:EventType.TEXT_MESSAGE_START,messageId:n,role:e.role}),e.delta&&s.push({type:EventType.TEXT_MESSAGE_CONTENT,messageId:n,delta:e.delta}),e.role&&e.delta&&s.push({type:EventType.TEXT_MESSAGE_END,messageId:n}),s.length>0?s:[t]}function Ie(t,e){let n=e.toolCallId||w(),s=[];return e.toolCallName&&s.push({type:EventType.TOOL_CALL_START,toolCallId:n,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId}),e.delta&&s.push({type:EventType.TOOL_CALL_ARGS,toolCallId:n,delta:e.delta}),e.toolCallName&&e.delta&&s.push({type:EventType.TOOL_CALL_END,toolCallId:n,parentMessageId:e.parentMessageId}),s.length>0?s:[t]}function F(t){switch(t.type){case EventType.TEXT_MESSAGE_CHUNK:return he(t,t);case EventType.TOOL_CALL_CHUNK:return Ie(t,t);default:return [t]}}function ye(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="reasoning"}function z(t){let e=t;if(e._getType()!=="ai")return [];let n=e.contentBlocks;return Array.isArray(n)?n.filter(ye):[]}function X(t){let e=z(t),n=new Map;for(let s of e){let r=s.index??0,i=n.get(r)??[];i.push(s),n.set(r,i);}return n}var L=class extends BaseCallbackHandler{name="ag-ui-callback";messageIds=new Map;latestMessageIds=new Map;startedMessageIds=new Set;agentRunIds=new Map;parentToAuthoritativeId=new Map;toolCallInfo=new Map;toolCallNames=new Map;agentTurnTracker=new Map;pendingToolCalls=new Map;accumulatedToolArgs=new Map;streamingToolCallIds=new Map;streamedReasoningRuns=new Set;openReasoningStates=new Map;warnedMissingStreamingContentBlocks=new Set;emitCallback;_enabled;_emitTextMessages;_emitToolCalls;_emitToolResults;_emitThinking;_reasoningEventMode;maxUIPayloadSize;chunkLargeResults;constructor(e){if(super({raiseError:false}),typeof e.publish!="function")throw new TypeError("publish must be a function");this.emitCallback=e.publish,this._enabled=e?.enabled??true,this._emitTextMessages=e?.emitTextMessages??true,this._emitToolCalls=e?.emitToolCalls??true,this._emitToolResults=e?.emitToolResults??true,this._emitThinking=e?.emitThinking??true,this._reasoningEventMode=e?.reasoningEventMode??"thinking",this.maxUIPayloadSize=e?.maxUIPayloadSize??50*1024,this.chunkLargeResults=e?.chunkLargeResults??false;}get enabled(){return this._enabled}set enabled(e){this._enabled=e;}get emitTextMessages(){return this._emitTextMessages}set emitTextMessages(e){this._emitTextMessages=e;}get emitToolCalls(){return this._emitToolCalls}set emitToolCalls(e){this._emitToolCalls=e;}get emitToolResults(){return this._emitToolResults}set emitToolResults(e){this._emitToolResults=e;}get emitThinking(){return this._emitThinking}set emitThinking(e){this._emitThinking=e;}get reasoningEventMode(){return this._reasoningEventMode}set reasoningEventMode(e){this._reasoningEventMode=e;}dispose(){this.messageIds.clear(),this.latestMessageIds.clear(),this.startedMessageIds.clear(),this.agentRunIds.clear(),this.parentToAuthoritativeId.clear(),this.toolCallInfo.clear(),this.toolCallNames.clear(),this.agentTurnTracker.clear(),this.pendingToolCalls.clear(),this.accumulatedToolArgs.clear(),this.streamingToolCallIds.clear(),this.streamedReasoningRuns.clear(),this.openReasoningStates.clear(),this.warnedMissingStreamingContentBlocks.clear();}emitTextChunk(e,n,s){if(!(this.enabled&&this.emitTextMessages))return;let r=F({type:EventType.TEXT_MESSAGE_CHUNK,messageId:e,role:n,delta:s});for(let i of r)this.emitCallback(i);}emitToolChunk(e,n,s,r){if(!(this.enabled&&this.emitToolCalls))return;let i=F({type:EventType.TOOL_CALL_CHUNK,toolCallId:e,toolCallName:n,delta:s,parentMessageId:r});for(let l of i)this.emitCallback(l);}handleLLMStart(e,n,s,r,i,l,a,g){if(!(this.enabled&&this.emitTextMessages))return;let d=this.getContext(i),c=this.resolveCallbackAgentRunId(s,r,a,d);this.agentRunIds.set(s,c),r&&this.parentToAuthoritativeId.set(r,c),this.prepareAssistantMessage(s,c,this.getString(a,"agui_messageId"));}handleLLMNewToken(e,n,s,r,i,l){if(!this.enabled)return;let a=this.messageIds.get(s);if(a)try{let g=this.resolveAgentRunId(s,r);this.emitStreamingReasoning(l,a,s),e&&e.length>0&&(this.closeStreamingReasoning(s),this.ensureAssistantMessageStarted(a,g)),this.emitStreamingToken(e,a),this.emitToolCalls&&this.trackStreamingToolCallArgs(l,g);}catch{}}handleLLMEnd(e,n,s,r,i){let l=this.resolveAgentRunId(n,s);if(this.collectToolCallsFromOutput(e,l),!this.enabled){let g=this.messageIds.get(n);this.cleanupOpenLifecycles(n,g),g&&this.startedMessageIds.delete(g),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.messageIds.delete(n),this.clearStreamingToolCallIds(l);return}let a=this.messageIds.get(n);this.streamedReasoningRuns.has(n)||this.emitThinkingFromOutput(e,a??n),this.closeStreamingReasoning(n),this.emitAssistantMessageFromOutput(e,a,l),this.emitTextMessageEnd(a),a&&this.startedMessageIds.delete(a),this.messageIds.delete(n),this.clearStreamingToolCallIds(l),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n);}detectAndEmitThinking(e,n){if(!(this.emitThinking&&this.emitTextMessages)||z(e).length===0)return;let r=X(e);for(let[i,l]of r){let a=C(`${n}-reasoning-phase`,i),g=C(`${n}-reasoning-message`,i);this.reasoningEventMode==="reasoning"?(this.emitCallback({type:EventType.REASONING_START,messageId:a,timestamp:Date.now()}),this.emitCallback({type:EventType.REASONING_MESSAGE_START,messageId:g,role:"reasoning",timestamp:Date.now()})):(this.emitCallback({type:EventType.THINKING_START,timestamp:Date.now()}),this.emitCallback({type:EventType.THINKING_TEXT_MESSAGE_START,timestamp:Date.now()}));let d=l.map(c=>c.reasoning).filter(c=>c.trim().length>0).join("");d&&(this.reasoningEventMode==="reasoning"?this.emitCallback({type:EventType.REASONING_MESSAGE_CONTENT,messageId:g,delta:d,timestamp:Date.now()}):this.emitCallback({type:EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:d,timestamp:Date.now()})),this.reasoningEventMode==="reasoning"?(this.emitCallback({type:EventType.REASONING_MESSAGE_END,messageId:g,timestamp:Date.now()}),this.emitCallback({type:EventType.REASONING_END,messageId:a,timestamp:Date.now()})):(this.emitCallback({type:EventType.THINKING_TEXT_MESSAGE_END,timestamp:Date.now()}),this.emitCallback({type:EventType.THINKING_END,timestamp:Date.now()}));}}handleLLMError(e,n,s){let r=this.messageIds.get(n),i=this.resolveAgentRunId(n,s);if(!this.enabled){this.cleanupOpenLifecycles(n,r),r&&this.startedMessageIds.delete(r),this.messageIds.delete(n),this.pendingToolCalls.delete(i),this.agentRunIds.delete(n),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.clearStreamingToolCallIds(i);return}r&&this.startedMessageIds.delete(r),this.messageIds.delete(n),this.pendingToolCalls.delete(i),this.agentRunIds.delete(n),this.closeStreamingReasoning(n),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.clearStreamingToolCallIds(i);}handleToolStart(e,n,s,r,i,l,a){if(!(this.enabled&&this.emitToolCalls))return;let g=this.resolveToolInput(e,n,s,l,a),d={id:g.toolCallId??s,name:g.toolCallName??this.getToolCallName(e,a)};this.toolCallInfo.set(s,d);let c=this.resolveParentAgentRunId(r),m=this.latestMessageIds.get(c);this.emitToolStartSequence(d,m,g.argsDelta);}handleToolEnd(e,n,s){if(!(this.enabled&&this.emitToolCalls))return;let r=this.toolCallInfo.get(n);this.toolCallInfo.delete(n),r?.id&&this.toolCallNames.delete(r.id);let i=this.latestMessageIds.get(this.resolveParentAgentRunId(s));try{let l=r?.id??n;this.emitCallback({type:EventType.TOOL_CALL_END,toolCallId:l,timestamp:Date.now()}),this.emitToolResults&&this.emitToolResultWithPolicy(e,l,i,r?.name);}catch{}}handleToolError(e,n,s){if(!(this.enabled&&this.emitToolCalls))return;let r=this.toolCallInfo.get(n);this.toolCallInfo.delete(n),r?.id&&this.accumulatedToolArgs.delete(r.id);try{this.emitCallback({type:EventType.TOOL_CALL_END,toolCallId:r?.id??n,timestamp:Date.now()});}catch{}}chunkString(e,n){let s=[],r=e;for(;r.length>0;){if(new Blob([r]).size<=n){s.push(r);break}let i=n,l=r.lastIndexOf(" ",n),a=r.lastIndexOf(`
|
|
2
|
+
`,n),g=Math.max(l,a);if(g>n*.5)i=g;else {for(;i>0&&r.charCodeAt(i-1)>127;)i--;i===0&&(i=n);}s.push(r.substring(0,i)),r=r.substring(i).trim();}return s}emitToolResultWithPolicy(e,n,s,r){let i=V(e),l=w(),a=new Blob([i]).size;if(a<=this.maxUIPayloadSize){this.emitCallback({type:EventType.TOOL_CALL_RESULT,messageId:l,toolCallId:n,content:i,role:"tool",timestamp:Date.now()});return}if(this.chunkLargeResults){let m=this.chunkString(i,this.maxUIPayloadSize);for(let u=0;u<m.length;u++)this.emitCallback({type:EventType.CUSTOM,name:"LARGE_RESULT_CHUNK",value:{toolCallId:n,chunk:m[u],index:u,total:m.length}});return}let g=` [Truncated: ${a-this.maxUIPayloadSize+50} bytes]`,d=this.maxUIPayloadSize-g.length,c=i.substring(0,Math.max(0,d))+g;this.emitCallback({type:EventType.TOOL_CALL_RESULT,messageId:l,toolCallId:n,content:c,role:"tool",timestamp:Date.now()});}asRecord(e){if(typeof e=="object"&&e!==null)return e}getString(e,n){let s=e?.[n];return typeof s=="string"?s:void 0}getContext(e){return this.asRecord(this.asRecord(e)?.options)?.context}resolveCallbackAgentRunId(e,n,s,r){return this.getString(s,"run_id")||this.getString(s,"runId")||this.getString(r,"run_id")||this.getString(r,"runId")||this.getString(s,"agui_runId")||n||e}resolveAgentRunId(e,n){return this.agentRunIds.get(e)||(n?this.parentToAuthoritativeId.get(n):void 0)||n||e}resolveParentAgentRunId(e){return (e?this.parentToAuthoritativeId.get(e):void 0)||e||""}prepareAssistantMessage(e,n,s){let r=s??this.createAssistantMessageId(n);this.messageIds.set(e,r);}ensureAssistantMessageStarted(e,n){this.startedMessageIds.has(e)||(this.startedMessageIds.add(e),this.latestMessageIds.set(n,e),this.emitCallback({type:EventType.TEXT_MESSAGE_START,messageId:e,role:"assistant",timestamp:Date.now()}));}createAssistantMessageId(e){let n=this.agentTurnTracker.get(e)||0;return this.agentTurnTracker.set(e,n+1),C(e,n)}emitStreamingToken(e,n){e&&e.length>0&&this.emitTextMessages&&this.emitCallback({type:EventType.TEXT_MESSAGE_CONTENT,messageId:n,delta:e,timestamp:Date.now()});}emitAssistantMessageFromOutput(e,n,s){if(!(n&&this.emitTextMessages)||this.startedMessageIds.has(n))return;let r=this.getOutputTextContent(e);typeof r=="string"&&r.length>0&&(this.ensureAssistantMessageStarted(n,s),this.emitStreamingToken(r,n));}trackStreamingToolCallArgs(e,n){let s=this.getToolCallChunks(e);if(s.length===0)return;let r=[...this.pendingToolCalls.get(n)||[]],i=false;for(let l of s){let a=this.resolveStreamingToolCallId(n,l);if(a){if(l.name&&this.toolCallNames.set(a,l.name),typeof l.args=="string"){let g=this.accumulatedToolArgs.get(a)||"",d=g+l.args;d!==g&&this.accumulatedToolArgs.set(a,d);}r.includes(a)||(r.push(a),i=true);}}i&&this.pendingToolCalls.set(n,r);}emitStreamingReasoning(e,n,s){if(!(this.emitThinking&&this.emitTextMessages))return;let r=this.getStreamingReasoningChunks(e,s);if(r.length!==0){this.streamedReasoningRuns.add(s);for(let i of r){let l=this.ensureStreamingReasoningState(s,n,i.index);typeof i.reasoning=="string"&&i.reasoning.length>0&&(this.reasoningEventMode==="reasoning"?this.emitCallback({type:EventType.REASONING_MESSAGE_CONTENT,messageId:l.messageId,delta:i.reasoning,timestamp:Date.now()}):this.emitCallback({type:EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:i.reasoning,timestamp:Date.now()}));}}}getStreamingReasoningChunks(e,n){let r=this.asRecord(this.asRecord(e)?.chunk)?.message,i=this.asRecord(r),l=this.getStreamingContentBlocks(r);return l.length===0&&this.hasRawStreamingReasoning(i)&&this.warnMissingStreamingContentBlocks(n),l.map(a=>this.asRecord(a)).flatMap(a=>{let g=this.getString(a,"reasoning");return a?.type!=="reasoning"?[]:[{index:typeof a.index=="number"?a.index:0,reasoning:g}]})}getStreamingContentBlocks(e){let n=this.asRecord(e);return Array.isArray(n?.contentBlocks)?n.contentBlocks:[]}hasRawStreamingReasoning(e){return Array.isArray(e?.content)?e.content.some(n=>{let s=this.asRecord(n);return s?.type==="reasoning"&&typeof s.reasoning=="string"}):false}warnMissingStreamingContentBlocks(e){!e||this.warnedMissingStreamingContentBlocks.has(e)||(this.warnedMissingStreamingContentBlocks.add(e),console.warn("[AG-UI] Stream chunk exposed reasoning outside LangChain contentBlocks; reasoning events were skipped for this chunk."));}ensureStreamingReasoningState(e,n,s){let r=`${e}:${s}`,i=this.openReasoningStates.get(r);if(i)return i;let l={phaseId:C(`${n}-reasoning-phase`,s),messageId:C(`${n}-reasoning-message`,s)};return this.openReasoningStates.set(r,l),this.reasoningEventMode==="reasoning"?(this.emitCallback({type:EventType.REASONING_START,messageId:l.phaseId,timestamp:Date.now()}),this.emitCallback({type:EventType.REASONING_MESSAGE_START,messageId:l.messageId,role:"reasoning",timestamp:Date.now()})):(this.emitCallback({type:EventType.THINKING_START,timestamp:Date.now()}),this.emitCallback({type:EventType.THINKING_TEXT_MESSAGE_START,timestamp:Date.now()})),l}closeStreamingReasoning(e){let n=`${e}:`;for(let[s,r]of this.openReasoningStates)s.startsWith(n)&&(this.reasoningEventMode==="reasoning"?(this.emitCallback({type:EventType.REASONING_MESSAGE_END,messageId:r.messageId,timestamp:Date.now()}),this.emitCallback({type:EventType.REASONING_END,messageId:r.phaseId,timestamp:Date.now()})):(this.emitCallback({type:EventType.THINKING_TEXT_MESSAGE_END,timestamp:Date.now()}),this.emitCallback({type:EventType.THINKING_END,timestamp:Date.now()})),this.openReasoningStates.delete(s));}getToolCallChunks(e){let n=this.asRecord(this.asRecord(e)?.chunk),s=this.asRecord(n?.message),r=this.asRecord(s?.kwargs),i=s?.tool_call_chunks??r?.tool_call_chunks;return Array.isArray(i)?i.map(l=>{let a=this.asRecord(l);return {id:this.getString(a,"id"),name:this.getString(a,"name"),args:this.getString(a,"args"),index:typeof a?.index=="number"?a.index:void 0}}):[]}resolveStreamingToolCallId(e,n){if(n.id){let r=this.getStreamingToolCallKey(e,n.index);return r&&this.streamingToolCallIds.set(r,n.id),n.id}let s=this.getStreamingToolCallKey(e,n.index);if(s)return this.streamingToolCallIds.get(s)}getStreamingToolCallKey(e,n){if(typeof n=="number")return `${e}:${n}`}clearStreamingToolCallIds(e){let n=`${e}:`;for(let s of this.streamingToolCallIds.keys())s.startsWith(n)&&this.streamingToolCallIds.delete(s);}collectToolCallsFromOutput(e,n){try{let s=this.getOutputToolCalls(e);if(s.length===0)return;let r=[...this.pendingToolCalls.get(n)||[]];for(let i of s)i.id&&!r.includes(i.id)&&(r.push(i.id),i.function?.name&&this.toolCallNames.set(i.id,i.function.name),i.function?.arguments&&this.accumulatedToolArgs.set(i.id,i.function.arguments));this.pendingToolCalls.set(n,r);}catch{}}getOutputToolCalls(e){let n=this.asRecord(e),s=this.asRecord(n?.kwargs),r=n?.tool_calls??s?.tool_calls;if(Array.isArray(r))return r.map(g=>{let d=this.asRecord(g),c=this.asRecord(d?.function);return {id:this.getString(d,"id"),function:{name:this.getString(c,"name"),arguments:this.getString(c,"arguments")}}});let i=this.getOutputMessage(e),a=this.asRecord(i)?.tool_calls;return Array.isArray(a)?a.map(g=>{let d=this.asRecord(g),c=this.asRecord(d?.function);return {id:this.getString(d,"id"),function:{name:this.getString(c,"name")??this.getString(d,"name"),arguments:this.getString(c,"arguments")??this.stringifyIfDefined(d?.args)}}}):[]}emitThinkingFromOutput(e,n){try{let r=this.asRecord(e)?.generations;if(!Array.isArray(r)||r.length===0)return;let i=r[0];if(!Array.isArray(i)||i.length===0)return;let a=this.asRecord(i[0])?.message;if(!a)return;this.detectAndEmitThinking(a,n);}catch{}}emitTextMessageEnd(e){e&&this.startedMessageIds.has(e)&&this.emitCallback({type:EventType.TEXT_MESSAGE_END,messageId:e,timestamp:Date.now()});}cleanupOpenLifecycles(e,n){this.closeStreamingReasoning(e),this.emitTextMessageEnd(n);}resolveToolInput(e,n,s,r,i){let l=s,a=this.getToolCallName(e,i),g=n||void 0,d=this.getString(r,"tool_call_id");if(d)return {toolCallId:d,toolCallName:this.resolveStoredToolName(d,a),argsDelta:g};let c=this.parseToolInput(n);c&&(l=this.getString(c,"tool_call_id")||this.getString(c,"id")||l,a=this.getString(c,"name")||a,g=this.resolveToolArgsDelta(c,n));let m=l===s?this.findMatchingAccumulatedToolCallId(n):void 0;return m&&(l=m),{toolCallId:l,toolCallName:this.resolveStoredToolName(l,a),argsDelta:g}}getToolCallName(e,n){if(n)return n;let s=this.asRecord(e);if(!s)return "unknown_tool";let r=s.getName?.();return typeof r=="string"&&r.length>0?r:s.kwargs?.name||s.name||s.func?.name||s.toolName||s._name||"unknown_tool"}parseToolInput(e){if(e)try{return this.asRecord(JSON.parse(e))}catch{return}}findMatchingAccumulatedToolCallId(e){if(e){for(let[n,s]of this.accumulatedToolArgs)if(e.includes(s)||s.includes(e))return n}}resolveStoredToolName(e,n){let s=this.toolCallNames.get(e);return s&&s!=="unknown_tool"?s:n}emitToolStartSequence(e,n,s){try{this.emitCallback({type:EventType.TOOL_CALL_START,toolCallId:e.id,toolCallName:e.name,parentMessageId:n,timestamp:Date.now()});let r=s??this.accumulatedToolArgs.get(e.id);if(!r)return;this.emitCallback({type:EventType.TOOL_CALL_ARGS,toolCallId:e.id,delta:r,timestamp:Date.now()}),this.accumulatedToolArgs.delete(e.id);}catch{}}getOutputMessage(e){let s=this.asRecord(e)?.generations;if(!Array.isArray(s)||s.length===0)return;let r=s[0];if(!(!Array.isArray(r)||r.length===0))return this.asRecord(r[0])?.message}getOutputTextContent(e){let n=this.asRecord(e),s=this.getOutputMessage(e),r=this.asRecord(s),i=r?.content;if(typeof i=="string"&&i.length>0)return i;let l=this.getString(this.asRecord(r?.kwargs),"text");if(l&&l.length>0)return l;let a=r?.contentBlocks;if(Array.isArray(a)){let u=a.map(p=>this.asRecord(p)).filter(p=>p?.type==="text").map(p=>this.getString(p,"text")).filter(p=>!!(p&&p.length>0)).join("");if(u.length>0)return u}let g=Array.isArray(n?.generations)?n.generations:void 0,d=Array.isArray(g?.[0])?g[0]:void 0,m=this.asRecord(d?.[0])?.text;return typeof m=="string"&&m.length>0?m:void 0}resolveToolArgsDelta(e,n){if(typeof e.args=="string")return e.args;let s=this.stringifyIfDefined(e.args);if(s)return s;if(typeof e.arguments=="string")return e.arguments;let r=this.stringifyIfDefined(e.arguments);return r||n||void 0}stringifyIfDefined(e){if(!(typeof e>"u")){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}};var Re="[unserializable content]",we="{}";function W(t){return typeof t=="object"&&t!==null}function J(t){try{return JSON.stringify(t)}catch{return}}function _(t){if(typeof t>"u")return "";if(typeof t=="string")return t;let e=J(t);return typeof e=="string"?e:Re}function Ce(t){return W(t)?t.type==="text"&&typeof t.text=="string":false}function be(t){return !W(t)||t.type!=="binary"||typeof t.mimeType!="string"||t.id!==void 0&&typeof t.id!="string"||t.url!==void 0&&typeof t.url!="string"||t.data!==void 0&&typeof t.data!="string"||t.filename!==void 0&&typeof t.filename!="string"?false:typeof t.id=="string"||typeof t.url=="string"||typeof t.data=="string"}function Me(t){return Array.isArray(t)?t.every(e=>Ce(e)||be(e)):false}function j(t){switch(t){case "assistant":case "user":case "system":case "developer":case "tool":case "reasoning":return t;default:return}}function _e(t,e){return typeof e=="string"||t==="user"&&Me(e)?e:_(e)}function xe(t,e){let n=e._getType?.(),s=j(e.role),r="assistant",i,l;if(t instanceof HumanMessage||s==="user"||n==="human")return {role:"user"};if(t instanceof AIMessage||s==="assistant"||n==="ai"){let a=e.tool_calls||e.kwargs?.tool_calls;return a&&a.length>0&&(i=a.map(g=>({id:g.id||w(),type:"function",function:{name:String(g.name??"unknown_tool"),arguments:typeof g.args=="string"?g.args:J(g.args)??we}}))),{role:"assistant",toolCalls:i}}return t instanceof ToolMessage||s==="tool"||n==="tool"?(l=e.tool_call_id||e.kwargs?.tool_call_id,{role:"tool",toolCallId:l}):t instanceof SystemMessage||s==="system"||n==="system"?{role:"system"}:t instanceof ChatMessage?(r=j(t.role)??"assistant",{role:r}):s?{role:s}:{role:r}}function q(t){let e=t,n=e.id||w(),{role:s,toolCalls:r,toolCallId:i}=xe(t,e);if(s==="assistant")return {id:n,role:s,content:_(e.content),toolCalls:r,name:e.name};if(s==="tool"){if(!i)throw new Error("Cannot map a tool-role message without a toolCallId.");return {id:n,role:s,content:_(e.content),toolCallId:i}}return s==="user"?{id:n,role:s,content:_e(s,e.content),name:e.name}:s==="system"?{id:n,role:s,content:_(e.content),name:e.name}:s==="developer"?{id:n,role:s,content:_(e.content),name:e.name}:{id:n,role:s,content:_(e.content)}}function Q(t,e){return compare(t,e)}function N(t){try{let e=EventSchemas.safeParse(t);return e.success?{success:!0,data:t}:{success:!1,error:{message:"Event validation failed",issues:e.error.issues.map(n=>({path:n.path,message:n.message}))}}}catch(e){return {success:false,error:{message:e instanceof Error?e.message:"Unknown validation error",issues:[]}}}}function Y(t){return N(t).success}function x(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Z(t){let e=t.context,n=x(e?.thread_id)||x(e?.threadId),s=x(e?.run_id)||x(e?.runId),r=x(t.threadIdOverride),i=x(t.runIdOverride);return {threadId:n||r||"",runId:s||i||t.createFallbackRunId()}}var ee=z$1.object({publish:z$1.custom(t=>typeof t=="function",{message:"publish must be a function"}),emitStateSnapshots:z$1.enum(["initial","final","all","none"]).default("initial"),emitActivities:z$1.boolean().default(false),threadIdOverride:z$1.string().optional(),runIdOverride:z$1.string().optional(),errorDetailLevel:z$1.enum(["full","message","code","none"]).default("message"),stateMapper:z$1.custom().optional(),activityMapper:z$1.custom().optional(),validateEvents:z$1.union([z$1.boolean(),z$1.literal("strict")]).default(false)});function Oe(t){return t===true||t==="strict"}function T(t){return typeof t=="object"&&t!==null}function Ue(t){return T(t)&&!Array.isArray(t)}function Le(t){return T(t)&&"content"in t}function D(t){return T(t)&&Array.isArray(t.messages)?t.messages.filter(Le):[]}function De(t){if(T(t))return t.error}function Pe(t){if(T(t))return t.context}function He(t){if(T(t)&&T(t.config))return t.config.input}function Fe(t){if(T(t)&&T(t.config)&&T(t.config.model))return typeof t.config.model._modelType=="string"?t.config.model._modelType:void 0}function ze(t){return T(t)&&typeof t.type=="string"?t.type:"[unknown]"}function Ke(t){let e=D(t).at(-1);return e&&typeof e.content=="string"?e.content.substring(0,100)+(e.content.length>100?"...":""):"[no input preview]"}function $e(t){let e=D(t).at(-1);return Array.isArray(e?.toolCalls)&&e.toolCalls.length>0?"tool_calls":e?.content?"text":"unknown"}function Ve(t){return D(t).some(e=>Array.isArray(e.toolCalls)&&e.toolCalls.length>0)}function te(t,e,n,s,r,i,l){if(!e)return;let a=`activity-${e}-${n}`,g={status:r,timestamp:Date.now(),...l},d=i?i(g):g;if(!s.currentActivityId||s.currentActivityId!==a)s.currentActivityId=a,s.currentActivityType="AGENT_STEP",s.activityContent=d,t({type:EventType.ACTIVITY_SNAPSHOT,messageId:a,activityType:"AGENT_STEP",content:d,replace:true});else {let c=Q(s.activityContent,d);c.length>0&&(s.activityContent=d,t({type:EventType.ACTIVITY_DELTA,messageId:a,activityType:"AGENT_STEP",patch:c}));}}function ne(t){let e=ee.parse(t),n=c=>{if(Oe(e.validateEvents)&&!Y(c)){let u=N(c).error;if(e.validateEvents==="strict")throw new Error(`Invalid AG-UI event: ${u?.message}`);console.warn("[AG-UI Validation] Invalid event:",ze(c),u);}e.publish(c);},s=(c,m)=>c==="none"?false:c==="all"?true:c===m,r=c=>{let m=b(c),u=e.stateMapper?e.stateMapper(m):m;if(!e.stateMapper&&Ue(u)){let{messages:p,...I}=u;return I}return u},i=(c,m)=>{if(!s(e.emitStateSnapshots,c))return;let u=r(m);n({type:EventType.STATE_SNAPSHOT,snapshot:u,timestamp:Date.now()});},l=new Map,a=new WeakMap,g=z$1.object({run_id:z$1.string().optional(),runId:z$1.string().optional(),thread_id:z$1.string().optional(),threadId:z$1.string().optional()}),d=c=>{let m=T(c)?c:void 0,u=m?a.get(m):void 0,p=Z({context:Pe(c),threadIdOverride:e.threadIdOverride,runIdOverride:e.runIdOverride,createFallbackRunId:()=>u??crypto.randomUUID()});m&&!a.has(m)&&a.set(m,p.runId);let I=l.get(p.runId);if(I)return !I.threadId&&p.threadId&&(I.threadId=p.threadId),I;let S={threadId:p.threadId,runId:p.runId,modelTurnIndex:0,activityTracker:{currentActivityId:void 0,currentActivityType:"AGENT_STEP",activityContent:{}}};return l.set(S.runId,S),S};return createMiddleware({name:"ag-ui-lifecycle",contextSchema:g,beforeAgent:(c,m)=>{let u=d(m);u.modelTurnIndex=0,u.currentStepName=void 0,u.activityTracker.currentActivityId=void 0,u.activityTracker.currentActivityType="AGENT_STEP",u.activityTracker.activityContent={};try{n({type:EventType.RUN_STARTED,threadId:u.threadId,runId:u.runId,input:b(He(m)),timestamp:Date.now()}),i("initial",c);let p=D(c);p.length>0&&n({type:EventType.MESSAGES_SNAPSHOT,messages:p.map(q),timestamp:Date.now()});}catch{}return {}},beforeModel:(c,m)=>{let u=d(m),p=u.modelTurnIndex++,S=`model_call_${C(u.runId,p)}`;u.currentStepName=S;try{n({type:EventType.STEP_STARTED,stepName:S,timestamp:Date.now()}),e.emitActivities&&te(n,u.runId,p,u.activityTracker,"started",e.activityMapper,{stepName:S,modelName:Fe(m)??"unknown",inputPreview:Ke(c)});}catch{}return {}},afterModel:(c,m)=>{let u=d(m);try{if(n({type:EventType.STEP_FINISHED,stepName:u.currentStepName||"",timestamp:Date.now()}),e.emitActivities&&u.currentStepName){let p=u.modelTurnIndex-1;te(n,u.runId,p,u.activityTracker,"completed",e.activityMapper,{stepName:u.currentStepName,outputType:$e(c),hasToolCalls:Ve(c)});}}catch{}return u.currentStepName=void 0,{}},afterAgent:(c,m)=>{let u=d(m);try{i("final",c);let p=De(c);if(p){let I=p instanceof Error?p.message:String(p);n({type:EventType.RUN_ERROR,message:e.errorDetailLevel==="full"||e.errorDetailLevel==="message"?I:"",code:"AGENT_EXECUTION_ERROR",timestamp:Date.now()});}else n({type:EventType.RUN_FINISHED,threadId:u.threadId,runId:u.runId,timestamp:Date.now()});}catch{}return l.delete(u.runId),T(m)&&a.delete(m),{}}})}var Xe=new TextEncoder;function se(t){return Xe.encode(`data: ${JSON.stringify(t)}
|
|
3
|
+
|
|
4
|
+
`)}var re=se;function ie(t,e="sse"){return t||re}function je(t){return t===true||t==="strict"}function oe(t){return typeof t=="object"&&t!==null}function M(t,e){if(!oe(t))return;let n=t[e];return typeof n=="string"?n:void 0}function ae(t){let e=M(t,"runId"),n=M(t,"threadId");if(!(!e||typeof n>"u"))return {runId:e,threadId:n}}function We(t){if(typeof t=="string")return {message:t};if(t instanceof Error){let e=typeof t.code=="string"?t.code:void 0;return {message:t.message,code:e}}if(oe(t)){let e=typeof t.message=="string"?t.message:"Agent execution failed",n=typeof t.code=="string"?t.code:void 0;return {message:e,code:n}}return {message:"Agent execution failed"}}function le(t={}){let e=ie(t.serializer,t.transport??"sse"),n=t.validateEvents??false,s=new Set,r=new Set,i=[],l=[],a=new Set,g=new Set,d=new Set,c=new Set,m=false,u=false,p,I=o=>{if(je(n)){let A=N(o);if(!A.success){if(n==="strict")throw new Error(`Invalid AG-UI event: ${A.error?.message}`);console.warn("[AG-UI Validation] Invalid event:",o.type,A.error);}}i.push(o);for(let A of s)A(o);let h=e(o);for(let A of r)A.enqueue(h);},S=()=>{for(let o of [...a])a.delete(o),I({type:EventType.TEXT_MESSAGE_END,messageId:o,timestamp:Date.now()});for(let o of [...g])g.delete(o),I({type:EventType.TOOL_CALL_END,toolCallId:o,timestamp:Date.now()});for(let o of [...d])d.delete(o),I({type:EventType.REASONING_MESSAGE_END,messageId:o,timestamp:Date.now()});for(let o of [...c])c.delete(o),I({type:EventType.REASONING_END,messageId:o,timestamp:Date.now()});},K=()=>{for(let o of r)o.close();r.clear();},B=o=>{u||(S(),u=true,I(o),K());},ce=()=>{u||(u=true,K());},ge=o=>{if(!(u||m))for(m=true,p=ae(o),I(o);l.length>0&&!u;){let h=l.shift();h&&$(h);}},O=(o,h,A)=>{let E=M(o,A);return E&&!h.has(E)?(h.add(E),I(o),true):false},P=(o,h,A)=>{let E=M(o,A);return E&&h.has(E)?(I(o),true):false},U=(o,h,A)=>{let E=M(o,A);return E&&h.has(E)?(h.delete(E),I(o),true):false},ue=o=>{switch(o.type){case EventType.TEXT_MESSAGE_START:return O(o,a,"messageId");case EventType.TEXT_MESSAGE_CONTENT:return P(o,a,"messageId");case EventType.TEXT_MESSAGE_END:return U(o,a,"messageId");default:return false}},me=o=>{switch(o.type){case EventType.TOOL_CALL_START:return O(o,g,"toolCallId");case EventType.TOOL_CALL_ARGS:return P(o,g,"toolCallId");case EventType.TOOL_CALL_END:return U(o,g,"toolCallId");default:return false}},pe=o=>{switch(o.type){case EventType.REASONING_START:return O(o,c,"messageId");case EventType.REASONING_END:return U(o,c,"messageId");case EventType.REASONING_MESSAGE_START:return O(o,d,"messageId");case EventType.REASONING_MESSAGE_CONTENT:return P(o,d,"messageId");case EventType.REASONING_MESSAGE_END:return U(o,d,"messageId");default:return false}},fe=o=>{if(o.type===EventType.RUN_ERROR)return B(o),true;if(o.type!==EventType.RUN_FINISHED)return false;let h=ae(o)??p;return B({...o,runId:h?.runId??M(o,"runId"),threadId:h?.threadId??M(o,"threadId")}),true},$=o=>{if(!u){if(o.type===EventType.RUN_STARTED){ge(o);return}if(!m){l.push(o);return}ue(o)||me(o)||pe(o)||fe(o)||I(o);}};return {publish(o){$(o);},complete(o){if(!u){if(!p)throw new Error("Cannot complete a run that has not been started. A `RUN_STARTED` event must be published first.");B({type:EventType.RUN_FINISHED,threadId:p.threadId,runId:p.runId,result:o,timestamp:Date.now()});}},error(o){if(u)return;let h=We(o);B({type:EventType.RUN_ERROR,message:h.message,code:h.code,timestamp:Date.now()});},close(){ce();},subscribe(o){return s.add(o),()=>{s.delete(o);}},toReadableStream(){let o;return new ReadableStream({start(h){o=h;for(let A of i)h.enqueue(e(A));if(u){h.close();return}r.add(h);},cancel(){o&&r.delete(o);}})}}}function qe(t){return t instanceof DOMException&&t.name==="AbortError"||t instanceof Error&&t.name==="AbortError"}function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ye(t){return Qe(t.state)?{...t.state,messages:t.messages}:{messages:t.messages,state:t.state}}function Ze(t){return e=>{e.type!==EventType.RUN_FINISHED&&t.publish(e);}}async function et(t){let e;for await(let n of t)e=n;return e}function tt(){let t=[],e=[],n=false,s,r=false,i=()=>{for(;t.length>0&&e.length>0;){let d=e.shift(),c=t.shift();d&&typeof c<"u"&&d.resolve({value:c,done:false});}},l=()=>{if(!(typeof s>"u"))for(let d of e.splice(0))d.reject(s);},a=()=>{if(n)for(let d of e.splice(0))d.resolve({value:void 0,done:true});},g=()=>{i(),!(t.length>0||e.length===0)&&(l(),a());};return {push(d){n||typeof s<"u"||(t.push(d),g());},close(){n||typeof s<"u"||(n=true,g());},error(d){n||typeof s<"u"||(s=d,g());},iterable:{async*[Symbol.asyncIterator](){if(r)throw new Error("AGUI adapter event streams support a single consumer.");for(r=true;;){if(t.length>0){yield t.shift();continue}if(typeof s<"u")throw s;if(n)return;let d=await new Promise((c,m)=>{e.push({resolve:c,reject:m});});if(d.done)return;yield d.value;}}}}}function de(t){if(typeof t.agentFactory!="function")throw new TypeError("agentFactory must be a function that accepts { input, middleware } and returns an agent with a stream() method");return {stream(e,n={}){let s=le({validateEvents:t.validateEvents}),r=tt(),i=s.subscribe(d=>{r.push(d);}),l=new L({publish:s.publish,...t.callbackOptions}),a=ne({publish:Ze(s),validateEvents:t.validateEvents??false,emitStateSnapshots:t.emitStateSnapshots??"initial",emitActivities:t.emitActivities??false,errorDetailLevel:t.errorDetailLevel??"message",runIdOverride:e.runId,threadIdOverride:e.threadId});return (async()=>{try{let c=await(await t.agentFactory({input:e,middleware:a})).stream(Ye(e),{callbacks:[l],signal:n.signal,streamMode:"values",configurable:{run_id:e.runId,thread_id:e.threadId},context:{run_id:e.runId,thread_id:e.threadId,signal:n.signal}}),m=await et(c);n.signal?.aborted?s.close():s.complete(m);}catch(d){n.signal?.aborted||qe(d)?s.close():s.error(d);}finally{try{l.dispose();}catch(d){console.error("Failed to dispose AG-UI callback handler.",d);}try{i();}catch(d){console.error("Failed to unsubscribe AG-UI adapter listener.",d);}r.close();}})().catch(d=>{r.error(d);}),Promise.resolve(r.iterable)}}}function tn(t){return de(t)}export{tn as createAGUIAdapter};
|
package/dist/backend.cjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var core=require('@ag-ui/core'),base=require('@langchain/core/callbacks/base'),langchain=require('langchain'),zod=require('zod'),messages=require('@langchain/core/messages'),fastJsonPatch=require('fast-json-patch');function H(t){return typeof t=="object"&&t!==null}function b(t){if(t==null)return t;if(Array.isArray(t))return t.map(b);if(H(t)){if((t.lc===1||t.lc_serializable===true)&&(t.kwargs||t.lc_kwargs)){let n=t.kwargs||t.lc_kwargs;return b(n)}let e={};for(let[n,s]of Object.entries(t))n==="lc"||n==="type"||n==="id"||n.startsWith("lc_")||(e[n]=b(s));return e}return t}function X(t){if(t==null)return "";let e=t;if(typeof t=="string")try{e=JSON.parse(t);}catch{return t}if(!H(e))return String(e);let n=e.kwargs||e.lc_kwargs||e;return H(n)&&n.content!==void 0?typeof n.content=="string"?n.content:JSON.stringify(n.content):e.result!==void 0?typeof e.result=="string"?e.result:JSON.stringify(e.result):e.output!==void 0?typeof e.output=="string"?e.output:JSON.stringify(e.output):JSON.stringify(b(e))}function w(){return crypto.randomUUID()}function C(t,e){if(!t)throw new Error("baseId is required for deterministic ID generation");let n=`${t}-${e}`,s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s*31+l)%2147483647;}let r=Math.abs(s).toString(16).padStart(8,"0");return `${t}-${r}`}function Te(t,e){let n=e.messageId||w(),s=[];return e.role&&s.push({type:core.EventType.TEXT_MESSAGE_START,messageId:n,role:e.role}),e.delta&&s.push({type:core.EventType.TEXT_MESSAGE_CONTENT,messageId:n,delta:e.delta}),e.role&&e.delta&&s.push({type:core.EventType.TEXT_MESSAGE_END,messageId:n}),s.length>0?s:[t]}function ve(t,e){let n=e.toolCallId||w(),s=[];return e.toolCallName&&s.push({type:core.EventType.TOOL_CALL_START,toolCallId:n,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId}),e.delta&&s.push({type:core.EventType.TOOL_CALL_ARGS,toolCallId:n,delta:e.delta}),e.toolCallName&&e.delta&&s.push({type:core.EventType.TOOL_CALL_END,toolCallId:n,parentMessageId:e.parentMessageId}),s.length>0?s:[t]}function F(t){switch(t.type){case core.EventType.TEXT_MESSAGE_CHUNK:return Te(t,t);case core.EventType.TOOL_CALL_CHUNK:return ve(t,t);default:return [t]}}function Ee(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="reasoning"}function z(t){let e=t;if(e._getType()!=="ai")return [];let n=e.contentBlocks;return Array.isArray(n)?n.filter(Ee):[]}function J(t){let e=z(t),n=new Map;for(let s of e){let r=s.index??0,i=n.get(r)??[];i.push(s),n.set(r,i);}return n}var L=class extends base.BaseCallbackHandler{name="ag-ui-callback";messageIds=new Map;latestMessageIds=new Map;startedMessageIds=new Set;agentRunIds=new Map;parentToAuthoritativeId=new Map;toolCallInfo=new Map;toolCallNames=new Map;agentTurnTracker=new Map;pendingToolCalls=new Map;accumulatedToolArgs=new Map;streamingToolCallIds=new Map;streamedReasoningRuns=new Set;openReasoningStates=new Map;warnedMissingStreamingContentBlocks=new Set;emitCallback;_enabled;_emitTextMessages;_emitToolCalls;_emitToolResults;_emitThinking;_reasoningEventMode;maxUIPayloadSize;chunkLargeResults;constructor(e){if(super({raiseError:false}),typeof e.publish!="function")throw new TypeError("publish must be a function");this.emitCallback=e.publish,this._enabled=e?.enabled??true,this._emitTextMessages=e?.emitTextMessages??true,this._emitToolCalls=e?.emitToolCalls??true,this._emitToolResults=e?.emitToolResults??true,this._emitThinking=e?.emitThinking??true,this._reasoningEventMode=e?.reasoningEventMode??"thinking",this.maxUIPayloadSize=e?.maxUIPayloadSize??50*1024,this.chunkLargeResults=e?.chunkLargeResults??false;}get enabled(){return this._enabled}set enabled(e){this._enabled=e;}get emitTextMessages(){return this._emitTextMessages}set emitTextMessages(e){this._emitTextMessages=e;}get emitToolCalls(){return this._emitToolCalls}set emitToolCalls(e){this._emitToolCalls=e;}get emitToolResults(){return this._emitToolResults}set emitToolResults(e){this._emitToolResults=e;}get emitThinking(){return this._emitThinking}set emitThinking(e){this._emitThinking=e;}get reasoningEventMode(){return this._reasoningEventMode}set reasoningEventMode(e){this._reasoningEventMode=e;}dispose(){this.messageIds.clear(),this.latestMessageIds.clear(),this.startedMessageIds.clear(),this.agentRunIds.clear(),this.parentToAuthoritativeId.clear(),this.toolCallInfo.clear(),this.toolCallNames.clear(),this.agentTurnTracker.clear(),this.pendingToolCalls.clear(),this.accumulatedToolArgs.clear(),this.streamingToolCallIds.clear(),this.streamedReasoningRuns.clear(),this.openReasoningStates.clear(),this.warnedMissingStreamingContentBlocks.clear();}emitTextChunk(e,n,s){if(!(this.enabled&&this.emitTextMessages))return;let r=F({type:core.EventType.TEXT_MESSAGE_CHUNK,messageId:e,role:n,delta:s});for(let i of r)this.emitCallback(i);}emitToolChunk(e,n,s,r){if(!(this.enabled&&this.emitToolCalls))return;let i=F({type:core.EventType.TOOL_CALL_CHUNK,toolCallId:e,toolCallName:n,delta:s,parentMessageId:r});for(let l of i)this.emitCallback(l);}handleLLMStart(e,n,s,r,i,l,a,u){if(!(this.enabled&&this.emitTextMessages))return;let d=this.getContext(i),c=this.resolveCallbackAgentRunId(s,r,a,d);this.agentRunIds.set(s,c),r&&this.parentToAuthoritativeId.set(r,c),this.prepareAssistantMessage(s,c,this.getString(a,"agui_messageId"));}handleLLMNewToken(e,n,s,r,i,l){if(!this.enabled)return;let a=this.messageIds.get(s);if(a)try{let u=this.resolveAgentRunId(s,r);this.emitStreamingReasoning(l,a,s),e&&e.length>0&&(this.closeStreamingReasoning(s),this.ensureAssistantMessageStarted(a,u)),this.emitStreamingToken(e,a),this.emitToolCalls&&this.trackStreamingToolCallArgs(l,u);}catch{}}handleLLMEnd(e,n,s,r,i){let l=this.resolveAgentRunId(n,s);if(this.collectToolCallsFromOutput(e,l),!this.enabled){let u=this.messageIds.get(n);this.cleanupOpenLifecycles(n,u),u&&this.startedMessageIds.delete(u),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.messageIds.delete(n),this.clearStreamingToolCallIds(l);return}let a=this.messageIds.get(n);this.streamedReasoningRuns.has(n)||this.emitThinkingFromOutput(e,a??n),this.closeStreamingReasoning(n),this.emitAssistantMessageFromOutput(e,a,l),this.emitTextMessageEnd(a),a&&this.startedMessageIds.delete(a),this.messageIds.delete(n),this.clearStreamingToolCallIds(l),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n);}detectAndEmitThinking(e,n){if(!(this.emitThinking&&this.emitTextMessages)||z(e).length===0)return;let r=J(e);for(let[i,l]of r){let a=C(`${n}-reasoning-phase`,i),u=C(`${n}-reasoning-message`,i);this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_START,messageId:a,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_MESSAGE_START,messageId:u,role:"reasoning",timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_START,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_START,timestamp:Date.now()}));let d=l.map(c=>c.reasoning).filter(c=>c.trim().length>0).join("");d&&(this.reasoningEventMode==="reasoning"?this.emitCallback({type:core.EventType.REASONING_MESSAGE_CONTENT,messageId:u,delta:d,timestamp:Date.now()}):this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:d,timestamp:Date.now()})),this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_MESSAGE_END,messageId:u,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_END,messageId:a,timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_END,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_END,timestamp:Date.now()}));}}handleLLMError(e,n,s){let r=this.messageIds.get(n),i=this.resolveAgentRunId(n,s);if(!this.enabled){this.cleanupOpenLifecycles(n,r),r&&this.startedMessageIds.delete(r),this.messageIds.delete(n),this.pendingToolCalls.delete(i),this.agentRunIds.delete(n),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.clearStreamingToolCallIds(i);return}r&&this.startedMessageIds.delete(r),this.messageIds.delete(n),this.pendingToolCalls.delete(i),this.agentRunIds.delete(n),this.closeStreamingReasoning(n),this.streamedReasoningRuns.delete(n),this.warnedMissingStreamingContentBlocks.delete(n),this.clearStreamingToolCallIds(i);}handleToolStart(e,n,s,r,i,l,a){if(!(this.enabled&&this.emitToolCalls))return;let u=this.resolveToolInput(e,n,s,l,a),d={id:u.toolCallId??s,name:u.toolCallName??this.getToolCallName(e,a)};this.toolCallInfo.set(s,d);let c=this.resolveParentAgentRunId(r),p=this.latestMessageIds.get(c);this.emitToolStartSequence(d,p,u.argsDelta);}handleToolEnd(e,n,s){if(!(this.enabled&&this.emitToolCalls))return;let r=this.toolCallInfo.get(n);this.toolCallInfo.delete(n),r?.id&&this.toolCallNames.delete(r.id);let i=this.latestMessageIds.get(this.resolveParentAgentRunId(s));try{let l=r?.id??n;this.emitCallback({type:core.EventType.TOOL_CALL_END,toolCallId:l,timestamp:Date.now()}),this.emitToolResults&&this.emitToolResultWithPolicy(e,l,i,r?.name);}catch{}}handleToolError(e,n,s){if(!(this.enabled&&this.emitToolCalls))return;let r=this.toolCallInfo.get(n);this.toolCallInfo.delete(n),r?.id&&this.accumulatedToolArgs.delete(r.id);try{this.emitCallback({type:core.EventType.TOOL_CALL_END,toolCallId:r?.id??n,timestamp:Date.now()});}catch{}}chunkString(e,n){let s=[],r=e;for(;r.length>0;){if(new Blob([r]).size<=n){s.push(r);break}let i=n,l=r.lastIndexOf(" ",n),a=r.lastIndexOf(`
|
|
2
|
+
`,n),u=Math.max(l,a);if(u>n*.5)i=u;else {for(;i>0&&r.charCodeAt(i-1)>127;)i--;i===0&&(i=n);}s.push(r.substring(0,i)),r=r.substring(i).trim();}return s}emitToolResultWithPolicy(e,n,s,r){let i=X(e),l=w(),a=new Blob([i]).size;if(a<=this.maxUIPayloadSize){this.emitCallback({type:core.EventType.TOOL_CALL_RESULT,messageId:l,toolCallId:n,content:i,role:"tool",timestamp:Date.now()});return}if(this.chunkLargeResults){let p=this.chunkString(i,this.maxUIPayloadSize);for(let g=0;g<p.length;g++)this.emitCallback({type:core.EventType.CUSTOM,name:"LARGE_RESULT_CHUNK",value:{toolCallId:n,chunk:p[g],index:g,total:p.length}});return}let u=` [Truncated: ${a-this.maxUIPayloadSize+50} bytes]`,d=this.maxUIPayloadSize-u.length,c=i.substring(0,Math.max(0,d))+u;this.emitCallback({type:core.EventType.TOOL_CALL_RESULT,messageId:l,toolCallId:n,content:c,role:"tool",timestamp:Date.now()});}asRecord(e){if(typeof e=="object"&&e!==null)return e}getString(e,n){let s=e?.[n];return typeof s=="string"?s:void 0}getContext(e){return this.asRecord(this.asRecord(e)?.options)?.context}resolveCallbackAgentRunId(e,n,s,r){return this.getString(s,"run_id")||this.getString(s,"runId")||this.getString(r,"run_id")||this.getString(r,"runId")||this.getString(s,"agui_runId")||n||e}resolveAgentRunId(e,n){return this.agentRunIds.get(e)||(n?this.parentToAuthoritativeId.get(n):void 0)||n||e}resolveParentAgentRunId(e){return (e?this.parentToAuthoritativeId.get(e):void 0)||e||""}prepareAssistantMessage(e,n,s){let r=s??this.createAssistantMessageId(n);this.messageIds.set(e,r);}ensureAssistantMessageStarted(e,n){this.startedMessageIds.has(e)||(this.startedMessageIds.add(e),this.latestMessageIds.set(n,e),this.emitCallback({type:core.EventType.TEXT_MESSAGE_START,messageId:e,role:"assistant",timestamp:Date.now()}));}createAssistantMessageId(e){let n=this.agentTurnTracker.get(e)||0;return this.agentTurnTracker.set(e,n+1),C(e,n)}emitStreamingToken(e,n){e&&e.length>0&&this.emitTextMessages&&this.emitCallback({type:core.EventType.TEXT_MESSAGE_CONTENT,messageId:n,delta:e,timestamp:Date.now()});}emitAssistantMessageFromOutput(e,n,s){if(!(n&&this.emitTextMessages)||this.startedMessageIds.has(n))return;let r=this.getOutputTextContent(e);typeof r=="string"&&r.length>0&&(this.ensureAssistantMessageStarted(n,s),this.emitStreamingToken(r,n));}trackStreamingToolCallArgs(e,n){let s=this.getToolCallChunks(e);if(s.length===0)return;let r=[...this.pendingToolCalls.get(n)||[]],i=false;for(let l of s){let a=this.resolveStreamingToolCallId(n,l);if(a){if(l.name&&this.toolCallNames.set(a,l.name),typeof l.args=="string"){let u=this.accumulatedToolArgs.get(a)||"",d=u+l.args;d!==u&&this.accumulatedToolArgs.set(a,d);}r.includes(a)||(r.push(a),i=true);}}i&&this.pendingToolCalls.set(n,r);}emitStreamingReasoning(e,n,s){if(!(this.emitThinking&&this.emitTextMessages))return;let r=this.getStreamingReasoningChunks(e,s);if(r.length!==0){this.streamedReasoningRuns.add(s);for(let i of r){let l=this.ensureStreamingReasoningState(s,n,i.index);typeof i.reasoning=="string"&&i.reasoning.length>0&&(this.reasoningEventMode==="reasoning"?this.emitCallback({type:core.EventType.REASONING_MESSAGE_CONTENT,messageId:l.messageId,delta:i.reasoning,timestamp:Date.now()}):this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:i.reasoning,timestamp:Date.now()}));}}}getStreamingReasoningChunks(e,n){let r=this.asRecord(this.asRecord(e)?.chunk)?.message,i=this.asRecord(r),l=this.getStreamingContentBlocks(r);return l.length===0&&this.hasRawStreamingReasoning(i)&&this.warnMissingStreamingContentBlocks(n),l.map(a=>this.asRecord(a)).flatMap(a=>{let u=this.getString(a,"reasoning");return a?.type!=="reasoning"?[]:[{index:typeof a.index=="number"?a.index:0,reasoning:u}]})}getStreamingContentBlocks(e){let n=this.asRecord(e);return Array.isArray(n?.contentBlocks)?n.contentBlocks:[]}hasRawStreamingReasoning(e){return Array.isArray(e?.content)?e.content.some(n=>{let s=this.asRecord(n);return s?.type==="reasoning"&&typeof s.reasoning=="string"}):false}warnMissingStreamingContentBlocks(e){!e||this.warnedMissingStreamingContentBlocks.has(e)||(this.warnedMissingStreamingContentBlocks.add(e),console.warn("[AG-UI] Stream chunk exposed reasoning outside LangChain contentBlocks; reasoning events were skipped for this chunk."));}ensureStreamingReasoningState(e,n,s){let r=`${e}:${s}`,i=this.openReasoningStates.get(r);if(i)return i;let l={phaseId:C(`${n}-reasoning-phase`,s),messageId:C(`${n}-reasoning-message`,s)};return this.openReasoningStates.set(r,l),this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_START,messageId:l.phaseId,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_MESSAGE_START,messageId:l.messageId,role:"reasoning",timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_START,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_START,timestamp:Date.now()})),l}closeStreamingReasoning(e){let n=`${e}:`;for(let[s,r]of this.openReasoningStates)s.startsWith(n)&&(this.reasoningEventMode==="reasoning"?(this.emitCallback({type:core.EventType.REASONING_MESSAGE_END,messageId:r.messageId,timestamp:Date.now()}),this.emitCallback({type:core.EventType.REASONING_END,messageId:r.phaseId,timestamp:Date.now()})):(this.emitCallback({type:core.EventType.THINKING_TEXT_MESSAGE_END,timestamp:Date.now()}),this.emitCallback({type:core.EventType.THINKING_END,timestamp:Date.now()})),this.openReasoningStates.delete(s));}getToolCallChunks(e){let n=this.asRecord(this.asRecord(e)?.chunk),s=this.asRecord(n?.message),r=this.asRecord(s?.kwargs),i=s?.tool_call_chunks??r?.tool_call_chunks;return Array.isArray(i)?i.map(l=>{let a=this.asRecord(l);return {id:this.getString(a,"id"),name:this.getString(a,"name"),args:this.getString(a,"args"),index:typeof a?.index=="number"?a.index:void 0}}):[]}resolveStreamingToolCallId(e,n){if(n.id){let r=this.getStreamingToolCallKey(e,n.index);return r&&this.streamingToolCallIds.set(r,n.id),n.id}let s=this.getStreamingToolCallKey(e,n.index);if(s)return this.streamingToolCallIds.get(s)}getStreamingToolCallKey(e,n){if(typeof n=="number")return `${e}:${n}`}clearStreamingToolCallIds(e){let n=`${e}:`;for(let s of this.streamingToolCallIds.keys())s.startsWith(n)&&this.streamingToolCallIds.delete(s);}collectToolCallsFromOutput(e,n){try{let s=this.getOutputToolCalls(e);if(s.length===0)return;let r=[...this.pendingToolCalls.get(n)||[]];for(let i of s)i.id&&!r.includes(i.id)&&(r.push(i.id),i.function?.name&&this.toolCallNames.set(i.id,i.function.name),i.function?.arguments&&this.accumulatedToolArgs.set(i.id,i.function.arguments));this.pendingToolCalls.set(n,r);}catch{}}getOutputToolCalls(e){let n=this.asRecord(e),s=this.asRecord(n?.kwargs),r=n?.tool_calls??s?.tool_calls;if(Array.isArray(r))return r.map(u=>{let d=this.asRecord(u),c=this.asRecord(d?.function);return {id:this.getString(d,"id"),function:{name:this.getString(c,"name"),arguments:this.getString(c,"arguments")}}});let i=this.getOutputMessage(e),a=this.asRecord(i)?.tool_calls;return Array.isArray(a)?a.map(u=>{let d=this.asRecord(u),c=this.asRecord(d?.function);return {id:this.getString(d,"id"),function:{name:this.getString(c,"name")??this.getString(d,"name"),arguments:this.getString(c,"arguments")??this.stringifyIfDefined(d?.args)}}}):[]}emitThinkingFromOutput(e,n){try{let r=this.asRecord(e)?.generations;if(!Array.isArray(r)||r.length===0)return;let i=r[0];if(!Array.isArray(i)||i.length===0)return;let a=this.asRecord(i[0])?.message;if(!a)return;this.detectAndEmitThinking(a,n);}catch{}}emitTextMessageEnd(e){e&&this.startedMessageIds.has(e)&&this.emitCallback({type:core.EventType.TEXT_MESSAGE_END,messageId:e,timestamp:Date.now()});}cleanupOpenLifecycles(e,n){this.closeStreamingReasoning(e),this.emitTextMessageEnd(n);}resolveToolInput(e,n,s,r,i){let l=s,a=this.getToolCallName(e,i),u=n||void 0,d=this.getString(r,"tool_call_id");if(d)return {toolCallId:d,toolCallName:this.resolveStoredToolName(d,a),argsDelta:u};let c=this.parseToolInput(n);c&&(l=this.getString(c,"tool_call_id")||this.getString(c,"id")||l,a=this.getString(c,"name")||a,u=this.resolveToolArgsDelta(c,n));let p=l===s?this.findMatchingAccumulatedToolCallId(n):void 0;return p&&(l=p),{toolCallId:l,toolCallName:this.resolveStoredToolName(l,a),argsDelta:u}}getToolCallName(e,n){if(n)return n;let s=this.asRecord(e);if(!s)return "unknown_tool";let r=s.getName?.();return typeof r=="string"&&r.length>0?r:s.kwargs?.name||s.name||s.func?.name||s.toolName||s._name||"unknown_tool"}parseToolInput(e){if(e)try{return this.asRecord(JSON.parse(e))}catch{return}}findMatchingAccumulatedToolCallId(e){if(e){for(let[n,s]of this.accumulatedToolArgs)if(e.includes(s)||s.includes(e))return n}}resolveStoredToolName(e,n){let s=this.toolCallNames.get(e);return s&&s!=="unknown_tool"?s:n}emitToolStartSequence(e,n,s){try{this.emitCallback({type:core.EventType.TOOL_CALL_START,toolCallId:e.id,toolCallName:e.name,parentMessageId:n,timestamp:Date.now()});let r=s??this.accumulatedToolArgs.get(e.id);if(!r)return;this.emitCallback({type:core.EventType.TOOL_CALL_ARGS,toolCallId:e.id,delta:r,timestamp:Date.now()}),this.accumulatedToolArgs.delete(e.id);}catch{}}getOutputMessage(e){let s=this.asRecord(e)?.generations;if(!Array.isArray(s)||s.length===0)return;let r=s[0];if(!(!Array.isArray(r)||r.length===0))return this.asRecord(r[0])?.message}getOutputTextContent(e){let n=this.asRecord(e),s=this.getOutputMessage(e),r=this.asRecord(s),i=r?.content;if(typeof i=="string"&&i.length>0)return i;let l=this.getString(this.asRecord(r?.kwargs),"text");if(l&&l.length>0)return l;let a=r?.contentBlocks;if(Array.isArray(a)){let g=a.map(m=>this.asRecord(m)).filter(m=>m?.type==="text").map(m=>this.getString(m,"text")).filter(m=>!!(m&&m.length>0)).join("");if(g.length>0)return g}let u=Array.isArray(n?.generations)?n.generations:void 0,d=Array.isArray(u?.[0])?u[0]:void 0,p=this.asRecord(d?.[0])?.text;return typeof p=="string"&&p.length>0?p:void 0}resolveToolArgsDelta(e,n){if(typeof e.args=="string")return e.args;let s=this.stringifyIfDefined(e.args);if(s)return s;if(typeof e.arguments=="string")return e.arguments;let r=this.stringifyIfDefined(e.arguments);return r||n||void 0}stringifyIfDefined(e){if(!(typeof e>"u")){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}};var Me="[unserializable content]",_e="{}";function q(t){return typeof t=="object"&&t!==null}function Q(t){try{return JSON.stringify(t)}catch{return}}function _(t){if(typeof t>"u")return "";if(typeof t=="string")return t;let e=Q(t);return typeof e=="string"?e:Me}function Be(t){return q(t)?t.type==="text"&&typeof t.text=="string":false}function xe(t){return !q(t)||t.type!=="binary"||typeof t.mimeType!="string"||t.id!==void 0&&typeof t.id!="string"||t.url!==void 0&&typeof t.url!="string"||t.data!==void 0&&typeof t.data!="string"||t.filename!==void 0&&typeof t.filename!="string"?false:typeof t.id=="string"||typeof t.url=="string"||typeof t.data=="string"}function Ge(t){return Array.isArray(t)?t.every(e=>Be(e)||xe(e)):false}function W(t){switch(t){case "assistant":case "user":case "system":case "developer":case "tool":case "reasoning":return t;default:return}}function Ne(t,e){return typeof e=="string"||t==="user"&&Ge(e)?e:_(e)}function Ue(t,e){let n=e._getType?.(),s=W(e.role),r="assistant",i,l;if(t instanceof messages.HumanMessage||s==="user"||n==="human")return {role:"user"};if(t instanceof messages.AIMessage||s==="assistant"||n==="ai"){let a=e.tool_calls||e.kwargs?.tool_calls;return a&&a.length>0&&(i=a.map(u=>({id:u.id||w(),type:"function",function:{name:String(u.name??"unknown_tool"),arguments:typeof u.args=="string"?u.args:Q(u.args)??_e}}))),{role:"assistant",toolCalls:i}}return t instanceof messages.ToolMessage||s==="tool"||n==="tool"?(l=e.tool_call_id||e.kwargs?.tool_call_id,{role:"tool",toolCallId:l}):t instanceof messages.SystemMessage||s==="system"||n==="system"?{role:"system"}:t instanceof messages.ChatMessage?(r=W(t.role)??"assistant",{role:r}):s?{role:s}:{role:r}}function Y(t){let e=t,n=e.id||w(),{role:s,toolCalls:r,toolCallId:i}=Ue(t,e);if(s==="assistant")return {id:n,role:s,content:_(e.content),toolCalls:r,name:e.name};if(s==="tool"){if(!i)throw new Error("Cannot map a tool-role message without a toolCallId.");return {id:n,role:s,content:_(e.content),toolCallId:i}}return s==="user"?{id:n,role:s,content:Ne(s,e.content),name:e.name}:s==="system"?{id:n,role:s,content:_(e.content),name:e.name}:s==="developer"?{id:n,role:s,content:_(e.content),name:e.name}:{id:n,role:s,content:_(e.content)}}function Z(t,e){return fastJsonPatch.compare(t,e)}function x(t){try{let e=core.EventSchemas.safeParse(t);return e.success?{success:!0,data:t}:{success:!1,error:{message:"Event validation failed",issues:e.error.issues.map(n=>({path:n.path,message:n.message}))}}}catch(e){return {success:false,error:{message:e instanceof Error?e.message:"Unknown validation error",issues:[]}}}}function ee(t){return x(t).success}function B(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function te(t){let e=t.context,n=B(e?.thread_id)||B(e?.threadId),s=B(e?.run_id)||B(e?.runId),r=B(t.threadIdOverride),i=B(t.runIdOverride);return {threadId:n||r||"",runId:s||i||t.createFallbackRunId()}}var ne=zod.z.object({publish:zod.z.custom(t=>typeof t=="function",{message:"publish must be a function"}),emitStateSnapshots:zod.z.enum(["initial","final","all","none"]).default("initial"),emitActivities:zod.z.boolean().default(false),threadIdOverride:zod.z.string().optional(),runIdOverride:zod.z.string().optional(),errorDetailLevel:zod.z.enum(["full","message","code","none"]).default("message"),stateMapper:zod.z.custom().optional(),activityMapper:zod.z.custom().optional(),validateEvents:zod.z.union([zod.z.boolean(),zod.z.literal("strict")]).default(false)});function Pe(t){return t===true||t==="strict"}function T(t){return typeof t=="object"&&t!==null}function He(t){return T(t)&&!Array.isArray(t)}function Fe(t){return T(t)&&"content"in t}function D(t){return T(t)&&Array.isArray(t.messages)?t.messages.filter(Fe):[]}function ze(t){if(T(t))return t.error}function je(t){if(T(t))return t.context}function Ke(t){if(T(t)&&T(t.config))return t.config.input}function $e(t){if(T(t)&&T(t.config)&&T(t.config.model))return typeof t.config.model._modelType=="string"?t.config.model._modelType:void 0}function Ve(t){return T(t)&&typeof t.type=="string"?t.type:"[unknown]"}function Xe(t){let e=D(t).at(-1);return e&&typeof e.content=="string"?e.content.substring(0,100)+(e.content.length>100?"...":""):"[no input preview]"}function Je(t){let e=D(t).at(-1);return Array.isArray(e?.toolCalls)&&e.toolCalls.length>0?"tool_calls":e?.content?"text":"unknown"}function We(t){return D(t).some(e=>Array.isArray(e.toolCalls)&&e.toolCalls.length>0)}function se(t,e,n,s,r,i,l){if(!e)return;let a=`activity-${e}-${n}`,u={status:r,timestamp:Date.now(),...l},d=i?i(u):u;if(!s.currentActivityId||s.currentActivityId!==a)s.currentActivityId=a,s.currentActivityType="AGENT_STEP",s.activityContent=d,t({type:core.EventType.ACTIVITY_SNAPSHOT,messageId:a,activityType:"AGENT_STEP",content:d,replace:true});else {let c=Z(s.activityContent,d);c.length>0&&(s.activityContent=d,t({type:core.EventType.ACTIVITY_DELTA,messageId:a,activityType:"AGENT_STEP",patch:c}));}}function re(t){let e=ne.parse(t),n=c=>{if(Pe(e.validateEvents)&&!ee(c)){let g=x(c).error;if(e.validateEvents==="strict")throw new Error(`Invalid AG-UI event: ${g?.message}`);console.warn("[AG-UI Validation] Invalid event:",Ve(c),g);}e.publish(c);},s=(c,p)=>c==="none"?false:c==="all"?true:c===p,r=c=>{let p=b(c),g=e.stateMapper?e.stateMapper(p):p;if(!e.stateMapper&&He(g)){let{messages:m,...I}=g;return I}return g},i=(c,p)=>{if(!s(e.emitStateSnapshots,c))return;let g=r(p);n({type:core.EventType.STATE_SNAPSHOT,snapshot:g,timestamp:Date.now()});},l=new Map,a=new WeakMap,u=zod.z.object({run_id:zod.z.string().optional(),runId:zod.z.string().optional(),thread_id:zod.z.string().optional(),threadId:zod.z.string().optional()}),d=c=>{let p=T(c)?c:void 0,g=p?a.get(p):void 0,m=te({context:je(c),threadIdOverride:e.threadIdOverride,runIdOverride:e.runIdOverride,createFallbackRunId:()=>g??crypto.randomUUID()});p&&!a.has(p)&&a.set(p,m.runId);let I=l.get(m.runId);if(I)return !I.threadId&&m.threadId&&(I.threadId=m.threadId),I;let S={threadId:m.threadId,runId:m.runId,modelTurnIndex:0,activityTracker:{currentActivityId:void 0,currentActivityType:"AGENT_STEP",activityContent:{}}};return l.set(S.runId,S),S};return langchain.createMiddleware({name:"ag-ui-lifecycle",contextSchema:u,beforeAgent:(c,p)=>{let g=d(p);g.modelTurnIndex=0,g.currentStepName=void 0,g.activityTracker.currentActivityId=void 0,g.activityTracker.currentActivityType="AGENT_STEP",g.activityTracker.activityContent={};try{n({type:core.EventType.RUN_STARTED,threadId:g.threadId,runId:g.runId,input:b(Ke(p)),timestamp:Date.now()}),i("initial",c);let m=D(c);m.length>0&&n({type:core.EventType.MESSAGES_SNAPSHOT,messages:m.map(Y),timestamp:Date.now()});}catch{}return {}},beforeModel:(c,p)=>{let g=d(p),m=g.modelTurnIndex++,S=`model_call_${C(g.runId,m)}`;g.currentStepName=S;try{n({type:core.EventType.STEP_STARTED,stepName:S,timestamp:Date.now()}),e.emitActivities&&se(n,g.runId,m,g.activityTracker,"started",e.activityMapper,{stepName:S,modelName:$e(p)??"unknown",inputPreview:Xe(c)});}catch{}return {}},afterModel:(c,p)=>{let g=d(p);try{if(n({type:core.EventType.STEP_FINISHED,stepName:g.currentStepName||"",timestamp:Date.now()}),e.emitActivities&&g.currentStepName){let m=g.modelTurnIndex-1;se(n,g.runId,m,g.activityTracker,"completed",e.activityMapper,{stepName:g.currentStepName,outputType:Je(c),hasToolCalls:We(c)});}}catch{}return g.currentStepName=void 0,{}},afterAgent:(c,p)=>{let g=d(p);try{i("final",c);let m=ze(c);if(m){let I=m instanceof Error?m.message:String(m);n({type:core.EventType.RUN_ERROR,message:e.errorDetailLevel==="full"||e.errorDetailLevel==="message"?I:"",code:"AGENT_EXECUTION_ERROR",timestamp:Date.now()});}else n({type:core.EventType.RUN_FINISHED,threadId:g.threadId,runId:g.runId,timestamp:Date.now()});}catch{}return l.delete(g.runId),T(p)&&a.delete(p),{}}})}var qe=new TextEncoder,Qe="text/event-stream",Ye="no-cache",Ze="keep-alive",et={"Content-Type":Qe,"Cache-Control":Ye,Connection:Ze};function j(t){return qe.encode(`data: ${JSON.stringify(t)}
|
|
3
|
+
|
|
4
|
+
`)}function K(t){return new ReadableStream({async start(e){try{for await(let n of t)e.enqueue(j(n));e.close();}catch(n){e.error(n);}}})}function ie(t,e={}){let n=new Headers(e.headers);for(let[s,r]of Object.entries(et))n.has(s)||n.set(s,r);return new Response(t,{...e,headers:n})}var ae=j;function oe(t,e="sse"){return t||ae}function tt(t){return t===true||t==="strict"}function de(t){return typeof t=="object"&&t!==null}function M(t,e){if(!de(t))return;let n=t[e];return typeof n=="string"?n:void 0}function le(t){let e=M(t,"runId"),n=M(t,"threadId");if(!(!e||typeof n>"u"))return {runId:e,threadId:n}}function nt(t){if(typeof t=="string")return {message:t};if(t instanceof Error){let e=typeof t.code=="string"?t.code:void 0;return {message:t.message,code:e}}if(de(t)){let e=typeof t.message=="string"?t.message:"Agent execution failed",n=typeof t.code=="string"?t.code:void 0;return {message:e,code:n}}return {message:"Agent execution failed"}}function ce(t={}){let e=oe(t.serializer,t.transport??"sse"),n=t.validateEvents??false,s=new Set,r=new Set,i=[],l=[],a=new Set,u=new Set,d=new Set,c=new Set,p=false,g=false,m,I=o=>{if(tt(n)){let A=x(o);if(!A.success){if(n==="strict")throw new Error(`Invalid AG-UI event: ${A.error?.message}`);console.warn("[AG-UI Validation] Invalid event:",o.type,A.error);}}i.push(o);for(let A of s)A(o);let h=e(o);for(let A of r)A.enqueue(h);},S=()=>{for(let o of [...a])a.delete(o),I({type:core.EventType.TEXT_MESSAGE_END,messageId:o,timestamp:Date.now()});for(let o of [...u])u.delete(o),I({type:core.EventType.TOOL_CALL_END,toolCallId:o,timestamp:Date.now()});for(let o of [...d])d.delete(o),I({type:core.EventType.REASONING_MESSAGE_END,messageId:o,timestamp:Date.now()});for(let o of [...c])c.delete(o),I({type:core.EventType.REASONING_END,messageId:o,timestamp:Date.now()});},$=()=>{for(let o of r)o.close();r.clear();},N=o=>{g||(S(),g=true,I(o),$());},me=()=>{g||(g=true,$());},fe=o=>{if(!(g||p))for(p=true,m=le(o),I(o);l.length>0&&!g;){let h=l.shift();h&&V(h);}},U=(o,h,A)=>{let E=M(o,A);return E&&!h.has(E)?(h.add(E),I(o),true):false},P=(o,h,A)=>{let E=M(o,A);return E&&h.has(E)?(I(o),true):false},O=(o,h,A)=>{let E=M(o,A);return E&&h.has(E)?(h.delete(E),I(o),true):false},he=o=>{switch(o.type){case core.EventType.TEXT_MESSAGE_START:return U(o,a,"messageId");case core.EventType.TEXT_MESSAGE_CONTENT:return P(o,a,"messageId");case core.EventType.TEXT_MESSAGE_END:return O(o,a,"messageId");default:return false}},Ie=o=>{switch(o.type){case core.EventType.TOOL_CALL_START:return U(o,u,"toolCallId");case core.EventType.TOOL_CALL_ARGS:return P(o,u,"toolCallId");case core.EventType.TOOL_CALL_END:return O(o,u,"toolCallId");default:return false}},ye=o=>{switch(o.type){case core.EventType.REASONING_START:return U(o,c,"messageId");case core.EventType.REASONING_END:return O(o,c,"messageId");case core.EventType.REASONING_MESSAGE_START:return U(o,d,"messageId");case core.EventType.REASONING_MESSAGE_CONTENT:return P(o,d,"messageId");case core.EventType.REASONING_MESSAGE_END:return O(o,d,"messageId");default:return false}},Ae=o=>{if(o.type===core.EventType.RUN_ERROR)return N(o),true;if(o.type!==core.EventType.RUN_FINISHED)return false;let h=le(o)??m;return N({...o,runId:h?.runId??M(o,"runId"),threadId:h?.threadId??M(o,"threadId")}),true},V=o=>{if(!g){if(o.type===core.EventType.RUN_STARTED){fe(o);return}if(!p){l.push(o);return}he(o)||Ie(o)||ye(o)||Ae(o)||I(o);}};return {publish(o){V(o);},complete(o){if(!g){if(!m)throw new Error("Cannot complete a run that has not been started. A `RUN_STARTED` event must be published first.");N({type:core.EventType.RUN_FINISHED,threadId:m.threadId,runId:m.runId,result:o,timestamp:Date.now()});}},error(o){if(g)return;let h=nt(o);N({type:core.EventType.RUN_ERROR,message:h.message,code:h.code,timestamp:Date.now()});},close(){me();},subscribe(o){return s.add(o),()=>{s.delete(o);}},toReadableStream(){let o;return new ReadableStream({start(h){o=h;for(let A of i)h.enqueue(e(A));if(g){h.close();return}r.add(h);},cancel(){o&&r.delete(o);}})}}}function rt(t){return t instanceof DOMException&&t.name==="AbortError"||t instanceof Error&&t.name==="AbortError"}function it(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function at(t){return it(t.state)?{...t.state,messages:t.messages}:{messages:t.messages,state:t.state}}function ot(t){return e=>{e.type!==core.EventType.RUN_FINISHED&&t.publish(e);}}async function lt(t){let e;for await(let n of t)e=n;return e}function dt(){let t=[],e=[],n=false,s,r=false,i=()=>{for(;t.length>0&&e.length>0;){let d=e.shift(),c=t.shift();d&&typeof c<"u"&&d.resolve({value:c,done:false});}},l=()=>{if(!(typeof s>"u"))for(let d of e.splice(0))d.reject(s);},a=()=>{if(n)for(let d of e.splice(0))d.resolve({value:void 0,done:true});},u=()=>{i(),!(t.length>0||e.length===0)&&(l(),a());};return {push(d){n||typeof s<"u"||(t.push(d),u());},close(){n||typeof s<"u"||(n=true,u());},error(d){n||typeof s<"u"||(s=d,u());},iterable:{async*[Symbol.asyncIterator](){if(r)throw new Error("AGUI adapter event streams support a single consumer.");for(r=true;;){if(t.length>0){yield t.shift();continue}if(typeof s<"u")throw s;if(n)return;let d=await new Promise((c,p)=>{e.push({resolve:c,reject:p});});if(d.done)return;yield d.value;}}}}}function ue(t){if(typeof t.agentFactory!="function")throw new TypeError("agentFactory must be a function that accepts { input, middleware } and returns an agent with a stream() method");return {stream(e,n={}){let s=ce({validateEvents:t.validateEvents}),r=dt(),i=s.subscribe(d=>{r.push(d);}),l=new L({publish:s.publish,...t.callbackOptions}),a=re({publish:ot(s),validateEvents:t.validateEvents??false,emitStateSnapshots:t.emitStateSnapshots??"initial",emitActivities:t.emitActivities??false,errorDetailLevel:t.errorDetailLevel??"message",runIdOverride:e.runId,threadIdOverride:e.threadId});return (async()=>{try{let c=await(await t.agentFactory({input:e,middleware:a})).stream(at(e),{callbacks:[l],signal:n.signal,streamMode:"values",configurable:{run_id:e.runId,thread_id:e.threadId},context:{run_id:e.runId,thread_id:e.threadId,signal:n.signal}}),p=await lt(c);n.signal?.aborted?s.close():s.complete(p);}catch(d){n.signal?.aborted||rt(d)?s.close():s.error(d);}finally{try{l.dispose();}catch(d){console.error("Failed to dispose AG-UI callback handler.",d);}try{i();}catch(d){console.error("Failed to unsubscribe AG-UI adapter listener.",d);}r.close();}})().catch(d=>{r.error(d);}),Promise.resolve(r.iterable)}}}function ge(t,e){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}function ut(t){return t.headers.get("content-type")?.toLowerCase().includes("application/json")??false}async function gt(t){let e=await t.json();return core.RunAgentInputSchema.parse(e)}function pe(t){let e=ue(t);return {async handle(n){if(n.method!=="POST")return new Response(JSON.stringify({error:"Method Not Allowed"}),{status:405,headers:{"Content-Type":"application/json",Allow:"POST"}});if(!ut(n))return ge(415,"Unsupported Media Type");let s;try{s=await gt(n);}catch(i){return ge(400,i instanceof Error?i.message:"Invalid request body")}let r=await e.stream(s,{signal:n.signal});return ie(K(r))}}}function hn(t){return pe(t)}exports.createAGUIBackend=hn;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { d as AGUIAgentLike, a as AGUIAdapterConfig, e as AGUIAgentRunOptions, c as AGUIAgentFactory$1 } from './create-agui-adapter-B6ZmSEvX.cjs';
|
|
2
|
+
import '@ag-ui/core';
|
|
3
|
+
import './callbacks.cjs';
|
|
4
|
+
import '@langchain/core/callbacks/base';
|
|
5
|
+
import './middleware.cjs';
|
|
6
|
+
import 'langchain';
|
|
7
|
+
import '@langchain/core/tools';
|
|
8
|
+
import 'zod';
|
|
9
|
+
|
|
10
|
+
interface AGUIBackend$1 {
|
|
11
|
+
handle(request: Request): Promise<Response>;
|
|
12
|
+
}
|
|
13
|
+
type AGUIBackendRunOptions$1 = AGUIAgentRunOptions;
|
|
14
|
+
type AGUIBackendAgentLike$1 = AGUIAgentLike;
|
|
15
|
+
type AGUIBackendConfig$1 = AGUIAdapterConfig;
|
|
16
|
+
|
|
17
|
+
type AGUIAgentFactory = AGUIAgentFactory$1;
|
|
18
|
+
type AGUIBackend = AGUIBackend$1;
|
|
19
|
+
type AGUIBackendAgentLike = AGUIBackendAgentLike$1;
|
|
20
|
+
type AGUIBackendConfig = AGUIBackendConfig$1;
|
|
21
|
+
type AGUIBackendRunOptions = AGUIBackendRunOptions$1;
|
|
22
|
+
declare function createAGUIBackend(config: AGUIBackendConfig): AGUIBackend;
|
|
23
|
+
|
|
24
|
+
export { type AGUIAgentFactory, type AGUIBackend, type AGUIBackendAgentLike, type AGUIBackendConfig, type AGUIBackendRunOptions, createAGUIBackend };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { d as AGUIAgentLike, a as AGUIAdapterConfig, e as AGUIAgentRunOptions, c as AGUIAgentFactory$1 } from './create-agui-adapter-C3WiiO-D.js';
|
|
2
|
+
import '@ag-ui/core';
|
|
3
|
+
import './callbacks.js';
|
|
4
|
+
import '@langchain/core/callbacks/base';
|
|
5
|
+
import './middleware.js';
|
|
6
|
+
import 'langchain';
|
|
7
|
+
import '@langchain/core/tools';
|
|
8
|
+
import 'zod';
|
|
9
|
+
|
|
10
|
+
interface AGUIBackend$1 {
|
|
11
|
+
handle(request: Request): Promise<Response>;
|
|
12
|
+
}
|
|
13
|
+
type AGUIBackendRunOptions$1 = AGUIAgentRunOptions;
|
|
14
|
+
type AGUIBackendAgentLike$1 = AGUIAgentLike;
|
|
15
|
+
type AGUIBackendConfig$1 = AGUIAdapterConfig;
|
|
16
|
+
|
|
17
|
+
type AGUIAgentFactory = AGUIAgentFactory$1;
|
|
18
|
+
type AGUIBackend = AGUIBackend$1;
|
|
19
|
+
type AGUIBackendAgentLike = AGUIBackendAgentLike$1;
|
|
20
|
+
type AGUIBackendConfig = AGUIBackendConfig$1;
|
|
21
|
+
type AGUIBackendRunOptions = AGUIBackendRunOptions$1;
|
|
22
|
+
declare function createAGUIBackend(config: AGUIBackendConfig): AGUIBackend;
|
|
23
|
+
|
|
24
|
+
export { type AGUIAgentFactory, type AGUIBackend, type AGUIBackendAgentLike, type AGUIBackendConfig, type AGUIBackendRunOptions, createAGUIBackend };
|