@picoflow/ezgraph 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +174 -68
  2. package/dist/framework/base-graph.js +1 -1
  3. package/dist/framework/conversation-node.js +1 -1
  4. package/dist/framework/conversation-runner.js +1 -1
  5. package/dist/framework/graph-engine.js +1 -1
  6. package/dist/framework/graph-node.js +1 -1
  7. package/dist/framework/graph-state.js +1 -1
  8. package/dist/framework/langchain-llm-gateway.js +1 -1
  9. package/dist/framework/langchain-provider.adapter.js +1 -1
  10. package/dist/framework/model-catalog.js +1 -1
  11. package/dist/framework/node-invocation.js +1 -0
  12. package/dist/framework/node-outcome.js +1 -1
  13. package/dist/framework/node-state.js +1 -1
  14. package/dist/framework/openai-auth-provider.js +4 -0
  15. package/dist/framework/persistence/session-manager.js +1 -1
  16. package/dist/framework/state-graph-ext.js +1 -1
  17. package/dist/framework/tool-response.js +1 -0
  18. package/dist/index.js +1 -1
  19. package/dist/types/npmlib/src/index.d.ts +5 -5
  20. package/dist/types/src/framework/base-graph.d.ts +8 -0
  21. package/dist/types/src/framework/conversation-node.d.ts +8 -14
  22. package/dist/types/src/framework/conversation-runner.d.ts +3 -3
  23. package/dist/types/src/framework/graph-llm.config.d.ts +1 -1
  24. package/dist/types/src/framework/graph-node.d.ts +24 -21
  25. package/dist/types/src/framework/graph-registry.d.ts +3 -0
  26. package/dist/types/src/framework/graph-state.d.ts +0 -2
  27. package/dist/types/src/framework/model-catalog.d.ts +20 -1
  28. package/dist/types/src/framework/node-invocation.d.ts +12 -0
  29. package/dist/types/src/framework/node-outcome.d.ts +1 -30
  30. package/dist/types/src/framework/node-state.d.ts +2 -1
  31. package/dist/types/src/framework/openai-auth-provider.d.ts +12 -0
  32. package/dist/types/src/framework/persistence/session-manager.d.ts +1 -0
  33. package/dist/types/src/framework/state-graph-ext.d.ts +2 -8
  34. package/dist/types/src/framework/tool-response.d.ts +25 -0
  35. package/package.json +1 -1
  36. package/dist/framework/conversation-tool-result.js +0 -1
  37. package/dist/types/src/framework/conversation-tool-result.d.ts +0 -19
package/README.md CHANGED
@@ -1,88 +1,191 @@
1
1
  # EZGraph
2
2
 
