@picoflow/ezgraph 0.0.6 → 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 (32) hide show
  1. package/README.md +172 -88
  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/node-invocation.js +1 -0
  11. package/dist/framework/node-outcome.js +1 -1
  12. package/dist/framework/node-state.js +1 -1
  13. package/dist/framework/persistence/session-manager.js +1 -1
  14. package/dist/framework/state-graph-ext.js +1 -1
  15. package/dist/framework/tool-response.js +1 -0
  16. package/dist/index.js +1 -1
  17. package/dist/types/npmlib/src/index.d.ts +4 -4
  18. package/dist/types/src/framework/base-graph.d.ts +8 -0
  19. package/dist/types/src/framework/conversation-node.d.ts +8 -14
  20. package/dist/types/src/framework/conversation-runner.d.ts +3 -3
  21. package/dist/types/src/framework/graph-node.d.ts +24 -21
  22. package/dist/types/src/framework/graph-registry.d.ts +3 -0
  23. package/dist/types/src/framework/graph-state.d.ts +0 -2
  24. package/dist/types/src/framework/node-invocation.d.ts +12 -0
  25. package/dist/types/src/framework/node-outcome.d.ts +1 -30
  26. package/dist/types/src/framework/node-state.d.ts +2 -1
  27. package/dist/types/src/framework/persistence/session-manager.d.ts +1 -0
  28. package/dist/types/src/framework/state-graph-ext.d.ts +2 -8
  29. package/dist/types/src/framework/tool-response.d.ts +25 -0
  30. package/package.json +1 -1
  31. package/dist/framework/conversation-tool-result.js +0 -1
  32. package/dist/types/src/framework/conversation-tool-result.d.ts +0 -19
package/README.md CHANGED
@@ -1,110 +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
23
16
 
24
- For the product overview, tutorial, and full developer guide, visit
25
- [picoflow.io/ezgraph](https://www.picoflow.io/ezgraph/).
17
+ ```bash
18
+ npm install @picoflow/ezgraph zod
26
19
 
27
- ## Requirements
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
+ ```
25
+
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
46
- ```
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
47
 
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`.
48
+ There is no per-turn context object, post-tool transition hook, synthetic tool
49
+ result, or automatic outcome router to maintain.
51
50
 
52
- ## Start an application graph
51
+ ## Define durable state
53
52
 
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`.
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.
57
55
 
58
56
  ```ts
59
- import "reflect-metadata";
60
- import { GraphEngine } from "@picoflow/ezgraph";
61
- import { WeatherGraph } from "./weather-graph.js";
57
+ import { createGraphStateAnnotation, type NodeStateValue } from "@picoflow/ezgraph";
58
+ import { CityNode } from "./nodes/city.node.js";
62
59
 
63
- const engine = await GraphEngine.create({ graphs: [WeatherGraph] });
60
+ export type WeatherGraphNodes = {
61
+ CityNode?: NodeStateValue<{ city?: string }>;
62
+ WeatherNode?: NodeStateValue<{ forecast?: string }>;
63
+ };
64
64
 
65
- const result = await engine.run({
66
- graphName: "WeatherGraph",
67
- sessionId: "customer-123",
68
- userMessage: "I need the weather in Seattle",
69
- });
65
+ export const WeatherGraphState = createGraphStateAnnotation(
66
+ CityNode.name,
67
+ () => ({} as WeatherGraphNodes),
68
+ );
70
69
 
71
- // { status, body, session }
70
+ export type WeatherGraphStateType = typeof WeatherGraphState.State;
72
71
  ```
73
72
 
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
- ### Experimental local OpenAI auth
73
+ ## Write a conversational node
79
74
 
80
- For local development, `openai-auth` uses the OAuth session owned by an
81
- already signed-in Codex client. The graph only selects the built-in model; no
82
- provider adapter or `OPENAI_API_KEY` is required:
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.
83
78
 
84
79
  ```ts
85
- ModelCatalog.model("openai-auth:gpt-5.4", {
86
- retries: 3,
87
- reasoningEffort: "low",
88
- });
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
+ }
89
115
  ```
90
116
 
91
- The provider reads `~/.codex/auth.json` for each request and never writes the
92
- shared credential or refresh token. Run `codex` when the access token expires.
93
- `EZGRAPH_OPENAI_AUTH_FILE` and `EZGRAPH_OPENAI_AUTH_BASE_URL` override the
94
- local defaults for testing.
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.
95
120
 
96
- This provider targets a private ChatGPT Codex backend. It is experimental,
97
- intended for local use, and may change independently of the supported OpenAI
98
- API-key provider.
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)`.
99
124
 
100
- For a complete two-stage graph, including state, a tool handler, explicit
101
- outcomes, and graph registration, follow the
102
- [Get started tutorial](https://www.picoflow.io/ezgraph/tutorial/).
125
+ ## Build and register the graph
103
126
 
104
- ## Persistence and configuration
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.
105
131
 
106
- The default `SESSION_STORE=memory` is useful for local development. Select a
107
- durable store when conversations must resume across process restarts or
132
+ ```ts
133
+ import "reflect-metadata";
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
+ }
173
+
174
+ const engine = await GraphEngine.create({ graphs: [WeatherGraph] });
175
+ const result = await engine.run({
176
+ graphName: "WeatherGraph",
177
+ userMessage: "I need the weather in Seattle",
178
+ });
179
+ ```
180
+
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.
184
+
185
+ ## Persistence and providers
186
+
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
108
189
  instances:
109
190
 
110
191
  ```dotenv
@@ -112,33 +193,36 @@ instances:
112
193
  SESSION_STORE=sqlite
113
194
  SQLITE_DB_PATH=./data/sessions.sqlite
114
195
 
115
- # Set the credential for the model provider you use.
196
+ # Example provider credential
116
197
  OPENAI_API_KEY=...
117
198
  ```
118
199
 
119
200
  For MongoDB, configure `MONGODB_URL`, `MONGODB_NAME`, and
120
- `MONGODB_COLLECTION`. For Cosmos DB, use the Cosmos settings described in the
121
- [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
122
205
 
123
- The [EZGraph demo application](https://github.com/picoflowio/ezgraph-demo)
124
- shows a NestJS + Fastify service with QuoteGraph, a LangGraph comparison, and a
125
- 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.
126
209
 
127
210
  ## Learn more
128
211
 
129
- - [Get started tutorial](https://www.picoflow.io/ezgraph/tutorial/)
212
+ - [Tutorial](https://www.picoflow.io/ezgraph/tutorial/)
130
213
  - [Developer guide](https://www.picoflow.io/ezgraph/docs/developer-guide/)
131
214
  - [QuoteGraph walkthrough](https://www.picoflow.io/ezgraph/quote-graph/)
132
- - [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)
133
217
 
134
218
  ## License
135
219
 
136
220
  EZGraph is proprietary software distributed under the
137
221
  [EZGraph Commercial Runtime License](https://www.picoflow.io/ezgraph/license/).
138
- Personal use, commercial SaaS, internal enterprise production, client work,
139
- and closed-source applications are permitted with no EZGraph runtime fee or
140
- license key. Optional support is separate; an active support subscription
141
- 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.
142
226
 
143
- See the [license page](https://www.picoflow.io/ezgraph/license/) for the
144
- 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 GN=e;(function(Y,R){const Go={Y:0x1df,R:0x1f1,Z:0x20f,m:0x209},Ga=e,Z=Y();while(!![]){try{const m=-parseInt(Ga(0x1f2))/0x1*(parseInt(Ga(Go.Y))/0x2)+-parseInt(Ga(0x1de))/0x3*(-parseInt(Ga(0x1e5))/0x4)+parseInt(Ga(0x20a))/0x5+parseInt(Ga(0x1ed))/0x6*(parseInt(Ga(Go.R))/0x7)+-parseInt(Ga(0x1dc))/0x8*(-parseInt(Ga(0x1f7))/0x9)+-parseInt(Ga(Go.Z))/0xa*(-parseInt(Ga(0x204))/0xb)+-parseInt(Ga(Go.m))/0xc;if(m===R)break;else Z['push'](Z['shift']());}catch(J){Z['push'](Z['shift']());}}}(G,0x8250d));var v=Object[GN(0x1ef)],p=(Y,R)=>v(Y,GN(0x207),{'value':R,'configurable':!0x0});import{HumanMessage as j,ToolMessage as g}from'@langchain/core/messages';import{addTokenUsage as E,emptyTokenUsage as X}from'./token-usage.js';import{describeStopReason as a,isRetryableStopReason as w,modelStopReason as i}from'./model-stop-reason.js';import{SessionLogWarning as c}from'./session-log.js';import{isOpenAIAuthConfig as f,openAIAuthMessageText as o}from'./openai-auth-provider.js';class V extends Error{static{p(this,GN(0x1ea));}[GN(0x200)];constructor(Y){const GY={Y:0x1db},GF=GN;super(GF(GY.Y)+a(Y)+').'),this[GF(0x200)]=Y,this[GF(0x207)]=GF(0x1ea);}}const D=0x8;function L(Y){const GU=GN;if(!Number[GU(0x20c)](Y)||Y<0x1)throw new Error('maxAgentRounds\x20must\x20be\x20a\x20positive\x20integer;\x20received\x20'+String(Y)+'.');return Y;}p(L,GN(0x20d));const S=GN(0x1f3),T={'retries':0x2,'nudge':GN(0x1e8)};function e(j,S){j=j-0x1da;const C=G();let g=C[j];if(e['zpVeGM']===undefined){var E=function(F){const U='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let w='',i='';for(let c=0x0,q,f,o=0x0;f=F['charAt'](o++);~f&&(q=c%0x4?q*0x40+f:f,c++%0x4)?w+=String['fromCharCode'](0xff&q>>(-0x2*c&0x6)):0x0){f=U['indexOf'](f);}for(let Y=0x0,R=w['length'];Y<R;Y++){i+='%'+('00'+w['charCodeAt'](Y)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(i);};e['BHXLBH']=E,e['kNhkym']={},e['zpVeGM']=!![];}const X=C[0x0],a=j+X,N=e['kNhkym'][a];return!N?(g=e['BHXLBH'](g),e['kNhkym'][a]=g):g=N,g;}function $(Y){const Gw=GN;if(!Number[Gw(0x20c)](Y)||Y<0x0)throw new Error(Gw(0x20b)+String(Y)+'.');return Y;}p($,GN(0x20e));const q={'emptyHistorySeed':S,'emptyResponseRecovery':T};class W{static{p(this,'ConversationRunner');}[GN(0x1fd)];constructor(Y){const Gi=GN;this[Gi(0x1fd)]=Y;}async[GN(0x1da)](Y){const GJ={Y:0x1ee,R:0x205,Z:0x208,m:0x202,J:0x203,Q:0x1eb,s:0x1fd,K:0x1fb,n:0x1e2,H:0x1e9,u:0x1f9,t:0x1f0,B:0x1e0,r:0x1fe,z:0x201,h:0x1dd,d:0x206,l:0x201,y:0x1e1,k:0x201},Gc=GN,Z=Y['emptyHistorySeed']===void 0x0?S:Y[Gc(GJ.Y)],J=Y[Gc(GJ.R)][Gc(GJ.Z)]===0x0&&Z!==null,Q=J?[new j(Z)]:[...Y[Gc(0x205)]],K=J?[...Q]:[];let H=[],t=X();const B=L(Y[Gc(GJ.m)]??D),z=Y[Gc(GJ.J)]===void 0x0?T:Y['emptyResponseRecovery'],k=z?$(z[Gc(GJ.Q)]):0x0;let G0=0x0;for(let G2=0x0;G2<B;G2+=0x1){let G3;try{G3=await this[Gc(GJ.s)]['agent'](Y[Gc(0x1ec)],Q,Y[Gc(GJ.K)],Y[Gc(0x1ff)],Y[Gc(GJ.n)]);}catch(G6){const G7=H;throw H=[],await Promise[Gc(0x1e6)](G7[Gc(GJ.H)](G8=>G8())),G6;}t=E(t,G3[Gc(GJ.u)]),K['push'](G3[Gc(GJ.t)]),Q['push'](G3['value']);const G4=G3[Gc(0x1f0)][Gc(GJ.B)]??[];if(G4[Gc(0x208)]===0x0){const G8=f(Y['llmConfig'])?o(G3[Gc(GJ.t)][Gc(0x1f8)]):F(G3[Gc(0x1f0)]);if(G8[Gc(GJ.r)]())return await G1(),{'messages':K,'usage':t,'response':G8,'stoppedAfterTool':!0x1};const G9=i(G3[Gc(0x1f0)]),GG=w(G9)&&z!==null&&G0<k;if(c({'empty_model_response':a(G9),'retried':GG}),GG&&z){G0+=0x1,K[Gc(0x1f4)](),Q[Gc(0x1f4)](),Q[Gc(GJ.z)](new j(z[Gc(GJ.h)]));continue;}return await G1(),{'messages':K,'usage':t,'response':G8,'stoppedAfterTool':!0x1,'stopReason':G9};}await G1();let G5=!0x1;try{for(const [Ge,Gj]of G4[Gc(0x1fa)]()){const GS=await Y[Gc(0x1e7)](Gj),GC=new g({'content':JSON[Gc(0x1e4)](GS[Gc(GJ.d)]),'tool_call_id':Gj['id']??'tool-call-'+G2+'-'+Ge,'name':Gj[Gc(0x207)]});K['push'](GC),Q['push'](GC),GS['messages']&&(K[Gc(GJ.l)](...GS[Gc(0x1f5)]),Q[Gc(0x201)](...GS['messages'])),GS[Gc(GJ.y)]&&H[Gc(GJ.k)](GS[Gc(0x1e1)]),G5||=GS['stopAfterBatch']===!0x0;}}catch(Gg){throw await G1(),Gg;}if(G5)return await G1(),{'messages':K,'usage':t,'stoppedAfterTool':!0x0};}throw await G1(),new Error('Conversation\x20exceeded\x20'+B+Gc(0x1f6));async function G1(){const Gq=Gc,GE=H;H=[],await Promise[Gq(0x1e6)](GE['map'](GX=>GX()));}p(G1,Gc(0x1e3));}}function G(){const Gs=['nZi0mZrXsNnKC2m','u3rHCNq','Cg9W','BwvZC2fNzxm','igfNzw50ihjVDw5KCY4','mti3mde5n2DZt0vbEa','y29UDgvUDa','DxnHz2u','zw50CMLLCW','Dg9VBhm','BwvZC2fNzvrLEhq','BgXTr2f0zxDHEq','DhjPBq','BgXTq29UzMLN','CMvHC29U','ChvZAa','Bwf4qwDLBNrsB3vUzhm','zw1WDhLszxnWB25ZzvjLy292zxj5','mJCXn2j5zwDkvG','AgLZDg9YEq','B3v0Chv0','BMfTzq','BgvUz3rO','odu3nZK5nK9WwfvKDq','mJq2nZG1y0DxthrP','zw1WDhLszxnWB25ZzvjLy292zxj5lNjLDhjPzxmGBxvZDcbIzsbHig5VBI1UzwDHDgL2zsbPBNrLz2vYoYbYzwnLAxzLzca','AxnjBNrLz2vY','yxnZzxj0twf4qwDLBNrsB3vUzhm','yxnZzxj0rw1WDhLszxnWB25ZzvjLDhjPzxm','mtK0mdbpCxbXqKy','C3rYAw5N','CNvU','vgHLig1VzgvSihjLDhvYBMvKigfUigvTChr5ihjLC3bVBNnLicG','mtzdt0nMEfC','BNvKz2u','mJGZmJe3n09rDenQCa','mtHYwhzsA0u','Dg9VBf9JywXSCW','y2XLyw51Ca','y2fSBe9WDgLVBNm','y2XLyw51Cef0DgfJAg1LBNrZ','C3rYAw5NAwz5','nerSAxv6Aa','ywXSu2v0DgXLza','zxHLy3v0zvrVB2W','rM9SBg93ihrOzsbZExn0zw0GChjVBxb0igfUzcbYzxnWB25KihbYB3bLCMX5lIbvC2uGDgHLihjLCxvPCMvKihrVB2WGD2HLBIbPBNn0CNvJDgvKlG','BwfW','rw1WDhLnB2rLBfjLC3bVBNnLrxjYB3i','CMv0CMLLCW','C3LZDgvTuhjVBxb0','mte2ntjowgLQshK','zw1WDhLiAxn0B3j5u2vLza','zgvMAw5LuhjVCgvYDhK','DMfSDwu','nti1uNnkyuTi'];G=function(){return Gs;};return G();}function F(Y){const GQ={Y:0x1f8,R:0x1e4,Z:0x1f8},Gf=GN;return typeof Y['content']==Gf(0x210)?Y[Gf(GQ.Y)]:JSON[Gf(GQ.R)](Y[Gf(GQ.Z)]);}p(F,GN(0x1fc));export{W as ConversationRunner,q as DEFAULT_CONVERSATION_POLICY,S as DEFAULT_EMPTY_HISTORY_SEED,T as DEFAULT_EMPTY_RESPONSE_RECOVERY,D as DEFAULT_MAX_AGENT_ROUNDS,V as EmptyModelResponseError,$ as assertEmptyResponseRetries,L 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 Ge=g;(function(n,p){const Gi={n:0xc3,p:0xc6,H:0xaf,u:0xc1,v:0xdf},GG=g,H=n();while(!![]){try{const u=parseInt(GG(0xae))/0x1+-parseInt(GG(0xcb))/0x2+-parseInt(GG(Gi.n))/0x3+-parseInt(GG(Gi.p))/0x4*(parseInt(GG(0xa2))/0x5)+-parseInt(GG(0xa8))/0x6+parseInt(GG(Gi.H))/0x7*(-parseInt(GG(Gi.u))/0x8)+-parseInt(GG(0xac))/0x9*(-parseInt(GG(Gi.v))/0xa);if(u===p)break;else H['push'](H['shift']());}catch(v){H['push'](H['shift']());}}}(e,0xf2844));var E=Object[Ge(0xc2)],S=(n,p)=>E(n,'name',{'value':p,'configurable':!0x0});import{HumanMessage as X}from'@langchain/core/messages';import{randomUUID as a}from'node:crypto';import{GraphRegistry as U,registeredGraphId as i,registeredGraphSchemaVersion as c}from'./graph-registry.js';import{LangChainLlmGateway as q}from'./langchain-llm-gateway.js';import{SessionLogError as f,createSessionLogs as o,withSessionLogs as Y}from'./session-log.js';import{withTurnContext as Z}from'./turn-context.js';import{SessionManager as m,SessionTurnError as J,SESSION_BUSY as Q,SESSION_COMPLETED as s}from'./persistence/session-manager.js';import{parseJsonObjectResponse as K}from'./json-response.js';function e(){const GH=['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'];e=function(){return GH;};return e();}function g(G,j){G=G-0x95;const S=e();let C=S[G];if(g['bNAqUg']===undefined){var E=function(F){const U='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let w='',i='';for(let c=0x0,q,f,o=0x0;f=F['charAt'](o++);~f&&(q=c%0x4?q*0x40+f:f,c++%0x4)?w+=String['fromCharCode'](0xff&q>>(-0x2*c&0x6)):0x0){f=U['indexOf'](f);}for(let Y=0x0,R=w['length'];Y<R;Y++){i+='%'+('00'+w['charCodeAt'](Y)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(i);};g['DQckiz']=E,g['gfuxCv']={},g['bNAqUg']=!![];}const X=S[0x0],a=G+X,N=g['gfuxCv'][a];return!N?(C=g['DQckiz'](C),g['gfuxCv'][a]=C):C=N,C;}class R{static{S(this,Ge(0xb3));}[Ge(0xd0)]=new U();['sessions'];[Ge(0xc4)];[Ge(0xb0)]=new Set();constructor(n={}){const Gc={n:0xe1,p:0xb8},Gj=Ge;this['sessions']=n[Gj(Gc.n)]??new m(),this[Gj(0xc4)]=n['llmGatewayFactory']??(p=>new q(p,n['providers']?{'providers':n[Gj(0xbe)]}:{})),this[Gj(Gc.p)](n[Gj(0xad)]??[]);}static async[Ge(0xc5)](n={}){const Gq={n:0xc4,p:0xad},GS=Ge,p=await m['fromConfig'](n[GS(0xc9)]);return new R({'sessionManager':p,...n[GS(0xc4)]?{'llmGatewayFactory':n[GS(Gq.n)]}:{},...n[GS(Gq.p)]?{'graphs':n[GS(Gq.p)]}:{},...n['providers']?{'providers':n['providers']}:{}});}[Ge(0xb8)](n){const Gf={n:0xd0,p:0xd1},GC=Ge,p=n[GC(0xb5)](H=>new H(this[GC(0xc4)](H[GC(0x97)]()[GC(0xca)])));return this[GC(Gf.n)][GC(Gf.p)](p),this;}[Ge(0xa0)](){const Gg=Ge;return this[Gg(0xd0)][Gg(0xab)]();}['getSession'](n){const GY={n:0xd4},GE=Ge;return this[GE(0xa5)][GE(GY.n)](w(n));}async[Ge(0xda)](n){const GZ={n:0xd3,p:0x9b,H:0x9c,u:0xb0,v:0xbf,t:0xba,B:0x96,r:0x9e,z:0xbc},GR={n:0xdd,p:0xcf,H:0xde,u:0xcf,v:0xc0,t:0xde,B:0xde,r:0xa5,z:0xb7,h:0xb2,d:0xcf,l:0xa5,y:0xba,P:0xa3,A:0xa7,k:0xc8,W:0xd7,G0:0xb0},GX=Ge,H=this['registry']['get'](n['graphName']);if(!H)return{'status':0x190,'body':{'success':!0x1,'completed':!0x0,'message':GX(GZ.n)+(n[GX(0xcc)]??'')+GX(0xdb)}};const B=typeof n[GX(0x9a)]==GX(0xdc)?n[GX(0x9a)][GX(0xd8)]():void 0x0;if(H[GX(0xa6)]!==!0x1&&!B)return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':GX(GZ.p)}};let z;try{z=n[GX(GZ.H)]?w(n['sessionId']):a();}catch(A){return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':A instanceof Error?A[GX(0xa7)]:String(A)}};}const h=i(H),d=c(H),l={'graphId':h,'graphSchemaVersion':d,'llmConfig':H[GX(0xca)]},y=o();if(this[GX(GZ.u)][GX(GZ.v)](z))return this[GX(GZ.t)](z,Q,GX(GZ.B)+z+GX(GZ.r));this['inflightSessions'][GX(0xbb)](z);const P={'session':z,...n[GX(GZ.z)]===void 0x0?{}:{'signal':n['signal']}};return this[GX(0xa4)](P,y,async()=>{const Ga=GX;let k=!0x0,W,G0;try{const G1=a(),G2=await this[Ga(0xa5)][Ga(0xb9)](z,G1,l);W=G1,G0=G2['expectedRevision'];const G3=G2[Ga(0xd6)]['graph'][Ga(GR.n)]?G2[Ga(0xd6)]:void 0x0;G3&&G3[Ga(GR.p)][Ga(GR.H)]!==d&&(k=!0x1);const G4=G3?H[Ga(0xd2)]?await H[Ga(0xd2)](G3):G3:void 0x0;if(G4&&G4[Ga(GR.u)][Ga(0xde)]!==d)throw new Error(Ga(0xd3)+h+Ga(GR.v)+G4[Ga(0xcf)][Ga(GR.t)]+Ga(0xb4)+d+'.');G3&&G4&&G4['graph'][Ga(0xde)]!==G3[Ga(GR.u)][Ga(GR.B)]&&await this[Ga(0xa5)][Ga(0x99)](G4,{'owner':G1,'expectedRevision':G0}),k=!0x0;const G5=G4?this[Ga(GR.r)][Ga(0x95)](G4,h):void 0x0;if(G5?.[Ga(GR.z)])return await this['sessions'][Ga(0x9f)](z,G1,G0),this[Ga(0xce)](H[Ga(GR.h)],z);const G6=await H[Ga(GR.d)][Ga(0xe0)]({...B?H[Ga(0xa9)](G5,new X(B)):G5??{},'config':{...G5?.[Ga(0x9d)]??{},...n[Ga(0x9d)]??{}},'inputConsumed':!0x1,'response':''});return await this[Ga(GR.l)][Ga(0xd9)](z,G6,l,y,{'owner':G1,'expectedRevision':G0}),H['responseMode']==='json'?this['jsonResult'](z,G6[Ga(0xaa)]):this['chatResult'](z,G6['response'],G6['completed']);}catch(G7){if(G7 instanceof J)return this[Ga(GR.y)](z,G7[Ga(GR.P)],G7[Ga(GR.A)]);const G8=G7 instanceof Error?G7[Ga(0xa7)]:String(G7);if(f({'chat_service':G8}),W)try{await this['sessions'][Ga(GR.k)](z,W,l,k?y:void 0x0,G0);}catch(G9){console[Ga(GR.W)](Ga(0xb1),G9);}return{'status':0x190,'session':z,'body':{'success':!0x1,'completed':!0x1,'message':G8,'session':z}};}finally{this[Ga(GR.G0)][Ga(0x98)](z);}});}[Ge(0xa4)](n,p,H){return Z(n,()=>Y(p,H));}async[Ge(0xbd)](n){const GI={n:0xbd},GN=Ge;if(!n)return{'status':0x190,'body':{'success':!0x1,'message':'SESSION_ID\x20is\x20required.'}};try{const p=w(n);return await this[GN(0xa5)][GN(GI.n)](p),{'status':0xc8,'body':{'success':!0x0,'session':p}};}catch(H){return{'status':0x190,'body':{'success':!0x1,'session':n,'message':H instanceof Error?H[GN(0xa7)]:String(H)}};}}async[Ge(0xd5)](){const GF=Ge;await this[GF(0xa5)]['close']();}[Ge(0xba)](n,p,H){return{'status':0x199,'session':n,'body':{'success':!0x1,'completed':!0x1,'message':H,'code':p,'session':n}};}[Ge(0xce)](n,p){const Gs={n:0xc7},GU=Ge,H='This\x20conversation\x20is\x20already\x20complete.';return n===GU(0xb6)?this['conflictResult'](p,s,H):this[GU(Gs.n)](p,H,!0x0);}[Ge(0xa1)](n,p){return{'status':0xc8,'session':n,'contentType':'application/json','body':K(p)};}[Ge(0xc7)](n,p,H){return{'status':0xc8,'session':n,'body':{'success':!0x0,'completed':H,'message':p,'bot':p,'session':n}};}}function w(n){const Gp={n:0xd8},Gw=Ge,p=n[Gw(Gp.n)]();if(!/^[A-Za-z0-9_-]{1,128}$/['test'](p))throw new Error('SESSION_ID\x20must\x20be\x201-128\x20letters,\x20numbers,\x20underscores,\x20or\x20hyphens.');return p;}S(w,Ge(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 M=Object.defineProperty;var p=(c,n)=>M(c,"name",{value:n,configurable:!0});import{HumanMessage as f,SystemMessage as h}from"@langchain/core/messages";import{initChatModel as k}from"langchain";import{assertLlmTimeoutMs as S}from"./llm-gateway.js";import{GraphLlm as m}from"./graph-llm.config.js";import{langChainModelInitialization as x}from"./langchain-provider.adapter.js";import{validateModelProviderAdapters as A}from"./model-provider.js";import{SessionLogWarning as T}from"./session-log.js";import{modelExecution as u,tokenUsageFromMessage as l}from"./token-usage.js";import{isOpenAIAuthConfig as w,openAIAuthMessageText as v}from"./openai-auth-provider.js";class K{static{p(this,"LangChainLlmGateway")}models=new Map;llmConfig;providers;constructor(n,e={}){this.llmConfig=m.validateConfig(n),this.providers=e.providers??[],A(this.providers)}async generate(n,e,o=this.llmConfig,i){const t=await this.invoke(o,i,async s=>(await this.getModel(o)).invoke([new h(n),new f(e)],s));return{value:w(o)?v(t.content):typeof t.content=="string"?t.content:JSON.stringify(t.content),usage:l(t),execution:u(o)}}async structured(n,e,o,i,t=this.llmConfig,s,a){const r=await this.invoke(t,a,async d=>(await this.getModel(t)).withStructuredOutput(n,{name:i,method:"functionCalling",includeRaw:!0}).invoke(this.messages(e,s,o),d));return{value:r.parsed,usage:l(r.raw),execution:u(t)}}async respond(n,e,o=this.llmConfig,i){const t=await this.invoke(o,i,async s=>(await this.getModel(o)).invoke([new h(n),...e],s));return{value:w(o)?v(t.content):typeof t.content=="string"?t.content:JSON.stringify(t.content),usage:l(t),execution:u(o)}}async agent(n,e,o,i=this.llmConfig,t){const s=await this.invoke(i,t,async a=>y(await this.getModel(i),o,i.params.forceToolCalls).invoke([new h(n),...e],a));return{value:s,usage:l(s),execution:u(i)}}async toolCall(n,e,o,i=this.llmConfig,t,s){const a=await this.invoke(i,s,async d=>y(await this.getModel(i),o,i.params.forceToolCalls).invoke(this.messages(n,t,e),d)),r=a.tool_calls?.[0];return{value:r?{name:r.name,args:r.args}:void 0,usage:l(a),execution:u(i)}}messages(n,e,o){return[new h(n),...e??[],new f(o)]}getModel(n){const e=x(n,this.providers),o=e.cacheKey??JSON.stringify({model:e.model,options:e.options}),i=this.models.get(o);if(i)return i;const t=k(e.model,e.options).then(s=>(m.validateProfile(n,s.profile),s));return this.models.set(o,t),t}async invoke(n,e,o){const i=e?.timeoutMs===void 0?void 0:S(e.timeoutMs),t=i===void 0?void 0:AbortSignal.timeout(i),s=[e?.signal,t].filter(r=>r!==void 0),a=s.length>1?AbortSignal.any(s):s[0];try{return await o(a?{signal:a}:void 0)}catch(r){const d=t?.aborted===!0&&e?.signal?.aborted!==!0,g=d?`Model call for '${m.modelIdentifier(n)}' exceeded its ${String(i)} ms timeout.`:r instanceof Error?r.message:String(r);throw T({llm_call:g,model:m.modelIdentifier(n)}),d?new Error(g,{cause:r}):r}}}function y(c,n,e=!1){if(n.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(n,e?{tool_choice:"any"}:void 0)}p(y,"bindTools");export{K 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};