3
- EZGraph is a pre-release TypeScript application layer for durable,
4
- multi-turn conversational workflows. It is built on LangGraph and LangChain,
5
- but gives each conversation an explicit graph, typed node state, durable session
6
- handling, and code-owned outcomes for validation, confirmation, and routing.
3
+ EZGraph is a TypeScript application layer for durable, guided conversations on
4
+ [LangGraph](https://langchain-ai.github.io/langgraphjs/). It gives customer-facing
5
+ chat applications an explicit contract for node-owned state, decorated tools,
6
+ durable sessions, and deterministic transitions—without requiring an EZGraph
7
+ account, cloud service, or dependency-injection framework.
7
8
 
8
- It is provider-neutral and framework-neutral: use it with the model provider
9
- and Node.js HTTP framework you already run.
9
+ Use it when a conversation is an application: it gathers validated facts,
10
+ applies business policy, presents exact reviews or decisions, and resumes safely
11
+ across requests.
10
12
 
11
- ## What it provides
13
+ > **Upgrading:** Version 0.0.7 contains breaking changes from 0.0.6; see the [EZGraph documentation](https://www.picoflow.io/ezgraph) before upgrading.
12
14
 
13
- - Graph and node primitives for staged conversations, rather than one large
14
- prompt or an implicit agent loop.
15
- - Per-node state, named history spaces, and typed outcomes such as `stay()`,
16
- `advance()`, `finish()`, and `quit()`.
17
- - One versioned session document per conversation, backed by memory, SQLite,
18
- MongoDB, or Azure Cosmos DB.
19
- - A model and tool loop that is bounded and owned by the graph, while business
20
- validation and routing remain ordinary application code.
21
- - Provider adapters and a typed model catalog, with support for OpenAI,
22
- Anthropic, Google, Azure OpenAI, and custom compatible endpoints.
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @picoflow/ezgraph zod
23
19
 
24
- For the product overview, tutorial, and full developer guide, visit
25
- [picoflow.io/ezgraph](https://www.picoflow.io/ezgraph/).
20
+ # Install only the LangChain provider adapter your application uses.
21
+ npm install @langchain/openai
22
+ # or: npm install @langchain/anthropic
23
+ # or: npm install @langchain/google
24
+ ```
26
25
 
27
- ## Requirements
26
+ Requirements:
28
27
 
29
28
  - Node.js 22.5 or later
30
29
  - TypeScript 5.x
31
- - A model-provider package and credentials for the provider you choose
30
+ - `experimentalDecorators` and `emitDecoratorMetadata` enabled in `tsconfig.json`
31
+ - `import "reflect-metadata"` once, before any module that declares `@Tool`
32
32
 
33
- Tool handlers use method decorators. Enable `experimentalDecorators` and
34
- `emitDecoratorMetadata` in `tsconfig.json`, and import `reflect-metadata` once
35
- at the very top of your application entry point.
33
+ EZGraph is ESM. TypeScript applications should use `module` and
34
+ `moduleResolution` set to `NodeNext`.
36
35
 
37
- ## Install
36
+ ## The conversation contract
38
37
 
39
- ```bash
40
- npm install @picoflow/ezgraph
38
+ Each node owns the facts it validates. A tool handler saves valid state, then
39
+ returns exactly one response:
41
40
 
42
- # Install only the provider adapter you use.
43
- npm install @langchain/openai
44
- # or: npm install @langchain/anthropic
45
- # or: npm install @langchain/google
41
+ | Return | Use it for |
42
+ | --- | --- |
43
+ | `stay(feedback)` | Validation failed; continue collecting in the current node. |
44
+ | `go(TargetNode)` | Enter another registered conversational node now. |
45
+ | `direct(content)` | Return exact code-owned content, such as a policy decision, price table, or ticket ID. |
46
+ | `finish(content)` | Return exact final content and complete the conversation. |
47
+
48
+ There is no per-turn context object, post-tool transition hook, synthetic tool
49
+ result, or automatic outcome router to maintain.
50
+
51
+ ## Define durable state
52
+
53
+ Keep the node registry next to the graph. It is converted into the annotated
54
+ LangGraph state; each node channel is replaced when that node saves state.
55
+
56
+ ```ts
57
+ import { createGraphStateAnnotation, type NodeStateValue } from "@picoflow/ezgraph";
58
+ import { CityNode } from "./nodes/city.node.js";
59
+
60
+ export type WeatherGraphNodes = {
61
+ CityNode?: NodeStateValue<{ city?: string }>;
62
+ WeatherNode?: NodeStateValue<{ forecast?: string }>;
63
+ };
64
+
65
+ export const WeatherGraphState = createGraphStateAnnotation(
66
+ CityNode.name,
67
+ () => ({} as WeatherGraphNodes),
68
+ );
69
+
70
+ export type WeatherGraphStateType = typeof WeatherGraphState.State;
46
71
  ```
47
72
 
48
- The provider adapters are optional peer dependencies. The published package is
49
- ESM; TypeScript applications should use `module` and `moduleResolution` set to
50
- `NodeNext`.
73
+ ## Write a conversational node
74
+
75
+ `ConversationNode` normally needs only the graph-state type. The handler below
76
+ validates model input in code, saves the owned state channel, and uses
77
+ `direct()` for an exact result.
51
78
 
52
- ## Start an application graph
79
+ ```ts
80
+ import { z } from "zod";
81
+ import {
82
+ ConversationNode,
83
+ Tool,
84
+ direct,
85
+ stay,
86
+ type ToolDefinition,
87
+ type ToolResponse,
88
+ } from "@picoflow/ezgraph";
89
+ import type { WeatherGraphStateType } from "../weather-graph.state.js";
90
+
91
+ type CityInput = { city: string };
92
+
93
+ export class CityNode extends ConversationNode<WeatherGraphStateType> {
94
+ getPrompt(): string {
95
+ return "Collect a city, then call capture_city.";
96
+ }
97
+
98
+ defineTool(): readonly ToolDefinition<CityInput>[] {
99
+ return [{
100
+ name: "capture_city",
101
+ description: "Save a city for the forecast.",
102
+ schema: z.object({ city: z.string().min(2) }),
103
+ }];
104
+ }
105
+
106
+ @Tool("capture_city")
107
+ async captureCity({ city }: CityInput): Promise<ToolResponse> {
108
+ const value = city.trim();
109
+ if (!value) return stay("Ask for a non-empty city.");
110
+
111
+ this.saveState({ city: value });
112
+ return direct(`Saved ${value}.`);
113
+ }
114
+ }
115
+ ```
53
116
 
54
- Define your graph and nodes in application code, then register the graph with a
55
- `GraphEngine`. The engine creates or resumes a session using the supplied
56
- `sessionId`.
117
+ Use `go(TargetNode).withState({ ... })` when a transition also initializes the
118
+ target node's state. Use `withMessages()` for real model-visible messages or
119
+ attachments, and `withCleanup()` for cleanup tied to that tool result.
120
+
121
+ For deterministic policy that needs state owned by another node, read
122
+ `this.graph.graphState()`. To write another node's channel, use
123
+ `this.graph.saveNodeState(TargetNode, patch)`.
124
+
125
+ ## Build and register the graph
126
+
127
+ Register conversational nodes explicitly. Tool-returned `go()` responses choose
128
+ ordinary conversational handoffs; fixed worker edges remain ordinary LangGraph
129
+ edges. Register `TerminateSessionNode` and connect it to `END` when a graph
130
+ contains conversational nodes.
57
131
 
58
132
  ```ts
59
133
  import "reflect-metadata";
60
- import { GraphEngine } from "@picoflow/ezgraph";
61
- import { WeatherGraph } from "./weather-graph.js";
134
+ import { END } from "@langchain/langgraph";
135
+ import {
136
+ BaseGraph,
137
+ GRAPH_END_NODE,
138
+ GraphEngine,
139
+ ModelCatalog,
140
+ TerminateSessionNode,
141
+ type GraphDefinition,
142
+ type LlmGateway,
143
+ } from "@picoflow/ezgraph";
144
+ import { WeatherGraphState, type WeatherGraphStateType } from "./weather-graph.state.js";
145
+ import { CityNode } from "./nodes/city.node.js";
146
+ import { WeatherNode } from "./nodes/weather.node.js";
147
+
148
+ export class WeatherGraph extends BaseGraph<WeatherGraphStateType> {
149
+ static getGraphDefinition(): GraphDefinition {
150
+ return {
151
+ llmConfig: ModelCatalog.model("openai:gpt-5.4", { retries: 2 }),
152
+ endNode: GRAPH_END_NODE,
153
+ initialHistorySpace: "weather",
154
+ historySpaces: [
155
+ [CityNode, "weather"],
156
+ [WeatherNode, "weather"],
157
+ [TerminateSessionNode, "weather-terminal"],
158
+ ],
159
+ };
160
+ }
161
+
162
+ constructor(llmGateway: LlmGateway) {
163
+ super(llmGateway, WeatherGraph.getGraphDefinition());
164
+ }
165
+
166
+ protected buildGraph() {
167
+ const graph = this.createStateGraph(WeatherGraphState);
168
+ graph.registerTurnNodes(CityNode, WeatherNode, TerminateSessionNode);
169
+ graph.addEdge(TerminateSessionNode, END);
170
+ return graph.compile();
171
+ }
172
+ }
62
173
 
63
174
  const engine = await GraphEngine.create({ graphs: [WeatherGraph] });
64
-
65
175
  const result = await engine.run({
66
176
  graphName: "WeatherGraph",
67
- sessionId: "customer-123",
68
177
  userMessage: "I need the weather in Seattle",
69
178
  });
70
-
71
- // { status, body, session }
72
179
  ```
73
180
 
74
- `GraphEngine.create()` reads `.env` and process environment values. Model
75
- credentials stay with the provider you configure; EZGraph does not require an
76
- EZGraph account or runtime key.
77
-
78
- For a complete two-stage graph, including state, a tool handler, explicit
79
- outcomes, and graph registration, follow the
80
- [Get started tutorial](https://www.picoflow.io/ezgraph/tutorial/).
181
+ `GraphEngine.create()` loads the selected session store from environment
182
+ configuration. The result contains an HTTP-ready status/body envelope and a
183
+ session ID for the next customer turn.
81
184
 
82
- ## Persistence and configuration
185
+ ## Persistence and providers
83
186
 
84
- The default `SESSION_STORE=memory` is useful for local development. Select a
85
- durable store when conversations must resume across process restarts or
187
+ The default `SESSION_STORE=memory` is suitable for local development. Use a
188
+ durable store for sessions that must survive process restarts or run across
86
189
  instances:
87
190
 
88
191
  ```dotenv
@@ -90,33 +193,36 @@ instances:
90
193
  SESSION_STORE=sqlite
91
194
  SQLITE_DB_PATH=./data/sessions.sqlite
92
195
 
93
- # Set the credential for the model provider you use.
196
+ # Example provider credential
94
197
  OPENAI_API_KEY=...
95
198
  ```
96
199
 
97
200
  For MongoDB, configure `MONGODB_URL`, `MONGODB_NAME`, and
98
- `MONGODB_COLLECTION`. For Cosmos DB, use the Cosmos settings described in the
99
- [developer guide](https://www.picoflow.io/ezgraph/docs/developer-guide/).
201
+ `MONGODB_COLLECTION`. See the developer guide for Cosmos DB and model-provider
202
+ configuration.
203
+
204
+ ## Testing
100
205
 
101
- The [EZGraph demo application](https://github.com/picoflowio/ezgraph-demo)
102
- shows a NestJS + Fastify service with QuoteGraph, a LangGraph comparison, and a
103
- copyable [`.env.example`](https://github.com/picoflowio/ezgraph-demo/blob/main/.env.example).
206
+ Keep deterministic state, transition, and policy tests separate from live
207
+ provider evaluations. The accompanying demo uses `USE_ENV=1` as its opt-in
208
+ live-provider switch and `KEEP_SESSION=1` to retain a session for inspection.
104
209
 
105
210
  ## Learn more
106
211
 
107
- - [Get started tutorial](https://www.picoflow.io/ezgraph/tutorial/)
212
+ - [Tutorial](https://www.picoflow.io/ezgraph/tutorial/)
108
213
  - [Developer guide](https://www.picoflow.io/ezgraph/docs/developer-guide/)
109
214
  - [QuoteGraph walkthrough](https://www.picoflow.io/ezgraph/quote-graph/)
110
- - [EZGraph compared with direct LangGraph](https://www.picoflow.io/ezgraph/compare/langgraph/)
215
+ - [Comparison with direct LangGraph](https://www.picoflow.io/ezgraph/compare/langgraph/)
216
+ - [Runnable demo application](https://github.com/picoflowio/ezgraph-demo)
111
217
 
112
218
  ## License
113
219
 
114
220
  EZGraph is proprietary software distributed under the
115
221
  [EZGraph Commercial Runtime License](https://www.picoflow.io/ezgraph/license/).
116
- Personal use, commercial SaaS, internal enterprise production, client work,
117
- and closed-source applications are permitted with no EZGraph runtime fee or
118
- license key. Optional support is separate; an active support subscription
119
- includes the private source and debug package.
222
+ The license permits personal use, commercial SaaS, internal enterprise
223
+ production, client work, and closed-source applications. You may not repackage,
224
+ re-license, or redistribute EZGraph as a competing SDK, developer library,
225
+ plugin framework, or hosted service.
120
226
 
121
- See the [license page](https://www.picoflow.io/ezgraph/license/) for the
122
- applicable production-use terms.
227
+ See [LICENSE.md](LICENSE.md) and the [license page](https://www.picoflow.io/ezgraph/license/)
228
+ for the applicable terms.
@@ -1 +1 @@
1
- var d=Object.defineProperty;var a=(t,r)=>d(t,"name",{value:r,configurable:!0});import{GraphLlm as c}from"./graph-llm.config.js";import{GraphNodeRuntime as g}from"./graph-node.js";import{StateGraphExt as u}from"./state-graph-ext.js";import{assertEmptyResponseRetries as l,assertMaxAgentRounds as y,DEFAULT_CONVERSATION_POLICY as h,DEFAULT_MAX_AGENT_ROUNDS as w}from"./conversation-runner.js";import{assertLlmTimeoutMs as f}from"./llm-gateway.js";import{assertGraphSchemaVersion as m,assertStableId as M,stableClassId as n}from"./stable-id.js";class p{static{a(this,"BaseGraph")}llmGateway;static id(){return this.name}static assertName(r){return p.assertId(r)}static assertId(r){return M(r,"graph")}name;id;schemaVersion;llmConfig;requiresUserMessage;responseMode;maxAgentRounds;conversationPolicy;compiledGraph;runtime;nodeMap=new Map;endNode;migrations;constructor(r,e){this.llmGateway=r;const s=new.target;this.name=s.name,this.id=n(s,"graph"),this.schemaVersion=m(e.schemaVersion??1),this.migrations=S(e.migrations,this.schemaVersion),this.llmConfig=c.resolveConfig(e.llmConfig),this.requiresUserMessage=e.requiresUserMessage??!0,this.responseMode=e.responseMode??"chat",this.maxAgentRounds=y(e.maxAgentRounds??w),this.conversationPolicy=v(e),this.endNode=e.endNode,this.runtime=new g(e.endNode,this.llmConfig,R(e.historySpaces),e.initialHistorySpace,this.responseMode,this.maxAgentRounds,this.conversationPolicy)}get graph(){return this.compiledGraph??=this.buildGraph()}prepareInput(r,e){const s=this.runtime.historySpace(r?.currentNode);return{...r??{},histories:{...r?.histories??{},[s]:[...r?.histories[s]??[],e]}}}async restoreSessionDoc(r){if(r.graph.id!==this.id)throw new Error(`Session '${r.id}' belongs to graph '${r.graph.id}', not '${this.id}'. Start a new session to run a different graph.`);if(r.graph.schemaVersion>this.schemaVersion)throw new Error(`Session '${r.id}' uses graph '${this.id}' schema version ${r.graph.schemaVersion}, but this runtime supports version ${this.schemaVersion}.`);let e=r;for(;e.graph.schemaVersion<this.schemaVersion;){const s=e.graph.schemaVersion,i=this.migrations.get(s);if(!i)throw new Error(`Graph '${this.id}' has no migration from schema version ${s} to ${s+1}.`);const o=await i.migrate(e);if(o.graph.id!==this.id)throw new Error(`Graph '${this.id}' migration from schema version ${s} changed the persisted graph ID.`);e={...o,graph:{...o.graph,schemaVersion:s+1}}}return await this.onRestoreSessionDoc(e)}async onRestoreSessionDoc(r){return r}idleMs(r){const e=Date.parse(r.modifiedAt);return Number.isFinite(e)?Date.now()-e:0}createStateGraph(r){return new u(r,(e=>this.createNode(e)),this.endNode)}createNode(r){const e=new r(this.llmGateway,this.runtime),s=n(r,"graph node");if(e.id!==s)throw new Error(`Graph node factory for '${s}' constructs '${e.id}'.`);if(this.nodeMap.has(e.id))throw new Error(`Graph node '${e.id}' is already registered.`);return this.nodeMap.set(e.id,e),this.runtime.registerTools(e.id,e.defineTool()),Object.freeze(e),e}}function v(t){const r=t.emptyResponseRecovery===void 0?h.emptyResponseRecovery:t.emptyResponseRecovery;return r&&l(r.retries),{...t.llmTimeoutMs===void 0?{}:{llmTimeoutMs:f(t.llmTimeoutMs)},emptyHistorySeed:t.emptyHistorySeed===void 0?h.emptyHistorySeed:t.emptyHistorySeed,emptyResponseRecovery:r}}a(v,"resolveConversationPolicy");function R(t){return Object.fromEntries((t??[]).map(([r,e])=>[n(r,"graph node"),e]))}a(R,"historySpaceMap");function S(t,r){const e=new Map;let s;for(const i of t??[]){const o=m(i.from);if(o>=r)throw new Error(`A graph migration from version ${o} cannot target schema version ${r}.`);if(e.has(o))throw new Error(`More than one graph migration starts at version ${o}.`);if(s!==void 0&&o!==s+1)throw new Error(`Graph migrations must be ordered and contiguous; version ${s} must be followed by ${s+1}.`);e.set(o,i),s=o}return e}a(S,"migrationMap");export{p as BaseGraph};
1
+ var d=Object.defineProperty;var a=(t,r)=>d(t,"name",{value:r,configurable:!0});import{GraphLlm as c}from"./graph-llm.config.js";import{GraphNodeRuntime as g}from"./graph-node.js";import{StateGraphExt as u}from"./state-graph-ext.js";import{assertEmptyResponseRetries as l,assertMaxAgentRounds as y,DEFAULT_CONVERSATION_POLICY as h,DEFAULT_MAX_AGENT_ROUNDS as w}from"./conversation-runner.js";import{assertLlmTimeoutMs as f}from"./llm-gateway.js";import{assertGraphSchemaVersion as m,assertStableId as v,stableClassId as n}from"./stable-id.js";class p{static{a(this,"BaseGraph")}llmGateway;static id(){return this.name}static assertName(r){return p.assertId(r)}static assertId(r){return v(r,"graph")}name;id;schemaVersion;llmConfig;requiresUserMessage;responseMode;maxAgentRounds;conversationPolicy;compiledGraph;runtime;nodeMap=new Map;endNode;migrations;constructor(r,e){this.llmGateway=r;const s=new.target;this.name=s.name,this.id=n(s,"graph"),this.schemaVersion=m(e.schemaVersion??1),this.migrations=R(e.migrations,this.schemaVersion),this.llmConfig=c.resolveConfig(e.llmConfig),this.requiresUserMessage=e.requiresUserMessage??!0,this.responseMode=e.responseMode??"chat",this.maxAgentRounds=y(e.maxAgentRounds??w),this.conversationPolicy=M(e),this.endNode=e.endNode,this.runtime=new g(e.endNode,this.llmConfig,S(e.historySpaces),e.initialHistorySpace,this.responseMode,this.maxAgentRounds,this.conversationPolicy)}get graph(){return this.compiledGraph??=this.buildGraph()}prepareInput(r,e){const s=this.runtime.historySpace(r?.currentNode);return{...r??{},histories:{...r?.histories??{},[s]:[...r?.histories[s]??[],e]}}}saveNodeState(r,e){this.runtime.saveNode(n(r,"graph node"),e)}async restoreSessionDoc(r){if(r.graph.id!==this.id)throw new Error(`Session '${r.id}' belongs to graph '${r.graph.id}', not '${this.id}'. Start a new session to run a different graph.`);if(r.graph.schemaVersion>this.schemaVersion)throw new Error(`Session '${r.id}' uses graph '${this.id}' schema version ${r.graph.schemaVersion}, but this runtime supports version ${this.schemaVersion}.`);let e=r;for(;e.graph.schemaVersion<this.schemaVersion;){const s=e.graph.schemaVersion,i=this.migrations.get(s);if(!i)throw new Error(`Graph '${this.id}' has no migration from schema version ${s} to ${s+1}.`);const o=await i.migrate(e);if(o.graph.id!==this.id)throw new Error(`Graph '${this.id}' migration from schema version ${s} changed the persisted graph ID.`);e={...o,graph:{...o.graph,schemaVersion:s+1}}}return await this.onRestoreSessionDoc(e)}async onRestoreSessionDoc(r){return r}idleMs(r){const e=Date.parse(r.modifiedAt);return Number.isFinite(e)?Date.now()-e:0}createStateGraph(r){return new u(r,(e=>this.createNode(e)),this.endNode)}createNode(r){const e=new r(this.llmGateway,this.runtime),s=n(r,"graph node");if(e.id!==s)throw new Error(`Graph node factory for '${s}' constructs '${e.id}'.`);if(this.nodeMap.has(e.id))throw new Error(`Graph node '${e.id}' is already registered.`);return this.nodeMap.set(e.id,e),this.runtime.registerTools(e.id,e.defineTool()),Object.freeze(e),e}}function M(t){const r=t.emptyResponseRecovery===void 0?h.emptyResponseRecovery:t.emptyResponseRecovery;return r&&l(r.retries),{...t.llmTimeoutMs===void 0?{}:{llmTimeoutMs:f(t.llmTimeoutMs)},emptyHistorySeed:t.emptyHistorySeed===void 0?h.emptyHistorySeed:t.emptyHistorySeed,emptyResponseRecovery:r}}a(M,"resolveConversationPolicy");function S(t){return Object.fromEntries((t??[]).map(([r,e])=>[n(r,"graph node"),e]))}a(S,"historySpaceMap");function R(t,r){const e=new Map;let s;for(const i of t??[]){const o=m(i.from);if(o>=r)throw new Error(`A graph migration from version ${o} cannot target schema version ${r}.`);if(e.has(o))throw new Error(`More than one graph migration starts at version ${o}.`);if(s!==void 0&&o!==s+1)throw new Error(`Graph migrations must be ordered and contiguous; version ${s} must be followed by ${s+1}.`);e.set(o,i),s=o}return e}a(R,"migrationMap");export{p as BaseGraph};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var c=(n,e)=>f(n,"name",{value:e,configurable:!0});var p=function(n,e,t,r){var o=arguments.length,s=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(i=n[a])&&(s=(o<3?i(s):o>3?i(e,t,s):i(e,t))||s);return o>3&&s&&Object.defineProperty(e,t,s),s},u=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};import{GraphNode as l,Tool as h}from"./graph-node.js";import{TerminateSessionNode as d}from"./terminate-session.node.js";class m extends l{static{c(this,"ConversationNode")}quitRequests=new WeakSet;supportsAutomaticOutcomeRouting=!0;async endChat(e,t){return this.quitRequests.add(t),{output:{message:e.message?.trim()||"Of course. This conversation is now complete."},stopAfterBatch:!0}}quit(e){return this.transition(d,e,!1)}async run(e){const t=this.createContext(e),r=await this.runConversation(e,t);return this.nextStep(e,t,r)}async runConversation(e,t){this.quitRequests.delete(t);try{return{...await super.runConversation(e,t),quitRequested:this.quitRequests.has(t)}}finally{this.quitRequests.delete(t)}}}p([h("terminate_session"),u("design:type",Function),u("design:paramtypes",[Object,Object]),u("design:returntype",Promise)],m.prototype,"endChat",null);export{m as ConversationNode};
1
+ var c=Object.defineProperty;var d=(n,t)=>c(n,"name",{value:t,configurable:!0});var u=function(n,t,e,o){var s=arguments.length,r=s<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var p=n.length-1;p>=0;p--)(i=n[p])&&(r=(s<3?i(r):s>3?i(t,e,r):i(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r},h=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)};import{HumanMessage as g}from"@langchain/core/messages";import{Command as a,END as f}from"@langchain/langgraph";import{GraphNode as l,Tool as w}from"./graph-node.js";import{stableClassId as y}from"./stable-id.js";import{TerminateSessionNode as C}from"./terminate-session.node.js";import{go as v}from"./tool-response.js";class R extends l{static{d(this,"ConversationNode")}async endChat(t){return v(C).withMessage(new g(t.message?.trim()||"The user asked to end the conversation."))}async run(t){const e=await this.runConversation(t,{});if(e.toolResponse)return this.resolveToolResponse(e,e.toolResponse);const o=e.response;if(!o?.trim())throw new Error(`Conversation node '${this.id}' stopped without a response or tool transition.`);return new a({update:{currentNode:this.id,response:o,inputConsumed:!0,completed:!1,...this.historyUpdate(e.messages),tokens:e.usage},goto:f})}resolveToolResponse(t,e){const o=this.historyUpdate(t.messages);if(e.kind==="go"){if(!e.target)throw new Error(`Conversation node '${this.id}' selected go() without a target.`);const s=y(e.target,"graph node");return e.state&&this.graph.saveNodeState(e.target,e.state),e.message&&this.graph.appendHistory(this.graph.historySpace(s),[e.message]),new a({update:{currentNode:s,inputConsumed:!0,response:"",completed:!1,...o,tokens:t.usage},goto:s})}if(e.kind==="direct")return new a({update:{currentNode:this.id,response:m(this.id,e),inputConsumed:!0,completed:!1,...o,tokens:t.usage},goto:f});if(e.kind==="finish")return new a({update:{...this.graph.complete(m(this.id,e)),...o,tokens:t.usage},goto:f});throw new Error(`Conversation node '${this.id}' returned stay() after the agent loop stopped.`)}}u([w("terminate_session"),h("design:type",Function),h("design:paramtypes",[Object]),h("design:returntype",Promise)],R.prototype,"endChat",null);function m(n,t){if(!t.response?.trim())throw new Error(`Conversation node '${n}' selected ${t.kind}() without a response.`);return t.response}d(m,"requireResponse");export{R as ConversationNode};
@@ -1 +1 @@
1
- const UB=K;(function(E,a){const UG={E:0x1d6,a:0x1cb,q:0x1b3,R:0x1ad,z:0x1b9,F:0x1bc},UA=K,q=E();while(!![]){try{const R=parseInt(UA(UG.E))/0x1*(-parseInt(UA(0x1c1))/0x2)+-parseInt(UA(UG.a))/0x3+-parseInt(UA(0x1c3))/0x4*(parseInt(UA(UG.q))/0x5)+-parseInt(UA(0x1b7))/0x6+-parseInt(UA(UG.R))/0x7+-parseInt(UA(0x1c6))/0x8*(-parseInt(UA(UG.z))/0x9)+parseInt(UA(UG.F))/0xa*(parseInt(UA(0x1b0))/0xb);if(R===a)break;else q['push'](q['shift']());}catch(z){q['push'](q['shift']());}}}(c,0x3a36d));var v=Object[UB(0x1c5)],p=(E,a)=>v(E,UB(0x1d1),{'value':a,'configurable':!0x0});import{HumanMessage as h,ToolMessage as g}from'@langchain/core/messages';import{addTokenUsage as f,emptyTokenUsage as u}from'./token-usage.js';import{describeStopReason as G,isRetryableStopReason as V,modelStopReason as e}from'./model-stop-reason.js';import{SessionLogWarning as d}from'./session-log.js';class k extends Error{static{p(this,UB(0x1bb));}[UB(0x1d7)];constructor(E){const UK=UB;super(UK(0x1b5)+G(E)+').'),this['reason']=E,this['name']=UK(0x1bb);}}const P=0x8;function K(U,M){U=U-0x1ac;const T=c();let C=T[U];if(K['VHduzc']===undefined){var D=function(g){const f='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let x='',u='';for(let v=0x0,G,V,e=0x0;V=g['charAt'](e++);~V&&(G=v%0x4?G*0x40+V:V,v++%0x4)?x+=String['fromCharCode'](0xff&G>>(-0x2*v&0x6)):0x0){V=f['indexOf'](V);}for(let O=0x0,d=x['length'];O<d;O++){u+='%'+('00'+x['charCodeAt'](O)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(u);};K['EoGUqK']=D,K['HnwWdm']={},K['VHduzc']=!![];}const A=T[0x0],B=U+A,h=K['HnwWdm'][B];return!h?(C=K['EoGUqK'](C),K['HnwWdm'][B]=C):C=h,C;}function D(E){const Uh=UB;if(!Number[Uh(0x1ba)](E)||E<0x1)throw new Error(Uh(0x1be)+String(E)+'.');return E;}p(D,UB(0x1c9));const T='Start',A={'retries':0x2,'nudge':UB(0x1db)};function L(E){const Ug=UB;if(!Number[Ug(0x1ba)](E)||E<0x0)throw new Error(Ug(0x1d8)+String(E)+'.');return E;}p(L,UB(0x1bd));const B={'emptyHistorySeed':T,'emptyResponseRecovery':A};function c(){const Ua=['BgXTq29UzMLN','zw1WDhLszxnWB25ZzvjLy292zxj5','DMfSDwu','zw50CMLLCW','mZzwsgTIBxq','CMvHC29U','zw1WDhLszxnWB25ZzvjLy292zxj5lNjLDhjPzxmGBxvZDcbIzsbHig5VBI1UzwDHDgL2zsbPBNrLz2vYoYbYzwnLAxzLzca','q29UDMvYC2f0Aw9Uigv4y2vLzgvKia','CNvU','rM9SBg93ihrOzsbZExn0zw0GChjVBxb0igfUzcbYzxnWB25KihbYB3bLCMX5lIbvC2uGDgHLihjLCxvPCMvKihrVB2WGD2HLBIbPBNn0CNvJDgvKlG','BgvUz3rO','CMv0CMLLCW','y2XLyw51Ca','Cg9W','zxHLy3v0zvrVB2W','mtK3ndy1mvjHBKXKEq','C3rYAw5NAwz5','AgLZDg9YEq','mJGXmJi2z0HiDNbM','BwvZC2fNzvrLEhq','B3v0Chv0','mZbXshflzhm','zw1WDhLiAxn0B3j5u2vLza','vgHLig1VzgvSihjLDhvYBMvKigfUigvTChr5ihjLC3bVBNnLicG','y29UDgvUDa','mtK0ntiYnfbsyxLXDG','DxnHz2u','nJq0ndLiAhPKtwm','AxnjBNrLz2vY','rw1WDhLnB2rLBfjLC3bVBNnLrxjYB3i','nJCWr1rvAwfQ','yxnZzxj0rw1WDhLszxnWB25ZzvjLDhjPzxm','Bwf4qwDLBNrsB3vUzhmGBxvZDcbIzsbHihbVC2L0AxzLigLUDgvNzxi7ihjLy2vPDMvKia','BgXTr2f0zxDHEq','igfNzw50ihjVDw5KCY4','mJq0odHxr1jSvuK','BwfW','mJKZodiWuKfOwxfx','BwvZC2fNzxm','zgvMAw5LuhjVCgvYDhK','mZKYAfDhBLbP','ChvZAa','y2fSBe9WDgLVBNm','yxnZzxj0twf4qwDLBNrsB3vUzhm','BNvKz2u','mtaXmJy2nwH3tvf2vG','q29UDMvYC2f0Aw9UuNvUBMvY','y2XLyw51Cef0DgfJAg1LBNrZ','C3rVCefMDgvYqMf0y2G','Bwf4qwDLBNrsB3vUzhm','Dg9VBhm','BMfTzq'];c=function(){return Ua;};return c();}class J{static{p(this,UB(0x1cc));}[UB(0x1bf)];constructor(E){const Uf=UB;this[Uf(0x1bf)]=E;}async[UB(0x1da)](q){const UE={E:0x1b4,a:0x1af,q:0x1cf,R:0x1d3,z:0x1d2,F:0x1c2,Q:0x1c7,W:0x1d4,H:0x1dc,i:0x1df,Z:0x1ca,w:0x1d5,j:0x1b2,n:0x1c7,t:0x1cd},Ux=UB,z=q[Ux(0x1b4)]===void 0x0?T:q[Ux(UE.E)],F=q[Ux(UE.a)][Ux(0x1dc)]===0x0&&z!==null,Q=F?[new h(z)]:[...q[Ux(UE.a)]],W=F?[...Q]:[];let H=[],Z=u();const j=D(q[Ux(UE.q)]??P),t=q[Ux(UE.R)]===void 0x0?A:q['emptyResponseRecovery'],Y=t?L(t[Ux(0x1dd)]):0x0;let X=0x0;for(let U0=0x0;U0<j;U0+=0x1){let U1;try{U1=await this['llmGateway']['agent'](q['systemPrompt'],Q,q[Ux(0x1d0)],q[Ux(UE.z)],q[Ux(0x1c8)]);}catch(U4){const U5=H;throw H=[],await Promise['allSettled'](U5[Ux(UE.F)](U6=>U6())),U4;}Z=f(Z,U1[Ux(0x1b8)]),W[Ux(UE.Q)](U1[Ux(0x1d4)]),Q['push'](U1[Ux(UE.W)]);const U2=U1[Ux(0x1d4)]['tool_calls']??[];if(U2[Ux(UE.H)]===0x0){const U6=$(U1[Ux(0x1d4)]);if(U6['trim']())return await I(),{'messages':W,'usage':Z,'response':U6,'stoppedAfterTool':!0x1};const U7=e(U1[Ux(0x1d4)]),U8=V(U7)&&t!==null&&X<Y;if(d({'empty_model_response':G(U7),'retried':U8}),U8&&t){X+=0x1,W[Ux(0x1df)](),Q[Ux(UE.i)](),Q['push'](new h(t[Ux(UE.Z)]));continue;}return await I(),{'messages':W,'usage':Z,'response':U6,'stoppedAfterTool':!0x1,'stopReason':U7};}await I();let U3=!0x1;try{for(const [U9,UU]of U2[Ux(UE.w)]()){const UM=await q[Ux(0x1ac)](UU),UT=new g({'content':JSON['stringify'](UM[Ux(UE.j)]),'tool_call_id':UU['id']??'tool-call-'+U0+'-'+U9,'name':UU[Ux(0x1d1)]});W[Ux(0x1c7)](UT),Q[Ux(0x1c7)](UT),UM[Ux(0x1c4)]&&(W[Ux(UE.n)](...UM['messages']),Q[Ux(UE.n)](...UM['messages'])),UM['cleanup']&&H[Ux(UE.Q)](UM[Ux(0x1de)]),U3||=UM[Ux(0x1ce)]===!0x0;}}catch(UC){throw await I(),UC;}if(U3)return await I(),{'messages':W,'usage':Z,'stoppedAfterTool':!0x0};}throw await I(),new Error(Ux(0x1d9)+j+Ux(0x1c0));async function I(){const Uu=Ux,UD=H;H=[],await Promise['allSettled'](UD[Uu(0x1c2)](Uc=>Uc()));}p(I,Ux(UE.t));}}function $(E){const Uk={E:0x1b6,a:0x1ae},Uv=UB;return typeof E[Uv(Uk.E)]=='string'?E['content']:JSON[Uv(Uk.a)](E[Uv(0x1b6)]);}p($,UB(0x1b1));export{J as ConversationRunner,B as DEFAULT_CONVERSATION_POLICY,T as DEFAULT_EMPTY_HISTORY_SEED,A as DEFAULT_EMPTY_RESPONSE_RECOVERY,P as DEFAULT_MAX_AGENT_ROUNDS,k as EmptyModelResponseError,L as assertEmptyResponseRetries,D as assertMaxAgentRounds};
1
+ const hJ=m;(function(r,A){const hp={r:0x1b2,A:0x1b5,c:0x1c8,a:0x1ad,V:0x1a6,t:0x1cb},he=m,c=r();while(!![]){try{const a=parseInt(he(hp.r))/0x1*(parseInt(he(0x1a2))/0x2)+parseInt(he(hp.A))/0x3*(-parseInt(he(hp.c))/0x4)+-parseInt(he(hp.a))/0x5*(-parseInt(he(hp.V))/0x6)+-parseInt(he(0x1c9))/0x7+parseInt(he(0x1cf))/0x8*(parseInt(he(0x1c0))/0x9)+parseInt(he(0x1b8))/0xa+parseInt(he(0x1be))/0xb*(parseInt(he(hp.t))/0xc);if(a===A)break;else c['push'](c['shift']());}catch(V){c['push'](c['shift']());}}}(h,0x8cecd));var v=Object[hJ(0x1b4)],p=(r,A)=>v(r,hJ(0x1b0),{'value':A,'configurable':!0x0});import{AIMessage as Z,HumanMessage as d,ToolMessage as B}from'@langchain/core/messages';import{addTokenUsage as E,emptyTokenUsage as f}from'./token-usage.js';import{isToolResponse as Q}from'./tool-response.js';import{describeStopReason as n,isRetryableStopReason as w,modelStopReason as e}from'./model-stop-reason.js';import{SessionLogWarning as J}from'./session-log.js';import{isOpenAIAuthConfig as u,openAIAuthMessageText as W}from'./openai-auth-provider.js';class X extends Error{static{p(this,'EmptyModelResponseError');}[hJ(0x1ba)];constructor(r){const hu=hJ;super(hu(0x1bc)+n(r)+').'),this['reason']=r,this[hu(0x1b0)]=hu(0x1c7);}}function h(){const hL=['BMfTzq','CMv0CMLLCW','mZqWotm3sNLJtvPr','AxnjBNrLz2vY','zgvMAw5LuhjVCgvYDhK','mJiZodnSsw9KrKO','Dg9VBc1JywXSlq','yxnZzxj0twf4qwDLBNrsB3vUzhm','mZm4ndK5mhHHDhb3wG','u3rHCNq','CMvHC29U','C3LZDgvTuhjVBxb0','vgHLig1VzgvSihjLDhvYBMvKigfUigvTChr5ihjLC3bVBNnLicG','AgLZDg9YEq','mJm2mZLYtKDxvMy','zw1WDhLiAxn0B3j5u2vLza','mtHowvrOAgS','CMvZCg9UC2u','DMfSDwu','zw1WDhLszxnWB25ZzvjLy292zxj5','C3rYAw5NAwz5','y2fSBe9WDgLVBNm','BgXTr2f0zxDHEq','rw1WDhLnB2rLBfjLC3bVBNnLrxjYB3i','mJeYDhbiA2Xi','nZq2ndKWnuPcC0XLyW','ChvZAa','mJy2ngfLAfnoDW','Bwf4qwDLBNrsB3vUzhmGBxvZDcbIzsbHihbVC2L0AxzLigLUDgvNzxi7ihjLy2vPDMvKia','ywDLBNq','BNvKz2u','ntGXntjUwNn0vvy','CNvU','DhjPBq','y29UDgvUDa','ywXSu2v0DgXLza','igfNzw50ihjVDw5KCY4','C3rHEq','Cg9W','BwfW','BgXTq29UzMLN','q29UDMvYC2f0Aw9Uigv4y2vLzgvKia','mNPcCKLzrq','zw1WDhLszxnWB25ZzvjLy292zxj5lNjLDhjPzxmGBxvZDcbIzsbHig5VBI1UzwDHDgL2zsbPBNrLz2vYoYbYzwnLAxzLzca','zxHLy3v0zvrVB2W','zw50CMLLCW','ntiWode1mgjwtgDpAW','y2XLyw51Ca','BgvUz3rO','qsb0B29SigjHDgnOihnLBgvJDgvKig1VCMuGDgHHBIbVBMuGDgvYBwLUywWGCMvZCg9UC2uGB3iGDhjHBNnPDgLVBI4','zMvLzgjHy2S','DxnHz2u','Dg9VBhm','nvHMEvzTra','A2LUza','rM9SBg93ihrOzsbZExn0zw0GChjVBxb0igfUzcbYzxnWB25KihbYB3bLCMX5lIbvC2uGDgHLihjLCxvPCMvKihrVB2WGD2HLBIbPBNn0CNvJDgvKlG'];h=function(){return hL;};return h();}function m(T,N){T=T-0x19d;const U=h();let Z=U[T];if(m['FARvlc']===undefined){var d=function(C){const Q='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let n='',w='';for(let Y=0x0,x,e,J=0x0;e=C['charAt'](J++);~e&&(x=Y%0x4?x*0x40+e:e,Y++%0x4)?n+=String['fromCharCode'](0xff&x>>(-0x2*Y&0x6)):0x0){e=Q['indexOf'](e);}for(let u=0x0,D=n['length'];u<D;u++){w+='%'+('00'+n['charCodeAt'](u)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(w);};m['vWmfno']=d,m['XkoHyf']={},m['FARvlc']=!![];}const B=U[0x0],E=T+B,f=m['XkoHyf'][E];return!f?(Z=m['vWmfno'](Z),m['XkoHyf'][E]=Z):Z=f,Z;}const $=0x8;function F(r){const hA={r:0x1cc},hD=hJ;if(!Number[hD(0x1b3)](r)||r<0x1)throw new Error(hD(hA.r)+String(r)+'.');return r;}p(F,hJ(0x1b7));const S=hJ(0x1b9),_={'retries':0x2,'nudge':hJ(0x1af)};function H(r){const hc={r:0x1b3},hW=hJ;if(!Number[hW(hc.r)](r)||r<0x0)throw new Error(hW(0x1a3)+String(r)+'.');return r;}p(H,'assertEmptyResponseRetries');const j={'emptyHistorySeed':S,'emptyResponseRecovery':_};class z{static{p(this,'ConversationRunner');}['llmGateway'];constructor(r){const ha={r:0x1c6},hk=hJ;this[hk(ha.r)]=r;}async[hJ(0x1d0)](V){const hS={r:0x1bd,A:0x1c3,c:0x1b1,a:0x1ac,V:0x1c5,t:0x1d3,g:0x19f,o:0x1a0,q:0x1c2,l:0x1d2,G:0x19e,i:0x1ce,y:0x1a4,R:0x1ae,K:0x19d,s:0x1aa,M:0x1ca,h0:0x1a7,h1:0x1ae,h2:0x1c1},hV={r:0x1d3},hz=hJ,t=V[hz(0x1bf)]===void 0x0?S:V[hz(0x1bf)],q=V[hz(hS.r)][hz(0x1a8)]===0x0&&t!==null,G=q?[new d(t)]:[...V[hz(0x1bd)]],K=q?[...G]:[];let h0=[],h1=f();const h2=F(V['maxAgentRounds']??$),h3=V[hz(hS.A)]===void 0x0?_:V['emptyResponseRecovery'],h4=h3?H(h3[hz(hS.c)]):0x0;let h5=0x0;for(let h7=0x0;h7<h2;h7+=0x1){let h8;try{h8=await this[hz(0x1c6)][hz(0x1cd)](V[hz(0x1bb)],G,V[hz(hS.a)],V['llmConfig'],V[hz(hS.V)]);}catch(hT){const hN=h0;throw h0=[],await Promise[hz(hS.t)](hN[hz(hS.g)](hU=>hU())),hT;}h1=E(h1,h8[hz(0x1ab)]),K[hz(0x1ca)](h8[hz(0x1c2)]),G['push'](h8['value']);const h9=h8['value']['tool_calls']??[];if(h9['length']===0x0){const hU=u(V[hz(hS.o)])?W(h8[hz(hS.q)][hz(hS.l)]):Y(h8[hz(hS.q)]);if(hU[hz(0x1d1)]())return await h6(),{'messages':K,'usage':h1,'response':hU,'stoppedAfterTool':!0x1};const hZ=e(h8['value']),hd=w(hZ)&&h3!==null&&h5<h4;if(J({'empty_model_response':n(hZ),'retried':hd}),hd&&h3){h5+=0x1,K[hz(hS.G)](),G[hz(0x19e)](),G[hz(0x1ca)](new d(h3[hz(hS.i)]));continue;}return await h6(),{'messages':K,'usage':h1,'response':hU,'stoppedAfterTool':!0x1,'stopReason':hZ};}await h6();let hh=!0x1,hm;try{for(const [hB,hE]of h9[hz(0x1a5)]()){const hf=await V[hz(hS.y)](hE);if(Q(hf)){if(hf[hz(hS.R)]!=='stay'){if(hm&&hm[hz(0x1ae)]!==hz(hS.K))throw new Error(hz(0x1a9));hm=hf;}else hm||(hm=hf);const hC=new B({'content':hf[hz(hS.s)]??'OK','tool_call_id':hE['id']??hz(0x1b6)+h7+'-'+hB,'name':hE[hz(0x1b0)]});K[hz(hS.M)](hC),G[hz(0x1ca)](hC),hf['messages']&&(K[hz(0x1ca)](...hf['messages']),G[hz(0x1ca)](...hf['messages'])),hf['cleanup']&&h0[hz(0x1ca)](hf[hz(hS.h0)]),hh||=hf[hz(hS.h1)]!==hz(hS.K);continue;}}}catch(hQ){throw await h6(),hQ;}if(hh){const hn=hm?.[hz(hS.h2)];if(hn){const hw=new Z(hn);K[hz(hS.M)](hw),G[hz(0x1ca)](hw);}return await h6(),{'messages':K,'usage':h1,'stoppedAfterTool':!0x0,...hn?{'response':hn}:{},...hm?{'toolResponse':hm}:{}};}}throw await h6(),new Error(hz(0x1a1)+h2+hz(0x1d4));async function h6(){const hr=hz,hY=h0;h0=[],await Promise[hr(hV.r)](hY['map'](hx=>hx()));}p(h6,'cleanupAttachments');}}function Y(r){const hj={r:0x1d2,A:0x1c4},hb=hJ;return typeof r['content']=='string'?r[hb(hj.r)]:JSON[hb(hj.A)](r['content']);}p(Y,'messageText');export{z as ConversationRunner,j as DEFAULT_CONVERSATION_POLICY,S as DEFAULT_EMPTY_HISTORY_SEED,_ as DEFAULT_EMPTY_RESPONSE_RECOVERY,$ as DEFAULT_MAX_AGENT_ROUNDS,X as EmptyModelResponseError,H as assertEmptyResponseRetries,F as assertMaxAgentRounds};
@@ -1 +1 @@
1
- const UT=c;(function(p,Q){const Uv={p:0xc3,Q:0xc6,W:0xaf,H:0xc1,i:0xdf},UM=c,W=p();while(!![]){try{const H=parseInt(UM(0xae))/0x1+-parseInt(UM(0xcb))/0x2+-parseInt(UM(Uv.p))/0x3+-parseInt(UM(Uv.Q))/0x4*(parseInt(UM(0xa2))/0x5)+-parseInt(UM(0xa8))/0x6+parseInt(UM(Uv.W))/0x7*(-parseInt(UM(Uv.H))/0x8)+-parseInt(UM(0xac))/0x9*(-parseInt(UM(Uv.i))/0xa);if(H===Q)break;else W['push'](W['shift']());}catch(i){W['push'](W['shift']());}}}(U,0xf2844));var E=Object[UT(0xc2)],S=(p,Q)=>E(p,'name',{'value':Q,'configurable':!0x0});import{HumanMessage as A}from'@langchain/core/messages';import{randomUUID as B}from'node:crypto';import{GraphRegistry as K,registeredGraphId as h,registeredGraphSchemaVersion as g}from'./graph-registry.js';import{LangChainLlmGateway as f}from'./langchain-llm-gateway.js';import{SessionLogError as u,createSessionLogs as v,withSessionLogs as e}from'./session-log.js';import{withTurnContext as d}from'./turn-context.js';import{SessionManager as P,SessionTurnError as k,SESSION_BUSY as a,SESSION_COMPLETED as q}from'./persistence/session-manager.js';import{parseJsonObjectResponse as z}from'./json-response.js';function U(){const UF=['y29UzMLN','jYbPCYbHBhjLywr5ihbYB2nLC3nPBMCGysb0DxjUlG','CMvSzwfZzvr1CM4','z2v0r3jHCgHZ','ANnVBLjLC3vSDa','nw11DKf1tG','y29Kzq','D2L0Afr1CM5ty29Wzq','C2vZC2LVBNm','CMvXDwLYzxnvC2vYtwvZC2fNzq','BwvZC2fNzq','ndm3ntCYofzVD1f3vW','ChjLCgfYzuLUChv0','CMvZCg9UC2u','BMfTzxm','mti3otm2oeX2vKDczq','z3jHCgHZ','mZu2nZLVr01ys0y','mtrWy2vUAfm','Aw5MBgLNAhrtzxnZAw9UCW','vw5HyMXLihrVihbLCNnPC3qGC2vZC2LVBIbLCNjVCIbSB2C6','CMvZCg9UC2vnB2rL','r3jHCgHfBMDPBMu','oYbLEhbLy3rLzca','BwfW','ANnVBG','y29TCgXLDgvK','CMvNAxn0zxjhCMfWAa','yMvNAw5uDxjU','y29UzMXPy3rszxn1Bhq','ywrK','C2LNBMfS','zgvSzxrLu2vZC2LVBG','ChjVDMLKzxjZ','AgfZ','jYbYzxn0B3jLihjLDhvYBMvKihnJAgvTysb2zxjZAw9Uia','nJy3nJmYofLive1rvq','zgvMAw5LuhjVCgvYDhK','mJe1mZa4nxPurxPQzW','BgXTr2f0zxDHEuzHy3rVCNK','y3jLyxrL','nJm4oty2ogXJD0jKuq','y2HHDfjLC3vSDa','zw5KrMfPBgvKvhvYBG','y29UzMLNtwfUywDLCG','BgXTq29UzMLN','mZCYntGXme1UC25pAa','z3jHCgHoyw1L','DMfSAwrHDgvtzxnZAw9Uswq','y29TCgXLDgvKu2vZC2LVBLjLC3vSDa','z3jHCgG','CMvNAxn0CNK','CMvNAxn0zxi','CMvZDg9YzvnLC3nPB25eB2m','r3jHCgGGjW','z2v0u2vZC2LVBG','y2XVC2u','zg9JDw1LBNq','zxjYB3i','DhjPBq','C2f2zvn0yxrL','CNvU','jYbPCYbUB3qGCMvNAxn0zxjLzc4','C3rYAw5N','BM9Kzxm','C2nOzw1HvMvYC2LVBG','ntmWs0Diq1vn','Aw52B2TL','C2vZC2LVBK1HBMfNzxi','CMvZDg9YzvnLC3nPB25eB2n1BwvUDa','u2vZC2LVBIaN','z2v0r3jHCgHezwzPBML0Aw9U','zgvSzxrL','CgvYC2LZDe1Pz3jHDgvKu2vZC2LVBG','DxnLCK1LC3nHz2u','DxnLCK1LC3nHz2uGBxvZDcbIzsbHig5VBI1LBxb0EsbZDhjPBMCU','C2vZC2LVBKLK'];U=function(){return UF;};return U();}function c(M,T){M=M-0x95;const C=U();let D=C[M];if(c['bNAqUg']===undefined){var A=function(g){const f='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let x='',u='';for(let v=0x0,G,V,e=0x0;V=g['charAt'](e++);~V&&(G=v%0x4?G*0x40+V:V,v++%0x4)?x+=String['fromCharCode'](0xff&G>>(-0x2*v&0x6)):0x0){V=f['indexOf'](V);}for(let O=0x0,d=x['length'];O<d;O++){u+='%'+('00'+x['charCodeAt'](O)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(u);};c['DQckiz']=A,c['gfuxCv']={},c['bNAqUg']=!![];}const B=C[0x0],K=M+B,h=c['gfuxCv'][K];return!h?(D=c['DQckiz'](D),c['gfuxCv'][K]=D):D=h,D;}class R{static{S(this,UT(0xb3));}[UT(0xd0)]=new K();['sessions'];[UT(0xc4)];[UT(0xb0)]=new Set();constructor(p={}){const UG={p:0xe1,Q:0xb8},UC=UT;this['sessions']=p[UC(UG.p)]??new P(),this[UC(0xc4)]=p['llmGatewayFactory']??(Q=>new f(Q,p['providers']?{'providers':p[UC(0xbe)]}:{})),this[UC(UG.Q)](p[UC(0xad)]??[]);}static async[UT(0xc5)](p={}){const UV={p:0xc4,Q:0xad},UD=UT,Q=await P['fromConfig'](p[UD(0xc9)]);return new R({'sessionManager':Q,...p[UD(0xc4)]?{'llmGatewayFactory':p[UD(UV.p)]}:{},...p[UD(UV.Q)]?{'graphs':p[UD(UV.Q)]}:{},...p['providers']?{'providers':p['providers']}:{}});}[UT(0xb8)](p){const Ue={p:0xd0,Q:0xd1},Uc=UT,Q=p[Uc(0xb5)](W=>new W(this[Uc(0xc4)](W[Uc(0x97)]()[Uc(0xca)])));return this[Uc(Ue.p)][Uc(Ue.Q)](Q),this;}[UT(0xa0)](){const UA=UT;return this[UA(0xd0)][UA(0xab)]();}['getSession'](p){const Ud={p:0xd4},UB=UT;return this[UB(0xa5)][UB(Ud.p)](w(p));}async[UT(0xda)](Q){const UE={p:0xd3,Q:0x9b,W:0x9c,H:0xb0,i:0xbf,Z:0xba,J:0x96,n:0x9e,t:0xbc},UP={p:0xdd,Q:0xcf,W:0xde,H:0xcf,i:0xc0,Z:0xde,J:0xde,n:0xa5,t:0xb7,m:0xb2,s:0xcf,o:0xa5,Y:0xba,l:0xa3,y:0xa7,X:0xc8,r:0xd7,U0:0xb0},UK=UT,W=this['registry']['get'](Q['graphName']);if(!W)return{'status':0x190,'body':{'success':!0x1,'completed':!0x0,'message':UK(UE.p)+(Q[UK(0xcc)]??'')+UK(0xdb)}};const H=typeof Q[UK(0x9a)]==UK(0xdc)?Q[UK(0x9a)][UK(0xd8)]():void 0x0;if(W[UK(0xa6)]!==!0x1&&!H)return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':UK(UE.Q)}};let Z;try{Z=Q[UK(UE.W)]?w(Q['sessionId']):B();}catch(y){return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':y instanceof Error?y[UK(0xa7)]:String(y)}};}const J=h(W),n=g(W),o={'graphId':J,'graphSchemaVersion':n,'llmConfig':W[UK(0xca)]},Y=v();if(this[UK(UE.H)][UK(UE.i)](Z))return this[UK(UE.Z)](Z,a,UK(UE.J)+Z+UK(UE.n));this['inflightSessions'][UK(0xbb)](Z);const l={'session':Z,...Q[UK(UE.t)]===void 0x0?{}:{'signal':Q['signal']}};return this[UK(0xa4)](l,Y,async()=>{const Uh=UK;let X=!0x0,U0,U1;try{const U2=B(),U3=await this[Uh(0xa5)][Uh(0xb9)](Z,U2,o);U0=U2,U1=U3['expectedRevision'];const U4=U3[Uh(0xd6)]['graph'][Uh(UP.p)]?U3[Uh(0xd6)]:void 0x0;U4&&U4[Uh(UP.Q)][Uh(UP.W)]!==n&&(X=!0x1);const U5=U4?W[Uh(0xd2)]?await W[Uh(0xd2)](U4):U4:void 0x0;if(U5&&U5[Uh(UP.H)][Uh(0xde)]!==n)throw new Error(Uh(0xd3)+J+Uh(UP.i)+U5[Uh(0xcf)][Uh(UP.Z)]+Uh(0xb4)+n+'.');U4&&U5&&U5['graph'][Uh(0xde)]!==U4[Uh(UP.H)][Uh(UP.J)]&&await this[Uh(0xa5)][Uh(0x99)](U5,{'owner':U2,'expectedRevision':U1}),X=!0x0;const U6=U5?this[Uh(UP.n)][Uh(0x95)](U5,J):void 0x0;if(U6?.[Uh(UP.t)])return await this['sessions'][Uh(0x9f)](Z,U2,U1),this[Uh(0xce)](W[Uh(UP.m)],Z);const U7=await W[Uh(UP.s)][Uh(0xe0)]({...H?W[Uh(0xa9)](U6,new A(H)):U6??{},'config':{...U6?.[Uh(0x9d)]??{},...Q[Uh(0x9d)]??{}},'inputConsumed':!0x1,'response':''});return await this[Uh(UP.o)][Uh(0xd9)](Z,U7,o,Y,{'owner':U2,'expectedRevision':U1}),W['responseMode']==='json'?this['jsonResult'](Z,U7[Uh(0xaa)]):this['chatResult'](Z,U7['response'],U7['completed']);}catch(U8){if(U8 instanceof k)return this[Uh(UP.Y)](Z,U8[Uh(UP.l)],U8[Uh(UP.y)]);const U9=U8 instanceof Error?U8[Uh(0xa7)]:String(U8);if(u({'chat_service':U9}),U0)try{await this['sessions'][Uh(UP.X)](Z,U0,o,X?Y:void 0x0,U1);}catch(UU){console[Uh(UP.r)](Uh(0xb1),UU);}return{'status':0x190,'session':Z,'body':{'success':!0x1,'completed':!0x1,'message':U9,'session':Z}};}finally{this[Uh(UP.U0)][Uh(0x98)](Z);}});}[UT(0xa4)](p,Q,W){return d(p,()=>e(Q,W));}async[UT(0xbd)](p){const Ua={p:0xbd},Ug=UT;if(!p)return{'status':0x190,'body':{'success':!0x1,'message':'SESSION_ID\x20is\x20required.'}};try{const Q=w(p);return await this[Ug(0xa5)][Ug(Ua.p)](Q),{'status':0xc8,'body':{'success':!0x0,'session':Q}};}catch(W){return{'status':0x190,'body':{'success':!0x1,'session':p,'message':W instanceof Error?W[Ug(0xa7)]:String(W)}};}}async[UT(0xd5)](){const Uf=UT;await this[Uf(0xa5)]['close']();}[UT(0xba)](p,Q,W){return{'status':0x199,'session':p,'body':{'success':!0x1,'completed':!0x1,'message':W,'code':Q,'session':p}};}[UT(0xce)](p,Q){const UN={p:0xc7},Ux=UT,W='This\x20conversation\x20is\x20already\x20complete.';return p===Ux(0xb6)?this['conflictResult'](Q,q,W):this[Ux(UN.p)](Q,W,!0x0);}[UT(0xa1)](p,Q){return{'status':0xc8,'session':p,'contentType':'application/json','body':z(Q)};}[UT(0xc7)](p,Q,W){return{'status':0xc8,'session':p,'body':{'success':!0x0,'completed':W,'message':Q,'bot':Q,'session':p}};}}function w(p){const Uz={p:0xd8},Uu=UT,Q=p[Uu(Uz.p)]();if(!/^[A-Za-z0-9_-]{1,128}$/['test'](Q))throw new Error('SESSION_ID\x20must\x20be\x201-128\x20letters,\x20numbers,\x20underscores,\x20or\x20hyphens.');return Q;}S(w,UT(0xcd));export{R as GraphEngine};
1
+ const hU=m;(function(A,c){const he={A:0xf7,c:0x131,a:0xfc,S:0x120,t:0xf4,g:0xfb,o:0x11f},hN=m,a=A();while(!![]){try{const S=-parseInt(hN(0xee))/0x1*(-parseInt(hN(he.A))/0x2)+-parseInt(hN(he.c))/0x3+parseInt(hN(he.a))/0x4*(-parseInt(hN(he.S))/0x5)+-parseInt(hN(he.t))/0x6+parseInt(hN(0x10f))/0x7*(parseInt(hN(he.g))/0x8)+-parseInt(hN(0x101))/0x9*(parseInt(hN(he.o))/0xa)+parseInt(hN(0x112))/0xb;if(S===c)break;else a['push'](a['shift']());}catch(t){a['push'](a['shift']());}}}(h,0x63be7));function m(T,N){T=T-0xed;const U=h();let Z=U[T];if(m['kpBgIi']===undefined){var d=function(C){const Q='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let n='',w='';for(let Y=0x0,x,e,J=0x0;e=C['charAt'](J++);~e&&(x=Y%0x4?x*0x40+e:e,Y++%0x4)?n+=String['fromCharCode'](0xff&x>>(-0x2*Y&0x6)):0x0){e=Q['indexOf'](e);}for(let u=0x0,D=n['length'];u<D;u++){w+='%'+('00'+n['charCodeAt'](u)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(w);};m['oLnleT']=d,m['EnHFIY']={},m['kpBgIi']=!![];}const B=U[0x0],E=T+B,f=m['EnHFIY'][E];return!f?(Z=m['oLnleT'](Z),m['EnHFIY'][E]=Z):Z=f,Z;}var C=Object[hU(0x106)],y=(A,c)=>C(A,'name',{'value':c,'configurable':!0x0});import{HumanMessage as T}from'@langchain/core/messages';import{randomUUID as Z}from'node:crypto';import{GraphRegistry as d,registeredGraphId as B,registeredGraphSchemaVersion as f}from'./graph-registry.js';import{LangChainLlmGateway as Q}from'./langchain-llm-gateway.js';import{SessionLogError as n,createSessionLogs as Y,withSessionLogs as e}from'./session-log.js';import{withTurnContext as J}from'./turn-context.js';function h(){const hj=['D2L0Afr1CM5ty29Wzq','zw5KrMfPBgvKvhvYBG','C2nOzw1HvMvYC2LVBG','mta1otC5mNfwy2XWsa','mtC2vM1Oz25n','DxnLCK1LC3nHz2uGBxvZDcbIzsbHig5VBI1LBxb0EsbZDhjPBMCU','z3jHCgHoyw1L','z2v0u2vZC2LVBG','z3jHCgHZ','mZmZmJK3tKjJrLHu','C2f2zvn0yxrL','CMvSzwfZzvr1CM4','z3jHCgG','CMvNAxn0zxi','zgvMAw5LuhjVCgvYDhK','BM9Kzxm','C2LNBMfS','DhjPBq','zgvSzxrL','Aw52B2TL','CMv2AxnPB24','u0vtu0LptL9jrcbTDxn0igjLideTmti4igXLDhrLCNmSig51BwjLCNmSihvUzgvYC2nVCMvZlcbVCIbOExbOzw5ZlG','BgXTq29UzMLN','ndjyBgzOr0C','CMvZCg9UC2vnB2rL','DxnLCK1LC3nHz2u','mtmZmdaXntvzA1fUDNi','zgvSzxrLu2vZC2LVBG','y29UzMLNtwfUywDLCG','BgXTr2f0zxDHEuzHy3rVCNK','ChjLCgfYzuLUChv0','zxjYB3i','r3jHCgGGjW','ChjVDMLKzxjZ','CMvZCg9UC2u','jYbYzxn0B3jLihjLDhvYBMvKihnJAgvTysb2zxjZAw9Uia','y29UzMXPy3rszxn1Bhq','y29TCgXLDgvKu2vZC2LVBLjLC3vSDa','Aw5MBgLNAhrtzxnZAw9UCW','ntb0vNHOzKq','odeWodblqLzrC0m','jYbPCYbUB3qGCMvNAxn0zxjLzc4','z2v0r3jHCgHZ','DMfSAwrHDgvtzxnZAw9Uswq','CgvYC2LZDe1Pz3jHDgvKu2vZC2LVBG','y2HHDfjLC3vSDa','CMvNAxn0CNK','y2XVC2u','DMfSDwvZ','zxHWzwn0zwrszxzPC2LVBG','CMvZDg9YzvnLC3nPB25eB2m','DgvZDa','AgfZ','zg9JDw1LBNq','vgHPCYbJB252zxjZyxrPB24GAxmGywXYzwfKEsbJB21WBgv0zs4','C2vZC2LVBNm','C2vZC2LVBK1HBMfNzxi','mtKXnJu3ngnVB25StW','BwvZC2fNzq','zNjVBunVBMzPzW','CMvZDg9YzvnLC3nPB25eB2n1BwvUDa','y29UzMLN','odmYmwruCfzpzW','ANnVBG','jYbPCYbHBhjLywr5ihbYB2nLC3nPBMCGysb0DxjUlG','y29TCgXLDgvK','C3rYzwfT','r3jHCgHfBMDPBMu','mZK5mtGYneXYsMfQwq','C2vZC2LVBKLK','ANnVBLjLC3vSDa','mtq2rMn3tMPv'];h=function(){return hj;};return h();}import{SessionManager as u,SessionTurnError as W,SESSION_BUSY as z,SESSION_COMPLETED as r}from'./persistence/session-manager.js';import{parseJsonObjectResponse as p}from'./json-response.js';class M{static{y(this,hU(0xf3));}['registry']=new d();[hU(0x12f)];[hU(0x115)];[hU(0x11e)]=new Set();constructor(A={}){const hJ={A:0x115},hZ=hU;this['sessions']=A[hZ(0x130)]??new u(),this[hZ(0x115)]=A[hZ(hJ.A)]??(c=>new Q(c,A[hZ(0x119)]?{'providers':A[hZ(0x119)]}:{})),this['registerGraph'](A[hZ(0x100)]??[]);}static async['create'](A={}){const hu={A:0x133,c:0x114,a:0x115,S:0x100},hd=hU,c=await u[hd(hu.A)](A[hd(hu.c)]);return new M({'sessionManager':c,...A[hd(0x115)]?{'llmGatewayFactory':A[hd(hu.a)]}:{},...A[hd(hu.S)]?{'graphs':A[hd(0x100)]}:{},...A[hd(0x119)]?{'providers':A[hd(0x119)]}:{}});}['registerGraph'](A){const hD={A:0x126},hB=hU,c=A['map'](a=>new a(this[hB(0x115)](a['getGraphDefinition']()[hB(0x10e)])));return this[hB(hD.A)][hB(0x105)](c),this;}[hU(0x122)](){const hW={A:0x126},hE=hU;return this[hE(hW.A)]['names']();}[hU(0xff)](A){const hk={A:0xff},hf=hU;return this[hf(0x12f)][hf(hk.A)](w(A));}async['run'](A){const hr={A:0x118,c:0x121,a:0x109,S:0xfd,t:0xf0,g:0x11e},hz={A:0x104,c:0x107,a:0x12d,S:0xfa,t:0x12a,g:0xfa,o:0x11b,q:0x124,l:0x134,i:0xf1,P:0x11d,R:0x128,K:0x102,H:0x10b,s:0x110,v:0xef,I:0x11a,X:0xf1,h0:0x132,h1:0x12f,h2:0xf9,h3:0x11e,h4:0x10a},hC=hU,c=this[hC(0x126)]['get'](A[hC(0xfe)]);if(!c)return{'status':0x190,'body':{'success':!0x1,'completed':!0x0,'message':hC(hr.A)+(A['graphName']??'')+hC(hr.c)}};const a=typeof A[hC(0x111)]=='string'?A[hC(0x111)][hC(hr.a)]():void 0x0;if(c['requiresUserMessage']!==!0x1&&!a)return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':hC(hr.S)}};let S;try{S=A[hC(0xf5)]?w(A[hC(0xf5)]):Z();}catch(K){return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':K instanceof Error?K[hC(0x132)]:String(K)}};}const o=B(c),q=f(c),l={'graphId':o,'graphSchemaVersion':q,'llmConfig':c['llmConfig']},i=Y();if(this['inflightSessions'][hC(0x12c)](S))return this[hC(0x11c)](S,z,'Session\x20\x27'+S+hC(hr.t));this[hC(hr.g)]['add'](S);const P={'session':S,...A['signal']===void 0x0?{}:{'signal':A[hC(0x108)]}};return this[hC(0xf8)](P,i,async()=>{const hQ=hC;let H=!0x0,X,h0;try{const h1=Z(),h2=await this['sessions']['beginTurn'](S,h1,l);X=h1,h0=h2[hQ(0x129)];const h3=h2[hQ(0x12d)][hQ(hz.A)][hQ(hz.c)]?h2[hQ(hz.a)]:void 0x0;h3&&h3['graph'][hQ(hz.S)]!==q&&(H=!0x1);const h4=h3?c[hQ(hz.t)]?await c[hQ(0x12a)](h3):h3:void 0x0;if(h4&&h4['graph'][hQ(hz.g)]!==q)throw new Error('Graph\x20\x27'+o+hQ(hz.o)+h4[hQ(0x104)][hQ(0xfa)]+';\x20expected\x20'+q+'.');h3&&h4&&h4[hQ(0x104)]['schemaVersion']!==h3['graph']['schemaVersion']&&await this[hQ(0x12f)][hQ(hz.q)](h4,{'owner':h1,'expectedRevision':h0}),H=!0x0;const h5=h4?this[hQ(0x12f)][hQ(hz.l)](h4,o):void 0x0;if(h5?.[hQ(hz.i)])return await this[hQ(0x12f)][hQ(0x103)](S,h1,h0),this[hQ(hz.P)](c[hQ(0x110)],S);const h6={...a?c[hQ(0x116)](h5,new T(a)):h5??{},'config':{...h5?.[hQ(0xed)]??{},...A['config']??{}},'inputConsumed':!0x1,'response':''};let h7;if(c['graph'][hQ(0xf2)]){const h8=await c['graph'][hQ(0xf2)](h6,{'streamMode':hQ(hz.R)});for await(const h9 of h8){if(h7=h9,h7['inputConsumed']!==!0x0)continue;h0=(await this[hQ(0x12f)][hQ(hz.K)](S,h7,l,Y(),{'owner':h1,...h0===void 0x0?{}:{'expectedRevision':h0},'keepTurn':!0x0}))[hQ(0x10c)];}}else h7=await c['graph'][hQ(hz.H)](h6);if(!h7)throw new Error('Graph\x20\x27'+o+'\x27\x20completed\x20without\x20producing\x20state.');return await this[hQ(0x12f)][hQ(0x102)](S,h7,l,i,{'owner':h1,...h0===void 0x0?{}:{'expectedRevision':h0}}),c[hQ(hz.s)]===hQ(hz.v)?this['jsonResult'](S,h7['response']):this[hQ(0x125)](S,h7[hQ(hz.I)],h7[hQ(hz.X)]);}catch(hh){if(hh instanceof W)return this[hQ(0x11c)](S,hh['code'],hh['message']);const hm=hh instanceof Error?hh[hQ(hz.h0)]:String(hh);if(n({'chat_service':hm}),X)try{await this[hQ(hz.h1)][hQ(hz.h2)](S,X,l,H?i:void 0x0,h0);}catch(hT){console[hQ(0x117)]('Unable\x20to\x20persist\x20session\x20error\x20log:',hT);}return{'status':0x190,'session':S,'body':{'success':!0x1,'completed':!0x1,'message':hm,'session':S}};}finally{this[hQ(hz.h3)][hQ(hz.h4)](S);}});}[hU(0xf8)](A,c,a){return J(A,()=>e(c,a));}async['deleteSession'](A){const hp={A:0x113,c:0x132},hn=hU;if(!A)return{'status':0x190,'body':{'success':!0x1,'message':'SESSION_ID\x20is\x20required.'}};try{const c=w(A);return await this['sessions'][hn(hp.A)](c),{'status':0xc8,'body':{'success':!0x0,'session':c}};}catch(a){return{'status':0x190,'body':{'success':!0x1,'session':A,'message':a instanceof Error?a[hn(hp.c)]:String(a)}};}}async[hU(0x127)](){const hF={A:0x12f},hw=hU;await this[hw(hF.A)]['close']();}['conflictResult'](A,c,a){return{'status':0x199,'session':A,'body':{'success':!0x1,'completed':!0x1,'message':a,'code':c,'session':A}};}[hU(0x11d)](A,c){const hY=hU,a=hY(0x12e);return A===hY(0xef)?this['conflictResult'](c,r,a):this[hY(0x125)](c,a,!0x0);}[hU(0xf6)](A,c){return{'status':0xc8,'session':A,'contentType':'application/json','body':p(c)};}['chatResult'](A,c,a){return{'status':0xc8,'session':A,'body':{'success':!0x0,'completed':a,'message':c,'bot':c,'session':A}};}}function w(A){const hS={A:0x12b,c:0x10d},hx=hU,c=A[hx(0x109)]();if(!/^[A-Za-z0-9_-]{1,128}$/[hx(hS.A)](c))throw new Error(hx(hS.c));return c;}y(w,hU(0x123));export{M as GraphEngine};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var n=(s,e)=>v(s,"name",{value:e,configurable:!0});import"reflect-metadata";import{AIMessage as f,HumanMessage as N}from"@langchain/core/messages";import{END as d}from"@langchain/langgraph";import{GraphLlm as m}from"./graph-llm.config.js";import{GraphStateSupport as C}from"./graph-state-support.js";import{ConversationRunner as T,DEFAULT_CONVERSATION_POLICY as O,DEFAULT_MAX_AGENT_ROUNDS as E,EmptyModelResponseError as A}from"./conversation-runner.js";import{currentTurnSignal as L}from"./turn-context.js";import{createConversationToolResult as H,resolveConversationToolResult as M}from"./conversation-tool-result.js";import{createNodeOutcomeBuilder as U,forwardedHistoryUpdate as $,preserveOutcomeRouteTarget as _}from"./node-outcome.js";import{parseJsonObjectResponse as y}from"./json-response.js";import{stableClassId as p}from"./stable-id.js";import{SessionLogWarning as G}from"./session-log.js";import{GRAPH_NODE_LOCAL_STATE as oe}from"./node-outcome.js";const P=Symbol("GRAPH_NODE_CLASS"),g=Symbol("graph-node-tool-handlers");function Q(s){if(!s.trim())throw new Error("A tool handler requires a tool name.");return(e,t)=>{const o=Reflect.getOwnMetadata(g,e)??[];if(o.some(r=>r.toolName===s))throw new Error(`Tool '${s}' already has a handler.`);o.push({toolName:s,methodName:t}),Reflect.defineMetadata(g,o,e)}}n(Q,"Tool");class R{static{n(this,"GraphNode")}llmGateway;runtime;static[P]=!0;static id(){return this.name}supportsAutomaticOutcomeRouting=!1;name;id;constructor(e,t){this.llmGateway=e,this.runtime=t;const o=new.target;this.name=o.name,this.id=p(o,"graph node")}defineTool(){return[]}getLlmConfig(){return{}}route(e){throw new Error(`Graph node '${this.id}' does not define a branch route.`)}async handleTool(e,t,o){const r=this.toolHandler(t.name);if(!r)return this.rejectToolCall(t.name,`Unsupported tool '${t.name}'.`);const i=this.runtime.requireTool(r.toolName),l=b(t.args);if(!l.ok)return this.rejectToolCall(r.toolName,l.error);const a=i.schema.safeParse(l.value);if(!a.success)return this.rejectToolCall(r.toolName,J(a.error));const u=a.data,h=this[r.methodName];if(!h)throw new Error(`Tool '${r.toolName}' is decorated on missing method '${String(r.methodName)}'.`);const c=await h.call(this,u,o,e);return M(c,o)}rejectToolCall(e,t){return G({tool_call:t,node:this.id,tool:e}),{output:{accepted:!1,error:t}}}onInvalidJsonResponse(e){throw e.error}onEmptyModelResponse(e){throw new A(e.reason)}invoke=n(async e=>{const t=await this.run(e),o=await this.resolveJsonResponse(e,t),r=this.runtime.resolveLlmConfig(this.getLlmConfig()),i=x(r,this.runtime.resolveLlmConfig()),l=(e.nodes??{})[this.id];if(i&&l?.model===void 0)return o;const a=this.runtime.saveNode(this.id,{model:i?void 0:m.modelMetadata(r)}),u=o.nodes??{},h=a.nodes??{};return _(o,{...o,nodes:{...u,[this.id]:{...u[this.id]??{},...h[this.id]??{}}}})},"invoke");obtainTools(){return this.toolHandlers().map(({toolName:e})=>this.runtime.requireTool(e)).sort((e,t)=>e.name==="terminate_session"?1:t.name==="terminate_session"?-1:0)}validateTools(){this.obtainTools()}llmConfig(){return this.runtime.resolveLlmConfig(this.getLlmConfig())}llmCallOptions(){return this.runtime.llmCallOptions()}async runConversation(e,t){const o=await this.runAgentLoop(e,t);if(!o.stopReason)return o;const r=await this.onEmptyModelResponse({state:e,conversation:o,reason:o.stopReason});return{...o,response:r}}runAgentLoop(e,t){return new T(this.llmGateway).run({systemPrompt:this.getPrompt(e),history:this.history(e),tools:this.obtainTools(),llmConfig:this.llmConfig(),executeTool:n(o=>this.handleTool(e,o,t),"executeTool"),maxAgentRounds:this.runtime.maxAgentRounds,emptyHistorySeed:this.runtime.conversationPolicy.emptyHistorySeed,emptyResponseRecovery:this.runtime.conversationPolicy.emptyResponseRecovery,callOptions:this.llmCallOptions()})}toolResult(e){return H(e)}historySpace(){return this.runtime.historySpace(this.id)}history(e){return e.histories[this.historySpace()]??[]}historyUpdate(e){return{histories:{[this.historySpace()]:e}}}respond(e){return{...this.runtime.respond(e),...this.historyUpdate([new f(e)])}}complete(e){return{...this.runtime.complete(e),...this.historyUpdate([new f(e)])}}stay(e,t=e.response){const o=w(this.id,"stay",t);return this.outcomeBuilder({currentNode:this.id,...this.runtime.respond(o),...this.historyUpdate(S(e,o)),tokens:e.usage},void 0,d)}resumeAt(e,t){const o=p(e,"graph node");return this.outcomeBuilder({currentNode:o,inputConsumed:!0,response:"",...this.historyUpdate(t.messages),tokens:t.usage},void 0,d)}advance(e,t){return this.transition(e,t,!0)}transition(e,t,o){const r=p(e,"graph node"),i={currentNode:r,inputConsumed:!0,response:"",...this.historyUpdate(t.messages),tokens:t.usage};return o?this.outcomeBuilder(i,(l,a)=>{const u=this.historySpace(),h=[...l.histories[u]??[]].reverse().find(c=>N.isInstance(c));return $({sourceSpace:u,targetSpace:this.runtime.historySpace(r),...h?{latestInput:h}:{},...a?{fallbackMessage:a}:{}})},e):this.outcomeBuilder(i,void 0,e)}finish(e,t){const o=w(this.id,"finish",e);return this.outcomeBuilder({...this.runtime.complete(o),...this.historyUpdate(S(t,o)),tokens:t.usage},void 0,d)}state(e){return e.nodes[this.id]??{}}save(e){return this.runtime.saveNode(this.id,e)}remove(...e){return this.runtime.removeNode(this.id,...e)}outcomeBuilder(e,t,o=d){return U({update:{...e,outcomeRoute:typeof o=="string"?o:p(o,"graph node")},nodeName:this.id,saveNode:n((r,i)=>this.runtime.saveNode(r,i),"saveNode"),routeTarget:o,...t?{forwardInput:t}:{}})}toolHandler(e){return this.toolHandlers().find(t=>t.toolName===e)}async resolveJsonResponse(e,t){if(!this.runtime.expectsJsonResponse()||t.completed!==!0)return t;try{return y(t.response??""),t}catch(o){const r=await this.onInvalidJsonResponse({state:e,update:t,response:t.response??"",error:o instanceof Error?o:new Error(String(o))});return(r.completed===!0||r.response)&&y(r.response??""),r}}toolHandlers(){let e=Object.getPrototypeOf(this);const t=[];for(;e&&e!==R.prototype;){const r=Reflect.getOwnMetadata(g,e)??[];t.push(...r),e=Object.getPrototypeOf(e)}const o=new Set;for(const r of t){if(o.has(r.toolName))throw new Error(`Graph node '${this.id}' has more than one handler for tool '${r.toolName}'.`);o.add(r.toolName)}return t}}function w(s,e,t){if(!t?.trim())throw new Error(`Graph node '${s}' cannot ${e} without an assistant response.`);return t}n(w,"requireOutcomeResponse");function S(s,e){return s.response===e?s.messages:[...s.messages,new f(e)]}n(S,"conversationMessagesWithResponse");function x(s,e){return s.model===e.model&&JSON.stringify(m.parameters(s))===JSON.stringify(m.parameters(e))}n(x,"sameLlmConfig");class Z extends C{static{n(this,"GraphNodeRuntime")}defaultLlmConfig;historySpaces;initialHistorySpace;responseMode;maxAgentRounds;conversationPolicy;tools=new Map;constructor(e,t,o={},r="default",i="chat",l=E,a=O){super(e),this.defaultLlmConfig=t,this.historySpaces=o,this.initialHistorySpace=r,this.responseMode=i,this.maxAgentRounds=l,this.conversationPolicy=a}llmCallOptions(){const{llmTimeoutMs:e}=this.conversationPolicy,t=L();return{...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}}}expectsJsonResponse(){return this.responseMode==="json"}historySpace(e){return e?this.historySpaces[e]??this.initialHistorySpace:this.initialHistorySpace}resolveLlmConfig(e={}){return m.resolveConfig(this.defaultLlmConfig,e)}registerTools(e,t){for(const o of t){const r=this.tools.get(o.name);if(r)throw new Error(`Tool '${o.name}' is defined by both '${r.owner}' and '${e}'.`);this.tools.set(o.name,{definition:o,owner:e})}}requireTool(e){const t=this.tools.get(e);if(!t)throw new Error(`Tool '${e}' is not defined in this graph.`);return t.definition}input(e){return this.latestInput({messages:e.histories[this.historySpace(e.currentNode)]??[]})}respond(e){return this.responseUpdate(e)}complete(e){return this.endUpdate(e)}saveNode(e,t){return this.saveState(e,t)}removeNode(e,...t){return this.removeState(e,...t)}}function b(s){if(typeof s!="string")return{ok:!0,value:s};try{return{ok:!0,value:JSON.parse(s)}}catch(e){return{ok:!1,error:`Tool arguments were not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}n(b,"coerceToolArgs");function J(s){return s.issues.map(e=>e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message).join("; ")}n(J,"formatToolArgumentError");export{P as GRAPH_NODE_CLASS,oe as GRAPH_NODE_LOCAL_STATE,R as GraphNode,Z as GraphNodeRuntime,Q as Tool};
1
+ var S=Object.defineProperty;var s=(n,e)=>S(n,"name",{value:e,configurable:!0});import"reflect-metadata";import{AIMessage as c}from"@langchain/core/messages";import{Command as w,isCommand as f}from"@langchain/langgraph";import{GraphLlm as d}from"./graph-llm.config.js";import{GraphStateSupport as N}from"./graph-state-support.js";import{ConversationRunner as C,DEFAULT_CONVERSATION_POLICY as T,DEFAULT_MAX_AGENT_ROUNDS as R,EmptyModelResponseError as E}from"./conversation-runner.js";import{currentTurnSignal as O}from"./turn-context.js";import{combineGraphNodeUpdates as A}from"./node-outcome.js";import{parseJsonObjectResponse as g}from"./json-response.js";import{stableClassId as y}from"./stable-id.js";import{SessionLogWarning as L}from"./session-log.js";import{isToolResponse as H,stay as b}from"./tool-response.js";import{invocationGraphState as I,hasNodeInvocation as G,invocationHistory as M,invocationNodeState as $,invocationUpdate as U,appendInvocationHistory as _,replaceInvocationNodeState as j,saveInvocationNodeState as P,withNodeInvocation as x}from"./node-invocation.js";import{GRAPH_NODE_LOCAL_STATE as le}from"./node-outcome.js";const J=Symbol("GRAPH_NODE_CLASS"),m=Symbol("graph-node-tool-handlers");function se(n){if(!n.trim())throw new Error("A tool handler requires a tool name.");return(e,t)=>{const o=Reflect.getOwnMetadata(m,e)??[];if(o.some(r=>r.toolName===n))throw new Error(`Tool '${n}' already has a handler.`);o.push({toolName:n,methodName:t}),Reflect.defineMetadata(m,o,e)}}s(se,"Tool");class v{static{s(this,"GraphNode")}llmGateway;runtime;static[J]=!0;static id(){return this.name}name;id;constructor(e,t){this.llmGateway=e,this.runtime=t;const o=new.target;this.name=o.name,this.id=y(o,"graph node")}get graph(){return this.runtime}defineTool(){return[]}getLlmConfig(){return{}}route(e){throw new Error(`Graph node '${this.id}' does not define a branch route.`)}async handleTool(e,t,o){const r=this.toolHandler(t.name);if(!r)return this.rejectToolCall(t.name,`Unsupported tool '${t.name}'.`);const h=this.runtime.requireTool(r.toolName),i=q(t.args);if(!i.ok)return this.rejectToolCall(r.toolName,i.error);const a=h.schema.safeParse(i.value);if(!a.success)return this.rejectToolCall(r.toolName,F(a.error));const l=a.data,p=this[r.methodName];if(!p)throw new Error(`Tool '${r.toolName}' is decorated on missing method '${String(r.methodName)}'.`);const u=await p.call(this,l,o,e);if(H(u))return u;throw new Error(`Tool '${r.toolName}' on '${this.id}' must return a ToolResponse.`)}rejectToolCall(e,t){return L({tool_call:t,node:this.id,tool:e}),b(JSON.stringify({accepted:!1,error:t}))}onInvalidJsonResponse(e){throw e.error}onEmptyModelResponse(e){throw new E(e.reason)}invoke=s(e=>this.runtime.withInvocation(this.id,e,async()=>{const t=await this.run(e),o=k(t),r=await this.resolveJsonResponse(e,o);this.runtime.stageNodeEntries(r.nodes);const h=this.runtime.resolveLlmConfig(this.getLlmConfig()),i=D(h,this.runtime.resolveLlmConfig()),a=(e.nodes??{})[this.id];(!i||a?.model!==void 0)&&this.runtime.saveNode(this.id,{model:i?void 0:d.modelMetadata(h)});const l=A(r,this.runtime.stagedUpdate());return f(t)?new w({update:l,...t.goto===void 0?{}:{goto:t.goto},...t.graph===void 0?{}:{graph:t.graph},...t.resume===void 0?{}:{resume:t.resume}}):l}),"invoke");obtainTools(){return this.toolHandlers().map(({toolName:e})=>this.runtime.requireTool(e)).sort((e,t)=>e.name==="terminate_session"?1:t.name==="terminate_session"?-1:0)}validateTools(){this.obtainTools()}llmConfig(){return this.runtime.resolveLlmConfig(this.getLlmConfig())}llmCallOptions(){return this.runtime.llmCallOptions()}async runConversation(e,t){const o=await this.runAgentLoop(e,t);if(!o.stopReason)return o;const r=await this.onEmptyModelResponse({state:e,conversation:o,reason:o.stopReason});return{...o,response:r}}runAgentLoop(e,t){return new C(this.llmGateway).run({systemPrompt:this.getPrompt(e),history:this.history(e),tools:this.obtainTools(),llmConfig:this.llmConfig(),executeTool:s(o=>this.handleTool(e,o,t),"executeTool"),maxAgentRounds:this.runtime.maxAgentRounds,emptyHistorySeed:this.runtime.conversationPolicy.emptyHistorySeed,emptyResponseRecovery:this.runtime.conversationPolicy.emptyResponseRecovery,callOptions:this.llmCallOptions()})}historySpace(){return this.runtime.historySpace(this.id)}history(e){return this.runtime.hasInvocation()?this.runtime.invocationHistory(this.historySpace()):e.histories[this.historySpace()]??[]}historyUpdate(e){return{histories:{[this.historySpace()]:e}}}respond(e){return{...this.runtime.respond(e),...this.historyUpdate([new c(e)])}}complete(e){return{...this.runtime.complete(e),...this.historyUpdate([new c(e)])}}state(e){return this.runtime.hasInvocation()?this.runtime.nodeState(this.id):e.nodes[this.id]??{}}getState(){return this.runtime.nodeState(this.id)}saveState(e){this.runtime.saveNode(this.id,e)}save(e){return this.runtime.saveNode(this.id,e)}remove(...e){return this.runtime.removeNode(this.id,...e)}toolHandler(e){return this.toolHandlers().find(t=>t.toolName===e)}async resolveJsonResponse(e,t){if(!this.runtime.expectsJsonResponse()||t.completed!==!0)return t;try{return g(t.response??""),t}catch(o){const r=await this.onInvalidJsonResponse({state:e,update:t,response:t.response??"",error:o instanceof Error?o:new Error(String(o))});return(r.completed===!0||r.response)&&g(r.response??""),r}}toolHandlers(){let e=Object.getPrototypeOf(this);const t=[];for(;e&&e!==v.prototype;){const r=Reflect.getOwnMetadata(m,e)??[];t.push(...r),e=Object.getPrototypeOf(e)}const o=new Set;for(const r of t){if(o.has(r.toolName))throw new Error(`Graph node '${this.id}' has more than one handler for tool '${r.toolName}'.`);o.add(r.toolName)}return t}}function D(n,e){return n.model===e.model&&JSON.stringify(d.parameters(n))===JSON.stringify(d.parameters(e))}s(D,"sameLlmConfig");class ie extends N{static{s(this,"GraphNodeRuntime")}defaultLlmConfig;historySpaces;initialHistorySpace;responseMode;maxAgentRounds;conversationPolicy;tools=new Map;constructor(e,t,o={},r="default",h="chat",i=R,a=T){super(e),this.defaultLlmConfig=t,this.historySpaces=o,this.initialHistorySpace=r,this.responseMode=h,this.maxAgentRounds=i,this.conversationPolicy=a}llmCallOptions(){const{llmTimeoutMs:e}=this.conversationPolicy,t=O();return{...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}}}expectsJsonResponse(){return this.responseMode==="json"}historySpace(e){return e?this.historySpaces[e]??this.initialHistorySpace:this.initialHistorySpace}resolveLlmConfig(e={}){return d.resolveConfig(this.defaultLlmConfig,e)}registerTools(e,t){for(const o of t){const r=this.tools.get(o.name);if(r)throw new Error(`Tool '${o.name}' is defined by both '${r.owner}' and '${e}'.`);this.tools.set(o.name,{definition:o,owner:e})}}requireTool(e){const t=this.tools.get(e);if(!t)throw new Error(`Tool '${e}' is not defined in this graph.`);return t.definition}input(e){return this.latestInput({messages:e.histories[this.historySpace(e.currentNode)]??[]})}respond(e){return this.responseUpdate(e)}complete(e){return this.endUpdate(e)}withInvocation(e,t,o){return x(this,e,t,o)}nodeState(e){return $(this,e)}hasInvocation(){return G(this)}graphState(){return I(this)}appendHistory(e,t){_(this,e,t)}invocationHistory(e){return M(this,e)}stagedUpdate(){return U(this)}stageNodeEntries(e){for(const[t,o]of Object.entries(e??{}))!o||typeof o!="object"||Array.isArray(o)||j(this,t,o)}saveNode(e,t){return P(this,e,t),{nodes:{[e]:this.nodeState(e)}}}saveNodeState(e,t){this.saveNode(y(e,"graph node"),t)}removeNode(e,...t){return this.saveNode(e,Object.fromEntries(t.map(o=>[o,void 0])))}}function k(n){if(!f(n))return n;if(Array.isArray(n.update))throw new Error("GraphNode Command updates must be state objects.");return n.update??{}}s(k,"commandUpdate");function q(n){if(typeof n!="string")return{ok:!0,value:n};try{return{ok:!0,value:JSON.parse(n)}}catch(e){return{ok:!1,error:`Tool arguments were not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}s(q,"coerceToolArgs");function F(n){return n.issues.map(e=>e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message).join("; ")}s(F,"formatToolArgumentError");export{J as GRAPH_NODE_CLASS,le as GRAPH_NODE_LOCAL_STATE,v as GraphNode,ie as GraphNodeRuntime,se as Tool};
@@ -1 +1 @@
1
- var c=Object.defineProperty;var e=(n,u)=>c(n,"name",{value:u,configurable:!0});import{Annotation as o,messagesStateReducer as s}from"@langchain/langgraph";import{mergeNodeStates as a}from"./node-state.js";import{addTokenUsage as f,emptyTokenUsage as m}from"./token-usage.js";const R="end";function k(n,u){return o.Root({histories:o({reducer:e((t,r)=>i(t??{},r??{}),"reducer"),default:e(()=>({}),"default")}),currentNode:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>n,"default")}),config:o({reducer:e((t,r)=>({...t,...r}),"reducer"),default:e(()=>({}),"default")}),nodes:o({reducer:a,default:e(()=>u?u():{},"default")}),tokens:o({reducer:f,default:m}),inputConsumed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")}),response:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>"","default")}),completed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")}),outcomeRoute:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>{},"default")})})}e(k,"createGraphStateAnnotation");function i(n,u){const t={...n};for(const[r,d]of Object.entries(u))t[r]=s(t[r]??[],d);return t}e(i,"mergeHistories");export{R as GRAPH_END_NODE,k as createGraphStateAnnotation};
1
+ var c=Object.defineProperty;var e=(u,n)=>c(u,"name",{value:n,configurable:!0});import{Annotation as o,messagesStateReducer as s}from"@langchain/langgraph";import{replaceNodeStates as a}from"./node-state.js";import{addTokenUsage as f,emptyTokenUsage as m}from"./token-usage.js";const k="end";function A(u,n){return o.Root({histories:o({reducer:e((t,r)=>i(t??{},r??{}),"reducer"),default:e(()=>({}),"default")}),currentNode:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>u,"default")}),config:o({reducer:e((t,r)=>({...t,...r}),"reducer"),default:e(()=>({}),"default")}),nodes:o({reducer:a,default:e(()=>n?n():{},"default")}),tokens:o({reducer:f,default:m}),inputConsumed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")}),response:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>"","default")}),completed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")})})}e(A,"createGraphStateAnnotation");function i(u,n){const t={...u};for(const[r,d]of Object.entries(n))t[r]=s(t[r]??[],d);return t}e(i,"mergeHistories");export{k as GRAPH_END_NODE,A as createGraphStateAnnotation};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var g=(c,t)=>v(c,"name",{value:t,configurable:!0});import{HumanMessage as f,SystemMessage as h}from"@langchain/core/messages";import{initChatModel as y}from"langchain";import{assertLlmTimeoutMs as M}from"./llm-gateway.js";import{GraphLlm as m}from"./graph-llm.config.js";import{langChainModelInitialization as k}from"./langchain-provider.adapter.js";import{validateModelProviderAdapters as S}from"./model-provider.js";import{SessionLogWarning as x}from"./session-log.js";import{modelExecution as l,tokenUsageFromMessage as u}from"./token-usage.js";class _{static{g(this,"LangChainLlmGateway")}models=new Map;llmConfig;providers;constructor(t,e={}){this.llmConfig=m.validateConfig(t),this.providers=e.providers??[],S(this.providers)}async generate(t,e,i=this.llmConfig,n){const o=await this.invoke(i,n,async s=>(await this.getModel(i)).invoke([new h(t),new f(e)],s));return{value:typeof o.content=="string"?o.content:JSON.stringify(o.content),usage:u(o),execution:l(i)}}async structured(t,e,i,n,o=this.llmConfig,s,a){const r=await this.invoke(o,a,async d=>(await this.getModel(o)).withStructuredOutput(t,{name:n,method:"functionCalling",includeRaw:!0}).invoke(this.messages(e,s,i),d));return{value:r.parsed,usage:u(r.raw),execution:l(o)}}async respond(t,e,i=this.llmConfig,n){const o=await this.invoke(i,n,async s=>(await this.getModel(i)).invoke([new h(t),...e],s));return{value:typeof o.content=="string"?o.content:JSON.stringify(o.content),usage:u(o),execution:l(i)}}async agent(t,e,i,n=this.llmConfig,o){const s=await this.invoke(n,o,async a=>w(await this.getModel(n),i,n.params.forceToolCalls).invoke([new h(t),...e],a));return{value:s,usage:u(s),execution:l(n)}}async toolCall(t,e,i,n=this.llmConfig,o,s){const a=await this.invoke(n,s,async d=>w(await this.getModel(n),i,n.params.forceToolCalls).invoke(this.messages(t,o,e),d)),r=a.tool_calls?.[0];return{value:r?{name:r.name,args:r.args}:void 0,usage:u(a),execution:l(n)}}messages(t,e,i){return[new h(t),...e??[],new f(i)]}getModel(t){const e=k(t,this.providers),i=e.cacheKey??JSON.stringify({model:e.model,options:e.options}),n=this.models.get(i);if(n)return n;const o=y(e.model,e.options).then(s=>(m.validateProfile(t,s.profile),s));return this.models.set(i,o),o}async invoke(t,e,i){const n=e?.timeoutMs===void 0?void 0:M(e.timeoutMs),o=n===void 0?void 0:AbortSignal.timeout(n),s=[e?.signal,o].filter(r=>r!==void 0),a=s.length>1?AbortSignal.any(s):s[0];try{return await i(a?{signal:a}:void 0)}catch(r){const d=o?.aborted===!0&&e?.signal?.aborted!==!0,p=d?`Model call for '${m.modelIdentifier(t)}' exceeded its ${String(n)} ms timeout.`:r instanceof Error?r.message:String(r);throw x({llm_call:p,model:m.modelIdentifier(t)}),d?new Error(p,{cause:r}):r}}}function w(c,t,e=!1){if(t.length>0&&c.profile.toolCalling===!1)throw new Error("The selected model profile reports that tool calling is unsupported.");if(e&&c.profile.toolChoice===!1)throw new Error("The selected model profile reports that tool choice is unsupported.");return c.bindTools(t,e?{tool_choice:"any"}:void 0)}g(w,"bindTools");export{_ as LangChainLlmGateway};
1
+ var k=Object.defineProperty;var g=(l,o)=>k(l,"name",{value:o,configurable:!0});import{HumanMessage as w,SystemMessage as h}from"@langchain/core/messages";import{initChatModel as x}from"langchain";import{assertLlmTimeoutMs as S}from"./llm-gateway.js";import{GraphLlm as m}from"./graph-llm.config.js";import{langChainModelInitialization as T}from"./langchain-provider.adapter.js";import{validateModelProviderAdapters as b}from"./model-provider.js";import{SessionLogWarning as A}from"./session-log.js";import{modelExecution as d,tokenUsageFromMessage as u}from"./token-usage.js";import{isOpenAIAuthConfig as v,openAIAuthMessageText as y}from"./openai-auth-provider.js";class K{static{g(this,"LangChainLlmGateway")}models=new Map;llmConfig;providers;constructor(o,e={}){this.llmConfig=m.validateConfig(o),this.providers=e.providers??[],b(this.providers)}async generate(o,e,n=this.llmConfig,i){const t=await this.invoke(n,i,async s=>(await this.getModel(n)).invoke([new h(o),new w(e)],s));return{value:v(n)?y(t.content):typeof t.content=="string"?t.content:JSON.stringify(t.content),usage:u(t),execution:d(n)}}async structured(o,e,n,i,t=this.llmConfig,s,a){const c=await this.invoke(t,a,async r=>(await this.getModel(t)).withStructuredOutput(o,{name:i,method:"functionCalling",includeRaw:!0}).invoke(this.messages(e,s,n),r));return{value:c.parsed,usage:u(c.raw),execution:d(t)}}async respond(o,e,n=this.llmConfig,i){const t=await this.invoke(n,i,async s=>(await this.getModel(n)).invoke([new h(o),...e],s));return{value:v(n)?y(t.content):typeof t.content=="string"?t.content:JSON.stringify(t.content),usage:u(t),execution:d(n)}}async agent(o,e,n,i=this.llmConfig,t){const s=await this.invoke(i,t,async a=>M(await this.getModel(i),n,i.params.forceToolCalls).invoke([new h(o),...e],a));return{value:s,usage:u(s),execution:d(i)}}async toolCall(o,e,n,i=this.llmConfig,t,s){const a=await this.invoke(i,s,async r=>M(await this.getModel(i),n,i.params.forceToolCalls).invoke(this.messages(o,t,e),r)),c=a.tool_calls?.[0];return{value:c?{name:c.name,args:c.args}:void 0,usage:u(a),execution:d(i)}}messages(o,e,n){return[new h(o),...e??[],new w(n)]}getModel(o){const e=T(o,this.providers),n=e.cacheKey??JSON.stringify({model:e.model,options:e.options}),i=this.models.get(n);if(i)return i;const t=x(e.model,e.options).then(s=>(m.validateProfile(o,s.profile),s));return this.models.set(n,t),t}async invoke(o,e,n){const i=e?.timeoutMs===void 0?void 0:S(e.timeoutMs),t=i===void 0?void 0:new AbortController,s=t?setTimeout(()=>t.abort(new Error("Model call timed out.")),i):void 0,a=[e?.signal,t?.signal].filter(r=>r!==void 0),c=a.length>1?AbortSignal.any(a):a[0];try{return await n(c?{signal:c}:void 0)}catch(r){const p=t?.signal.aborted===!0&&e?.signal?.aborted!==!0,f=p?`Model call for '${m.modelIdentifier(o)}' exceeded its ${String(i)} ms timeout.`:r instanceof Error?r.message:String(r);throw A({llm_call:f,model:m.modelIdentifier(o)}),p?new Error(f,{cause:r}):r}finally{s&&clearTimeout(s)}}}function M(l,o,e=!1){if(o.length>0&&l.profile.toolCalling===!1)throw new Error("The selected model profile reports that tool calling is unsupported.");if(e&&l.profile.toolChoice===!1)throw new Error("The selected model profile reports that tool choice is unsupported.");return l.bindTools(o,e?{tool_choice:"any"}:void 0)}g(M,"bindTools");export{K as LangChainLlmGateway};
@@ -1 +1 @@
1
- const E=T;(function(B,K){const q={B:0xaf,K:0x9d,h:0xa6,g:0xa1,x:0xa9,u:0xad},P=T,h=B();while(!![]){try{const g=-parseInt(P(q.B))/0x1*(-parseInt(P(q.K))/0x2)+-parseInt(P(0xaa))/0x3+parseInt(P(0x98))/0x4+parseInt(P(q.h))/0x5+parseInt(P(q.g))/0x6*(parseInt(P(0xa4))/0x7)+parseInt(P(q.x))/0x8+parseInt(P(0xa7))/0x9*(-parseInt(P(q.u))/0xa);if(g===K)break;else h['push'](h['shift']());}catch(x){h['push'](h['shift']());}}}(U,0xe9bc9));var d=Object[E(0x9a)],s=(B,K)=>d(B,E(0xa2),{'value':K,'configurable':!0x0});import{GraphLlm as C,ModelCatalog as D}from'./graph-llm.config.js';import{modelProviderAdapter as A}from'./model-provider.js';function M(B,K=[]){const b={B:0xa3,K:0x9e,h:0x9b},k=E,h=C[k(0x9c)](B),g=D[k(0x99)](h),x={};for(const [G,V]of Object[k(0xac)](h[k(0xb1)])){const O=g[k(0xb2)][G];O!==null&&v(x,O??G,V);}const u=A(g['provider'],K)??g[k(b.B)];return u?u[k(0xab)]({'provider':g[k(b.K)],'model':g[k(b.h)],'options':x}):{'model':g[k(0x9b)],'options':{'modelProvider':g[k(b.K)],...x}};}function T(M,C){M=M-0x97;const D=U();let c=D[M];if(T['VKtcuj']===undefined){var A=function(g){const f='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let x='',u='';for(let v=0x0,G,V,e=0x0;V=g['charAt'](e++);~V&&(G=v%0x4?G*0x40+V:V,v++%0x4)?x+=String['fromCharCode'](0xff&G>>(-0x2*v&0x6)):0x0){V=f['indexOf'](V);}for(let O=0x0,d=x['length'];O<d;O++){u+='%'+('00'+x['charCodeAt'](O)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(u);};T['fKhknC']=A,T['utqQPK']={},T['VKtcuj']=!![];}const B=D[0x0],K=M+B,h=T['utqQPK'][K];return!h?(c=T['fKhknC'](c),T['utqQPK'][K]=c):c=h,c;}function U(){const S=['nda1ndi2s09jDNL6','Aw5PDgLHBgL6zq','zw50CMLLCW','ndbvt0rvwgm','BgfUz0nOywLUtw9KzwXjBML0AwfSAxPHDgLVBG','mKjqteLYqG','jYbOyxmGysbJB25MBgLJDgLUzYbWyxrOlG','CgfYyw1Z','CgfYyw1LDgvYtwfWCgLUz3m','C2v0ugf0Aa','nde2mJq5nNfivfP5Aq','CMvZB2X2zu1VzgvSrgvZy3jPChrVCG','zgvMAw5LuhjVCgvYDhK','ChjVDMLKzxjnB2rLBa','DMfSAwrHDgvdB25MAwC','mtiXndK1ogXRD2r5AG','ChjVDMLKzxi','C3bSAxq','C2XPy2u','odG4ndq1mLPnrfvkzq','BMfTzq','ChjVDMLKzxjbzgfWDgvY','n1DQBvjrrW','AxnbCNjHEq','nZm5nJGZmeXTEfzjwG','mtiXodeXndLXs1fHtKy','B2jQzwn0','mtaZmJu0ndH0quzStgm'];U=function(){return S;};return U();}s(M,E(0xae));function v(B,K,h){const N={B:0xa8,K:0xb0},a=E,g=K[a(0x9f)]('.');let x=B;for(const G of g[a(0xa0)](0x0,-0x1)){const V=x[G];if(V===void 0x0){const O={};x[G]=O,x=O;}else{if(typeof V==a(N.B)&&V!==null&&!Array[a(0xa5)](V))x=V;else throw new Error('Catalog\x20parameter\x20mapping\x20\x27'+K+a(N.K));}}const u=g['at'](-0x1);if(!u)throw new Error('Catalog\x20parameter\x20mapping\x20paths\x20cannot\x20be\x20empty.');x[u]=h;}s(v,E(0x97));export{M as langChainModelInitialization};
1
+ function h(){const V=['CMvZB2X2zu1VzgvSrgvZy3jPChrVCG','DMfSAwrHDgvdB25MAwC','zw50CMLLCW','CgfYyw1Z','ntuYndy4DNHqAfjm','CgfYyw1LDgvYtwfWCgLUz3m','C2v0ugf0Aa','BgfUz0nOywLUtw9KzwXjBML0AwfSAxPHDgLVBG','Aw5PDgLHBgL6zq','ntCXmZCYohLHBhDsra','ndbUuejIqM8','ChjVDMLKzxjnB2rLBa','ChjVDMLKzxi','B2jQzwn0','ChjVDMLKzxjbzgfWDgvY','BMfTzq','C2XPy2u','ntKXnJCXELjNrNDU','nZDVtujpzhK','mZeYotq1m1vtC294qG','q2f0ywXVzYbWyxjHBwv0zxiGBwfWCgLUzYaN','C3bSAxq','nde1nZq5nxn1CKL2Aq','q2f0ywXVzYbWyxjHBwv0zxiGBwfWCgLUzYbWyxrOCYbJyw5UB3qGyMuGzw1WDhKU','mJqWndK2nwzoDNfWqq','AxnbCNjHEq','mJm2nJa5nePzAg10ta'];h=function(){return V;};return h();}const r=T;(function(E,Q){const F={E:0x17a,Q:0x16b,n:0x178,w:0x166},z=T,n=E();while(!![]){try{const w=parseInt(z(0x173))/0x1+-parseInt(z(0x17c))/0x2+-parseInt(z(F.E))/0x3+-parseInt(z(F.Q))/0x4+parseInt(z(F.n))/0x5+parseInt(z(F.w))/0x6*(parseInt(z(0x174))/0x7)+parseInt(z(0x16c))/0x8*(parseInt(z(0x175))/0x9);if(w===Q)break;else n['push'](n['shift']());}catch(Y){n['push'](n['shift']());}}}(h,0xb9e87));var s=Object['defineProperty'],l=(E,Q)=>s(E,r(0x171),{'value':Q,'configurable':!0x0});import{GraphLlm as N,ModelCatalog as U}from'./graph-llm.config.js';function T(m,N){m=m-0x165;const U=h();let Z=U[m];if(T['uapbbH']===undefined){var d=function(C){const Q='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let n='',w='';for(let Y=0x0,x,e,J=0x0;e=C['charAt'](J++);~e&&(x=Y%0x4?x*0x40+e:e,Y++%0x4)?n+=String['fromCharCode'](0xff&x>>(-0x2*Y&0x6)):0x0){e=Q['indexOf'](e);}for(let u=0x0,D=n['length'];u<D;u++){w+='%'+('00'+n['charCodeAt'](u)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(w);};T['ujitrk']=d,T['tGlJwF']={},T['uapbbH']=!![];}const B=U[0x0],E=m+B,f=T['tGlJwF'][E];return!f?(Z=T['ujitrk'](Z),T['tGlJwF'][E]=Z):Z=f,Z;}import{modelProviderAdapter as Z}from'./model-provider.js';import{OPENAI_AUTH_PROVIDER as d,initializeOpenAIAuthProvider as B}from'./openai-auth-provider.js';function C(E,Q=[]){const A={E:0x17e,Q:0x17d,n:0x165,w:0x167,Y:0x16d,x:0x16e,e:0x170,J:0x16a,D:0x16e},b=r,w=N[b(A.E)](E),Y=U[b(A.Q)](w),x={};for(const [D,W]of Object[b(0x17f)](w[b(A.n)])){const k=Y[b(A.w)][D];k!==null&&u(x,k??D,W);}if(Y[b(0x16e)]===d)return B(Y[b(A.Y)],x);const J=Z(Y[b(A.x)],Q)??Y[b(A.e)];return J?J[b(A.J)]({'provider':Y[b(A.D)],'model':Y[b(A.Y)],'options':x}):{'model':Y[b(A.Y)],'options':{'modelProvider':Y[b(0x16e)],...x}};}l(C,r(0x169));function u(E,Q,w){const a={E:0x16f,Q:0x17b,n:0x176,w:0x179},p=r,Y=Q[p(0x177)]('.');let x=E;for(const D of Y[p(0x172)](0x0,-0x1)){const W=x[D];if(W===void 0x0){const k={};x[D]=k,x=k;}else{if(typeof W==p(a.E)&&W!==null&&!Array[p(a.Q)](W))x=W;else throw new Error(p(a.n)+Q+'\x27\x20has\x20a\x20conflicting\x20path.');}}const J=Y['at'](-0x1);if(!J)throw new Error(p(a.w));x[J]=w;}l(u,r(0x168));export{C as langChainModelInitialization};