@picoflow/ezgraph 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,6 +42,7 @@ returns exactly one response:
42
42
  | ------------------------------- | -------------------------------------------------------------------------------------- |
43
43
  | `stay(feedback)` | Validation failed; continue collecting in the current node. |
44
44
  | `go(TargetNode)` | Enter another registered conversational node now. |
45
+ | `go(Child1Node, Child2Node)` | Schedule multiple registered nodes concurrently; use an explicit join to continue. |
45
46
  | `direct(content)` | Return exact code-owned content, such as a policy decision, price table, or ticket ID. |
46
47
  | `directTo(TargetNode, content)` | Return exact content and make the target the next user-turn node. |
47
48
  | `finish(content)` | Return exact final content and complete the conversation. |
@@ -166,13 +167,78 @@ For deterministic policy that needs state owned by another node, read
166
167
  `this.graph.graphState()`. To write another node's channel, use
167
168
  `this.graph.saveNodeState(TargetNode, patch)`.
168
169
 
170
+ ## Run internal LLM tasks
171
+
172
+ Use the same `LlmNode` for conversation, sequential internal generation,
173
+ nested calls, and parallel workers. Its prompt, tools, configuration, and
174
+ response/error hooks always run through `LlmRunner`, including node-first graph
175
+ fallback, temporary alternate models, cancellation, timeout, and usage accounting.
176
+ Execution ownership belongs to the graph or caller, not to a different superclass.
177
+
178
+ ```ts
179
+ import { LlmNode } from "@picoflow/ezgraph";
180
+
181
+ class JokeNode extends LlmNode<MyGraphState, { joke?: string }> {
182
+ getPrompt() {
183
+ return "You are a concise comedian. Tell one short joke about parallel execution.";
184
+ }
185
+
186
+ protected onResponse(response: string) {
187
+ this.saveState({ joke: response });
188
+ }
189
+ }
190
+ ```
191
+
192
+ Instructions and input data belong in `getPrompt(state)`. The optional
193
+ `onResponse(output, state)` receives accepted model text or the unwrapped value
194
+ from `taskResult(value)`, including successful model recovery. It is not called
195
+ for intermediate tool feedback or routing outcomes such as `go()`/`finish()`.
196
+ Return nothing to keep the original output, return text to replace it, or return
197
+ a response/routing helper. Validate domain output before saving it. A hook error
198
+ is an application error, not a provider failure to retry.
199
+
200
+ `graph.registerTurns(...)` (or `registerTurnNodes(...)`) designates the nodes that
201
+ own user-facing conversation. Other registered nodes in that graph execute as
202
+ internal work, whether sequential or parallel. In fixed-entry graphs without a
203
+ turn registry, existing nodes retain conversational behavior; use
204
+ `graph.workers(JokeNode, OtherWorker)` to register internal placements explicitly.
205
+ Connect internal successors with `graph.addEdge(...)`; scheduling does not change
206
+ the node's contract.
207
+
208
+ Internal LLM history is ephemeral and initially empty. The runner applies
209
+ `emptyHistorySeed` (default `"Start"`, or `null` for system-only calls). It neither
210
+ reads nor appends conversation history and does not offer `terminate_session`.
211
+ Internal execution publishes only its own node entry and usage; runtime writes
212
+ to another node, shared context, or persisted history are rejected. Parallel
213
+ workers publish independent node entries, and a join owns shared decisions.
214
+
215
+ Tools use `stay(feedback)` to continue, `direct(content)` for final code-owned
216
+ content, or `taskResult(value)` for typed output in either execution mode. A
217
+ third type parameter declares that output:
218
+ `LlmNode<MyGraphState, { title?: string }, { title: string }>`; its `onResponse`
219
+ receives `string | { title: string }`. Conversational structured output is JSON
220
+ unless the hook renders it as text. Internal execution rejects `go`, `directTo`,
221
+ `finish`, and response builders containing conversation effects, including from
222
+ tools or graph-wide recovery. It never silently drops a conversation transition.
223
+
224
+ A nested `child.invoke(state)` automatically runs as internal work, with tools
225
+ registered in the runtime. The parent explicitly combines/publishes the child's
226
+ update (including usage) and owns continuation. A standalone caller can request
227
+ internal execution with `node.invoke(state, { mode: "internal" })`; a nested call
228
+ cannot escalate to conversation ownership. Calling `run(state)` directly bypasses
229
+ invocation ownership and is not a supported managed execution entry point.
230
+
231
+ Direct `llmGateway` calls remain available to custom `GraphNode` implementations,
232
+ but they do not automatically exercise the managed LLM lifecycle.
233
+
169
234
  ## Handle model failures
170
235
 
171
- `LlmNode` supports the same response/error hooks as PicoFlow. The
236
+ `LlmNode` supports response/error hooks in every execution mode. The
172
237
  three error hooks also exist on `BaseGraph` as graph-wide fallback policy:
173
238
 
174
239
  | Hook | Behavior |
175
240
  | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
241
+ | `onResponse(output, state)` | Consumes accepted text or a typed tool result in any execution mode. Save local state; return nothing to preserve output, text to render it, or an allowed response/routing helper. |
176
242
  | `checkResponse(candidate)` | Receives the raw AI message before tool dispatch or acceptance. `true` rejects and retries; `false` accepts. Node-only. |
177
243
  | `onLlmBlocked(context)` | Handles prompt blocks and blocked candidates, including candidates with text or tools. Node first, then graph on `null`; two `null` results propagate `LlmResponseBlockedError`. |
178
244
  | `shouldRetryLlmError(context)` | Controls retries for thrown invocation errors. Node first, then graph on `undefined`, then the configured retry budget. `false` stops immediately. |
@@ -224,6 +290,31 @@ alternate in the same recovery sequence is rejected. Completed tool effects
224
290
  and their feedback remain in place; newly generated tool calls still execute
225
291
  normally, so applications should keep side effects idempotent.
226
292
 
293
+ ```ts
294
+ import {
295
+ LlmNode, ModelCatalog, retryWithModel,
296
+ type GraphState, type LlmErrorContext,
297
+ } from "@picoflow/ezgraph";
298
+
299
+ class AlternateSupportNode extends LlmNode<GraphState> {
300
+ getPrompt(): string { return "Help the customer with their request."; }
301
+
302
+ override async onLlmError(context: LlmErrorContext) {
303
+ if (context.model === "openai:gpt-4o-mini") {
304
+ return retryWithModel(
305
+ ModelCatalog.model("openai:gpt-4.1", { retries: 0, temperature: 0.2 }),
306
+ );
307
+ }
308
+ return "The service is unavailable. Please try again.";
309
+ }
310
+ }
311
+ ```
312
+
313
+ `retryWithModel()` validates the selected model and parameters immediately.
314
+ The runner also validates manually constructed recovery results before calling
315
+ the gateway. Cancellation and the graph's per-call timeout apply to the alternate;
316
+ provider blocks continue through `onLlmBlocked()`.
317
+
227
318
  For conversational nodes, `params.retries` remains an **additional** retry
228
319
  count: `2` allows three attempts for invocation errors or rejected candidates.
229
320
  The runner supplies `retries: 0` to each gateway call to prevent nested SDK
@@ -237,6 +328,11 @@ and direct gateway calls retain their existing behavior, including
237
328
  `GraphNode.onEmptyModelResponse()`. Typed `DecisionNode` validation and
238
329
  `onDecisionError()` remain separate.
239
330
 
331
+ The shared model/tool loop is exported as `LlmRunner`. Its result is
332
+ `LlmRunResult`; `LlmPolicy` and `DEFAULT_LLM_POLICY` describe the call policy.
333
+ Custom `GraphNode` subclasses can use `runLlm()`, and `LlmNode` connects its
334
+ response/error hooks through `llmLifecycle()`.
335
+
240
336
  ## Add typed decisions with Jev
241
337
 
242
338
  EZGraph supports [Jev](https://typesafe.ai/) through LangChain's optional
@@ -315,6 +411,32 @@ ordinary conversational handoffs; fixed worker edges remain ordinary LangGraph
315
411
  edges. Register `TerminateSessionNode` and connect it to `END` when a graph
316
412
  contains conversational nodes.
317
413
 
414
+ For conditional fan-out, return `go(Child1Node, Child2Node)` from the successful
415
+ tool handler, `onResponse()`, or deterministic `GraphNode.run()`. Save parent-owned
416
+ data before returning. A multi-target builder has no `withState()` or
417
+ `withMessage()` because there is no single destination for those effects;
418
+ `withUsage()`, tool feedback, tool cleanup, and current-history messages still work.
419
+ Single-target `go(TargetNode).withState(...)` remains unchanged.
420
+
421
+ Register the children as internal work (leave them out of `registerTurns()`, or
422
+ use `workers()` in a fixed-entry graph), and declare a barrier for the next stage:
423
+
424
+ ```ts
425
+ // In the parent, only after accepting and saving the input:
426
+ return go(Child1Node, Child2Node);
427
+
428
+ // In buildGraph(), after registering all nodes:
429
+ graph.addEdge([Child1Node, Child2Node], NextConversationNode);
430
+ ```
431
+
432
+ Both children use the same `LlmNode` contract, save only their own local state,
433
+ and publish their own usage. The multi-target transition consumes the current
434
+ input but leaves `currentNode` with its existing conversation owner. The join
435
+ waits for both children; a conversational node there becomes the next turn owner.
436
+ Do not attach unconditional child edges to a conversational parent when work
437
+ should run only on acceptance: those edges also run on ordinary replies or
438
+ termination, independently of `go()`.
439
+
318
440
  ```ts
319
441
  import "reflect-metadata";
320
442
  import { END } from "@langchain/langgraph";
@@ -1 +1 @@
1
- var d=Object.defineProperty;var i=(o,e)=>d(o,"name",{value:e,configurable:!0});import{GraphLlm as p}from"./graph-llm.config.js";import{GraphNodeRuntime as u}from"./graph-node.js";import{StateGraphExt as l}from"./state-graph-ext.js";import{assertEmptyResponseRetries as g,assertMaxAgentRounds as f,DEFAULT_CONVERSATION_POLICY as h,DEFAULT_MAX_AGENT_ROUNDS as y}from"./conversation-runner.js";import{assertLlmTimeoutMs as w}from"./llm-gateway.js";import{assertGraphSchemaVersion as m,assertStableId as v,stableClassId as a}from"./stable-id.js";class c{static{i(this,"BaseGraph")}llmGateway;static id(){return this.name}static assertName(e){return c.assertId(e)}static assertId(e){return v(e,"graph")}name;id;schemaVersion;llmConfig;requiresUserMessage;responseMode;maxAgentRounds;conversationPolicy;compiledGraph;runtime;nodeMap=new Map;endNode;migrations;constructor(e,r){this.llmGateway=e;const t=new.target;this.name=t.name,this.id=a(t,"graph"),this.schemaVersion=m(r.schemaVersion??1),this.migrations=N(r.migrations,this.schemaVersion),this.llmConfig=p.resolveConfig(r.llmConfig),this.requiresUserMessage=r.requiresUserMessage??!0,this.responseMode=r.responseMode??"chat",this.maxAgentRounds=f(r.maxAgentRounds??y),this.conversationPolicy=E(r),this.endNode=r.endNode,this.runtime=new u(r.endNode,this.llmConfig,R(r.historySpaces),this.responseMode,this.maxAgentRounds,this.conversationPolicy,r.decisionConfig,s=>this.onDecisionError(s),{onLlmBlocked:i(s=>this.onLlmBlocked(s),"onLlmBlocked"),shouldRetryLlmError:i(s=>this.shouldRetryLlmError(s),"shouldRetryLlmError"),onLlmError:i(s=>this.onLlmError(s),"onLlmError")},()=>{if(!this.graph.channels?.context)throw new Error(`Graph '${this.id}' must declare a context channel to save context. Use createGraphStateAnnotation().`)})}async onLlmBlocked(e){return null}shouldRetryLlmError(e){}async onLlmError(e){return null}onDecisionError(e){return null}attachDecisionProviderResolver(e){this.runtime.attachDecisionProviderResolver(e)}get graph(){return this.compiledGraph??=this.buildGraph()}prepareInput(e,r){const t=e?.currentNode??this.initialNodeId(),s=this.runtime.historySpace(t);return{...e??{},currentNode:t,histories:{...e?.histories??{},[s]:[...e?.histories[s]??[],r]}}}initialNodeId(){const e=this.graph.channels?.currentNode;if(!e||typeof e.fromCheckpoint!="function")throw new Error(`Graph '${this.id}' must declare a currentNode default before preparing its first message.`);let r;try{r=e.fromCheckpoint().get()}catch(t){throw new Error(`Graph '${this.id}' must declare a currentNode default before preparing its first message.`,{cause:t})}if(typeof r!="string"||!r.trim())throw new Error(`Graph '${this.id}' must declare a non-empty currentNode default.`);return r}getContext(){return this.runtime.getContext()}saveContext(e){this.runtime.saveContext(e)}saveNodeState(e,r){this.runtime.saveNode(a(e,"graph node"),r)}async restoreSessionDoc(e){if(e.graph.id!==this.id)throw new Error(`Session '${e.id}' belongs to graph '${e.graph.id}', not '${this.id}'. Start a new session to run a different graph.`);if(e.graph.schemaVersion>this.schemaVersion)throw new Error(`Session '${e.id}' uses graph '${this.id}' schema version ${e.graph.schemaVersion}, but this runtime supports version ${this.schemaVersion}.`);let r=e;for(;r.graph.schemaVersion<this.schemaVersion;){const t=r.graph.schemaVersion,s=this.migrations.get(t);if(!s)throw new Error(`Graph '${this.id}' has no migration from schema version ${t} to ${t+1}.`);const n=await s.migrate(r);if(n.graph.id!==this.id)throw new Error(`Graph '${this.id}' migration from schema version ${t} changed the persisted graph ID.`);r={...n,graph:{...n.graph,schemaVersion:t+1}}}return await this.onRestoreSessionDoc(r)}async onRestoreSessionDoc(e){return e}idleMs(e){const r=Date.parse(e.modifiedAt);return Number.isFinite(r)?Date.now()-r:0}createStateGraph(e){return new l(e,(r=>this.createNode(r)),this.endNode)}createNode(e){const r=new e(this.llmGateway,this.runtime),t=a(e,"graph node");if(r.id!==t)throw new Error(`Graph node factory for '${t}' constructs '${r.id}'.`);if(this.nodeMap.has(r.id))throw new Error(`Graph node '${r.id}' is already registered.`);return this.nodeMap.set(r.id,r),this.runtime.registerTools(r.id,r.defineTool()),Object.freeze(r),r}}function E(o){const e=o.emptyResponseRecovery===void 0?h.emptyResponseRecovery:o.emptyResponseRecovery;return e&&g(e.retries),{...o.llmTimeoutMs===void 0?{}:{llmTimeoutMs:w(o.llmTimeoutMs)},emptyHistorySeed:o.emptyHistorySeed===void 0?h.emptyHistorySeed:o.emptyHistorySeed,emptyResponseRecovery:e}}i(E,"resolveConversationPolicy");function R(o){return Object.fromEntries((o??[]).map(([e,r])=>[a(e,"graph node"),r]))}i(R,"historySpaceMap");function N(o,e){const r=new Map;let t;for(const s of o??[]){const n=m(s.from);if(n>=e)throw new Error(`A graph migration from version ${n} cannot target schema version ${e}.`);if(r.has(n))throw new Error(`More than one graph migration starts at version ${n}.`);if(t!==void 0&&n!==t+1)throw new Error(`Graph migrations must be ordered and contiguous; version ${t} must be followed by ${t+1}.`);r.set(n,s),t=n}return r}i(N,"migrationMap");export{c as BaseGraph};
1
+ var d=Object.defineProperty;var i=(o,e)=>d(o,"name",{value:e,configurable:!0});import{GraphLlm as p}from"./graph-llm.config.js";import{GraphNodeRuntime as l}from"./graph-node.js";import{StateGraphExt as u}from"./state-graph-ext.js";import{assertEmptyResponseRetries as g,assertMaxAgentRounds as f,DEFAULT_LLM_POLICY as h,DEFAULT_MAX_AGENT_ROUNDS as y}from"./llm-runner.js";import{assertLlmTimeoutMs as w}from"./llm-gateway.js";import{assertGraphSchemaVersion as m,assertStableId as E,stableClassId as a}from"./stable-id.js";class c{static{i(this,"BaseGraph")}llmGateway;static id(){return this.name}static assertName(e){return c.assertId(e)}static assertId(e){return E(e,"graph")}name;id;schemaVersion;llmConfig;requiresUserMessage;responseMode;maxAgentRounds;llmPolicy;compiledGraph;runtime;nodeMap=new Map;endNode;migrations;constructor(e,r){this.llmGateway=e;const t=new.target;this.name=t.name,this.id=a(t,"graph"),this.schemaVersion=m(r.schemaVersion??1),this.migrations=$(r.migrations,this.schemaVersion),this.llmConfig=p.resolveConfig(r.llmConfig),this.requiresUserMessage=r.requiresUserMessage??!0,this.responseMode=r.responseMode??"chat",this.maxAgentRounds=f(r.maxAgentRounds??y),this.llmPolicy=v(r),this.endNode=r.endNode,this.runtime=new l(r.endNode,this.llmConfig,R(r.historySpaces),this.responseMode,this.maxAgentRounds,this.llmPolicy,r.decisionConfig,s=>this.onDecisionError(s),{onLlmBlocked:i(s=>this.onLlmBlocked(s),"onLlmBlocked"),shouldRetryLlmError:i(s=>this.shouldRetryLlmError(s),"shouldRetryLlmError"),onLlmError:i(s=>this.onLlmError(s),"onLlmError")},()=>{if(!this.graph.channels?.context)throw new Error(`Graph '${this.id}' must declare a context channel to save context. Use createGraphStateAnnotation().`)})}async onLlmBlocked(e){return null}shouldRetryLlmError(e){}async onLlmError(e){return null}onDecisionError(e){return null}attachDecisionProviderResolver(e){this.runtime.attachDecisionProviderResolver(e)}get graph(){return this.compiledGraph??=this.buildGraph()}prepareInput(e,r){const t=e?.currentNode??this.initialNodeId(),s=this.runtime.historySpace(t);return{...e??{},currentNode:t,histories:{...e?.histories??{},[s]:[...e?.histories[s]??[],r]}}}initialNodeId(){const e=this.graph.channels?.currentNode;if(!e||typeof e.fromCheckpoint!="function")throw new Error(`Graph '${this.id}' must declare a currentNode default before preparing its first message.`);let r;try{r=e.fromCheckpoint().get()}catch(t){throw new Error(`Graph '${this.id}' must declare a currentNode default before preparing its first message.`,{cause:t})}if(typeof r!="string"||!r.trim())throw new Error(`Graph '${this.id}' must declare a non-empty currentNode default.`);return r}getContext(){return this.runtime.getContext()}saveContext(e){this.runtime.saveContext(e)}saveNodeState(e,r){this.runtime.saveNode(a(e,"graph node"),r)}async restoreSessionDoc(e){if(e.graph.id!==this.id)throw new Error(`Session '${e.id}' belongs to graph '${e.graph.id}', not '${this.id}'. Start a new session to run a different graph.`);if(e.graph.schemaVersion>this.schemaVersion)throw new Error(`Session '${e.id}' uses graph '${this.id}' schema version ${e.graph.schemaVersion}, but this runtime supports version ${this.schemaVersion}.`);let r=e;for(;r.graph.schemaVersion<this.schemaVersion;){const t=r.graph.schemaVersion,s=this.migrations.get(t);if(!s)throw new Error(`Graph '${this.id}' has no migration from schema version ${t} to ${t+1}.`);const n=await s.migrate(r);if(n.graph.id!==this.id)throw new Error(`Graph '${this.id}' migration from schema version ${t} changed the persisted graph ID.`);r={...n,graph:{...n.graph,schemaVersion:t+1}}}return await this.onRestoreSessionDoc(r)}async onRestoreSessionDoc(e){return e}idleMs(e){const r=Date.parse(e.modifiedAt);return Number.isFinite(r)?Date.now()-r:0}createStateGraph(e){return new u(e,(r=>this.createNode(r)),this.endNode)}createNode(e){const r=new e(this.llmGateway,this.runtime),t=a(e,"graph node");if(r.id!==t)throw new Error(`Graph node factory for '${t}' constructs '${r.id}'.`);if(this.nodeMap.has(r.id))throw new Error(`Graph node '${r.id}' is already registered.`);return this.nodeMap.set(r.id,r),this.runtime.registerTools(r.id,r.defineTool()),Object.freeze(r),r}}function v(o){const e=o.emptyResponseRecovery===void 0?h.emptyResponseRecovery:o.emptyResponseRecovery;return e&&g(e.retries),{...o.llmTimeoutMs===void 0?{}:{llmTimeoutMs:w(o.llmTimeoutMs)},emptyHistorySeed:o.emptyHistorySeed===void 0?h.emptyHistorySeed:o.emptyHistorySeed,emptyResponseRecovery:e}}i(v,"resolveLlmPolicy");function R(o){return Object.fromEntries((o??[]).map(([e,r])=>[a(e,"graph node"),r]))}i(R,"historySpaceMap");function $(o,e){const r=new Map;let t;for(const s of o??[]){const n=m(s.from);if(n>=e)throw new Error(`A graph migration from version ${n} cannot target schema version ${e}.`);if(r.has(n))throw new Error(`More than one graph migration starts at version ${n}.`);if(t!==void 0&&n!==t+1)throw new Error(`Graph migrations must be ordered and contiguous; version ${t} must be followed by ${t+1}.`);r.set(n,s),t=n}return r}i($,"migrationMap");export{c as BaseGraph};
@@ -1 +1 @@
1
- var D=Object.defineProperty;var r=(a,o)=>D(a,"name",{value:o,configurable:!0});import{GraphNode as m}from"../graph-node.js";import{currentTurnSignal as v}from"../turn-context.js";import{DecisionRunner as C}from"./decision-runner.js";import{assertJsonCompatible as w,validateDecisionQuestions as g}from"./decision-validation.js";class y extends m{static{r(this,"DecisionNode")}getPrompt(o){return""}getDecisionFacts(o){return{}}getDecisionConfig(){return{}}onDecisionError(o){return null}async run(o){this.assertNoChatConfiguration();const s=v();s?.throwIfAborted();const h=this.graph.resolveDecisionOptions(this.getDecisionConfig()),f=this.graph.resolveDecisionProvider(h.provider),l=structuredClone(this.defineQuestions(o));g(l);const u=this.getPrompt(o).trim(),p=Object.fromEntries(Object.entries(l).map(([e,t])=>[e,{...t,...u?{instructions:[u,...t.instructions===void 0?[]:[t.instructions]]}:{}}]));g(p);const n=this.graph.getConversation(this.historySpace()),c=structuredClone(this.getDecisionFacts(o));if("request"in c||"priorRequests"in c)throw new Error("getDecisionFacts() cannot replace framework-owned request or priorRequests.");const d={...c,request:n.request,priorRequests:[...n.priorRequests]};return w(d,"Decision input"),C.run({nodeId:this.id,state:o,conversation:n,providerState:d,questions:p,provider:f,options:h,callerSignal:s,onDecision:r(async(e,t,i)=>this.resolveNodeResponse(await this.onDecision(e,t,i)),"onDecision"),onError:r(async e=>{const i=await this.onDecisionError(e)??await this.graph.handleDecisionError(e);if(i===null)throw e.error;return this.resolveNodeResponse(i)},"onError")})}validateTools(){this.assertNoChatConfiguration();const o=this.graph.resolveDecisionOptions(this.getDecisionConfig());this.graph.resolveDecisionProvider(o.provider)}assertNoChatConfiguration(){const o=this.defineTool(),s=this.obtainTools();if(o.length>0||s.length>0)throw new Error("DecisionNode cannot configure chat tools.");if(Object.keys(this.getLlmConfig()).length>0)throw new Error("DecisionNode uses getDecisionConfig(), not a chat model configuration.")}usesChatModel(){return!1}async runConversation(o,s){throw new Error("DecisionNode does not run the conversational model loop.")}}export{y as DecisionNode};
1
+ var D=Object.defineProperty;var r=(a,o)=>D(a,"name",{value:o,configurable:!0});import{GraphNode as m}from"../graph-node.js";import{currentTurnSignal as v}from"../turn-context.js";import{DecisionRunner as C}from"./decision-runner.js";import{assertJsonCompatible as w,validateDecisionQuestions as g}from"./decision-validation.js";class y extends m{static{r(this,"DecisionNode")}getPrompt(o){return""}getDecisionFacts(o){return{}}getDecisionConfig(){return{}}onDecisionError(o){return null}async run(o){this.assertNoChatConfiguration();const s=v();s?.throwIfAborted();const h=this.graph.resolveDecisionOptions(this.getDecisionConfig()),f=this.graph.resolveDecisionProvider(h.provider),l=structuredClone(this.defineQuestions(o));g(l);const u=this.getPrompt(o).trim(),p=Object.fromEntries(Object.entries(l).map(([e,t])=>[e,{...t,...u?{instructions:[u,...t.instructions===void 0?[]:[t.instructions]]}:{}}]));g(p);const n=this.graph.getConversation(this.historySpace()),c=structuredClone(this.getDecisionFacts(o));if("request"in c||"priorRequests"in c)throw new Error("getDecisionFacts() cannot replace framework-owned request or priorRequests.");const d={...c,request:n.request,priorRequests:[...n.priorRequests]};return w(d,"Decision input"),C.run({nodeId:this.id,state:o,conversation:n,providerState:d,questions:p,provider:f,options:h,callerSignal:s,onDecision:r(async(e,t,i)=>this.resolveNodeResponse(await this.onDecision(e,t,i)),"onDecision"),onError:r(async e=>{const i=await this.onDecisionError(e)??await this.graph.handleDecisionError(e);if(i===null)throw e.error;return this.resolveNodeResponse(i)},"onError")})}validateTools(){this.assertNoChatConfiguration();const o=this.graph.resolveDecisionOptions(this.getDecisionConfig());this.graph.resolveDecisionProvider(o.provider)}assertNoChatConfiguration(){const o=this.defineTool(),s=this.obtainTools();if(o.length>0||s.length>0)throw new Error("DecisionNode cannot configure chat tools.");if(Object.keys(this.getLlmConfig()).length>0)throw new Error("DecisionNode uses getDecisionConfig(), not a chat model configuration.")}usesChatModel(){return!1}async runLlm(o,s){throw new Error("DecisionNode does not run the conversational model loop.")}}export{y as DecisionNode};
@@ -1 +1 @@
1
- const qB=G;(function(t,r){const qE={t:0xe0,r:0xdb,f:0xc1,i:0xb4},qv=G,f=t();while(!![]){try{const i=parseInt(qv(0xa0))/0x1+parseInt(qv(qE.t))/0x2+parseInt(qv(qE.r))/0x3+parseInt(qv(qE.f))/0x4+-parseInt(qv(0xce))/0x5+parseInt(qv(0xd6))/0x6+parseInt(qv(qE.i))/0x7*(-parseInt(qv(0xa3))/0x8);if(i===r)break;else f['push'](f['shift']());}catch(h){f['push'](f['shift']());}}}(d,0x8258d));var P=Object['defineProperty'],y=(t,r)=>P(t,qB(0xc5),{'value':r,'configurable':!0x0});import{HumanMessage as T}from'@langchain/core/messages';function d(){const qZ=['z2v0','jYbJB21WBgv0zwqGD2L0Ag91DcbWCM9KDwnPBMCGC3rHDguU','C2f2zvn0yxrL','zgvSzxrLu2vZC2LVBG','mtmZyKPmquzc','C2LNBMfS','yxbWBgLJyxrPB24VANnVBG','zg9JDw1LBNq','y2HHDfjLC3vSDa','CNvU','z3jHCgG','u0vtu0LptL9jrcbPCYbYzxf1AxjLzc4','ANnVBG','jYbYzxn0B3jLihjLDhvYBMvKihnJAgvTysb2zxjZAw9Uia','BwfW','CMvZDg9YzvnLC3nPB25eB2n1BwvUDa','z3jHCgHZ','mti2mZCWmhbWs2TtCq','y29UzMLN','C3rYAw5N','CMvZCg9UC2vnB2rL','BMfTzq','CMvSzwfZzvr1CM4','DxnLCK1LC3nHz2uGBxvZDcbIzsbHig5VBI1LBxb0EsbZDhjPBMCU','C2vZC2LVBK1HBMfNzxi','BM9Kzxm','y3jLyxrL','CMvZCg9UC2u','jYbPCYbUB3qGCMvNAxn0zxjLzc4','ChjLCgfYzuLUChv0','ntG5nda1y0DYtxje','zgvJAxnPB25qCM92AwrLCNm','yxr0ywnOrgvJAxnPB25qCM92AwrLCLjLC29SDMvY','DgvZDa','C2vZC2LVBKLK','C3rYzwfT','y29UzMXPy3rszxn1Bhq','ChjVDMLKzxjZ','mJK0odeYnhbwwMLgBq','Aw52B2TL','CMvXDwLYzxnvC2vYtwvZC2fNzq','zxHWzwn0zwrszxzPC2LVBG','y29Kzq','mtu3otGZmgfArvHPzG','ANnVBLjLC3vSDa','DxnLCK1LC3nHz2u','CMvNAxn0zxjhCMfWAa','zgvSzxrL','mtiWnJCYnfHLC1jRra','CMvNAxn0CNK','Aw5MBgLNAhrtzxnZAw9UCW','BgXTq29UzMLN','z3jHCgHoyw1L','z2v0u2vZC2LVBG','Aw5WDxrdB25ZDw1Lza','CMvZB2X2zq','D2L0Afr1CM5ty29Wzq','vw5HyMXLihrVihbLCNnPC3qGC2vZC2LVBIbLCNjVCIbSB2C6','oYbLEhbLy3rLzca','r3jHCgGGjW','zxjYB3i','z2v0r3jHCgHezwzPBML0Aw9U','C2vZC2LVBNm','odGXodyXqKPzvuvt','y29TCgXLDgvK','zNjVBunVBMzPzW','oteYntyWuwjHww5m','BgXTr2f0zxDHEuzHy3rVCNK','u2vZC2LVBIaN','jYbPCYbHBhjLywr5ihbYB2nLC3nPBMCGysb0DxjUlG','DMfSAwrHDgvtzxnZAw9Uswq','C2nOzw1HvMvYC2LVBG','CMvZDg9YzvnLC3nPB25eB2m','z2v0r3jHCgHZ','DhjPBq','yMvNAw5uDxjU','y2XVC2u','y29TCgXLDgvKu2vZC2LVBLjLC3vSDa','BwvZC2fNzq'];d=function(){return qZ;};return d();}function G(q,k){q=q-0x9d;const T=d();let y=T[q];if(G['pjzpNm']===undefined){var l=function(B){const w='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let K='',j='';for(let D=0x0,o,a,N=0x0;a=B['charAt'](N++);~a&&(o=D%0x4?o*0x40+a:a,D++%0x4)?K+=String['fromCharCode'](0xff&o>>(-0x2*D&0x6)):0x0){a=w['indexOf'](a);}for(let u=0x0,P=K['length'];u<P;u++){j+='%'+('00'+K['charCodeAt'](u)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(j);};G['bOrkSb']=l,G['wJSDQu']={},G['pjzpNm']=!![];}const e=T[0x0],X=q+e,v=G['wJSDQu'][X];return!v?(y=G['bOrkSb'](y),G['wJSDQu'][X]=y):y=v,y;}import{randomUUID as l}from'node:crypto';import{GraphRegistry as e,registeredGraphId as X,registeredGraphSchemaVersion as v}from'./graph-registry.js';import{LangChainLlmGateway as K}from'./langchain-llm-gateway.js';import{SessionLogError as D,createSessionLogs as o,drainSessionLogs as a,restoreSessionLogs as u,withSessionLogs as n}from'./session-log.js';import{withTurnContext as m}from'./turn-context.js';import{SessionManager as p,SessionTurnError as J,SESSION_BUSY as s,SESSION_COMPLETED as L}from'./persistence/session-manager.js';import{parseJsonObjectResponse as c}from'./json-response.js';import{DecisionProviderRegistry as g}from'./decision/decision-provider.js';class M{static{y(this,'GraphEngine');}[qB(0xe1)]=new e();[qB(0x9f)];[qB(0xa4)];['decisionProviders'];[qB(0xe2)]=new Set();constructor(t={}){const qC={t:0xc8,r:0xcf,f:0xcf,i:0xa4,h:0xde},qw=qB;this[qw(0x9f)]=t[qw(qC.t)]??new p(),this[qw(qC.r)]=new g(t[qw(qC.f)]??[]),this['llmGatewayFactory']=t[qw(qC.i)]??(r=>new K(r,t[qw(0xd5)]?{'providers':t[qw(0xd5)]}:{})),this[qw(qC.h)](t['graphs']??[]);}static async[qB(0xca)](t={}){const qp={t:0xc0,r:0xc0,f:0xd5,i:0xcf},qK=qB,r=await p[qK(0xa2)](t['configManager']);return new M({'sessionManager':r,...t['llmGatewayFactory']?{'llmGatewayFactory':t[qK(0xa4)]}:{},...t[qK(qp.t)]?{'graphs':t[qK(qp.r)]}:{},...t[qK(qp.f)]?{'providers':t[qK(0xd5)]}:{},...t[qK(qp.i)]?{'decisionProviders':t['decisionProviders']}:{}});}[qB(0xde)](t){const qs={t:0xbe},qJ={t:0x9e,r:0xd0},qj=qB,r=t[qj(qs.t)](f=>{const qD=qj,i=new f(this[qD(0xa4)](f[qD(qJ.t)]()[qD(0xe3)]));return i[qD(qJ.r)]?.(h=>this['decisionProviders'][qD(0xe7)](h)),i[qD(0xba)],i;});return this[qj(0xe1)]['register'](r),this;}[qB(0xaa)](){return this['registry']['names']();}[qB(0xe5)](t){const qz={t:0x9f},qo=qB;return this[qo(qz.t)]['getSession'](w(t));}async[qB(0xb9)](f){const qc={t:0xcc,r:0xdd,f:0xab,i:0xa5,h:0xa6,Q:0xe2,Z:0xb5},qR={t:0x9f,r:0xac,f:0xb7,i:0xba,h:0xa9,Q:0xa9,Z:0xa8,Y:0xeb,W:0xa8,S:0xea,b:0x9f,I:0xc4,q0:0xc2,q1:0xba,q2:0xba,q3:0xd7,q4:0xb1,q5:0xbc,q6:0xa1,q7:0xda,q8:0x9d,q9:0xe9,qq:0xdf},qa=qB,i=this[qa(0xe1)][qa(0xb0)](f[qa(0xe4)]);if(!i)return{'status':0x190,'body':{'success':!0x1,'completed':!0x0,'message':'Graph\x20\x27'+(f['graphName']??'')+qa(qc.t)}};const h=typeof f[qa(qc.r)]==qa(0xc3)?f['userMessage'][qa(qc.f)]():void 0x0;if(i[qa(0xd8)]!==!0x1&&!h)return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':qa(0xc7)}};let Q;try{Q=f[qa(0xd2)]?w(f['sessionId']):l();}catch(q0){return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':q0 instanceof Error?q0[qa(0xaf)]:String(q0)}};}const Z=X(i),Y=v(i),W={'graphId':Z,'graphSchemaVersion':Y,'llmConfig':i['llmConfig']},S=o();if(this['inflightSessions']['has'](Q))return this[qa(0xd4)](Q,s,qa(qc.i)+Q+qa(qc.h));this[qa(qc.Q)]['add'](Q);const b={'session':Q,...f[qa(0xb5)]===void 0x0?{}:{'signal':f[qa(qc.Z)]}};return this['withTurnScope'](b,S,async()=>{const qN=qa;let q1=!0x0,q2,q3;try{const q4=l(),q5=await this[qN(qR.t)][qN(qR.r)](Q,q4,W);q2=q4,q3=q5[qN(0xd9)];const q6=q5[qN(qR.f)][qN(qR.i)][qN(0xc9)]?q5[qN(0xb7)]:void 0x0;q6&&q6[qN(0xba)][qN(0xa8)]!==Y&&(q1=!0x1);const q7=q6?i[qN(qR.h)]?await i[qN(qR.Q)](q6):q6:void 0x0;if(q7&&q7[qN(0xba)][qN(qR.Z)]!==Y)throw new Error(qN(qR.Y)+Z+qN(0xbd)+q7[qN(0xba)][qN(qR.W)]+qN(qR.S)+Y+'.');q6&&q7&&q7['graph'][qN(0xa8)]!==q6[qN(0xba)][qN(qR.Z)]&&await this[qN(qR.t)]['persistMigratedSession'](q7,{'owner':q4,'expectedRevision':q3}),q1=!0x0;const q8=q7?this[qN(qR.t)][qN(0xbf)](q7,Z):void 0x0;if(q8?.[qN(0xa1)])return await this[qN(qR.b)][qN(0xc6)](Q,q4,q3),this[qN(0xae)](i[qN(qR.I)],Q);const q9={...h?i[qN(0xcd)](q8,new T(h)):q8??{},'config':{...q8?.[qN(qR.q0)]??{},...f[qN(0xc2)]??{}},'inputConsumed':!0x1,'response':''};let qq;if(i['graph'][qN(0xd3)]){const qk=await i[qN(qR.q1)][qN(0xd3)](q9,{'streamMode':'values'});for await(const qd of qk){if(qq=qd,qq[qN(0xe6)]!==!0x0)continue;const qG=a(S);let qT;try{qT=await this['sessions']['saveState'](Q,qq,W,qG,{'owner':q4,...q3===void 0x0?{}:{'expectedRevision':q3},'keepTurn':!0x0});}catch(qy){throw u(S,qG),qy;}q3=qT['revision'];}}else qq=await i[qN(qR.q2)][qN(qR.q3)](q9);if(!qq)throw new Error('Graph\x20\x27'+Z+qN(qR.q4));return await this[qN(qR.t)][qN(0xb2)](Q,qq,W,S,{'owner':q4,...q3===void 0x0?{}:{'expectedRevision':q3}}),i[qN(0xc4)]===qN(qR.q5)?this[qN(0xdc)](Q,qq[qN(0xcb)]):this['chatResult'](Q,qq[qN(0xcb)],qq[qN(qR.q6)]);}catch(ql){if(ql instanceof J)return this['conflictResult'](Q,ql[qN(qR.q7)],ql['message']);const qe=ql instanceof Error?ql['message']:String(ql);if(D({'chat_service':qe}),q2)try{await this[qN(0x9f)]['endFailedTurn'](Q,q2,W,q1?S:void 0x0,q3);}catch(qX){console[qN(qR.q8)](qN(qR.q9),qX);}return{'status':0x190,'session':Q,'body':{'success':!0x1,'completed':!0x1,'message':qe,'session':Q}};}finally{this['inflightSessions'][qN(qR.qq)](Q);}});}[qB(0xe8)](r,f,i){return m(r,()=>n(f,i));}async[qB(0xb3)](t){const qt={t:0xbb},qu=qB;if(!t)return{'status':0x190,'body':{'success':!0x1,'message':qu(qt.t)}};try{const r=w(t);return await this['sessions'][qu(0xb3)](r),{'status':0xc8,'body':{'success':!0x0,'session':r}};}catch(f){return{'status':0x190,'body':{'success':!0x1,'session':t,'message':f instanceof Error?f[qu(0xaf)]:String(f)}};}}async[qB(0xad)](){const qP=qB;await this[qP(0x9f)][qP(0xad)]();}['conflictResult'](r,f,i){return{'status':0x199,'session':r,'body':{'success':!0x1,'completed':!0x1,'message':i,'code':f,'session':r}};}[qB(0xae)](r,f){const qf={t:0xd4},qn=qB,i='This\x20conversation\x20is\x20already\x20complete.';return r===qn(0xbc)?this[qn(qf.t)](f,L,i):this['chatResult'](f,i,!0x0);}[qB(0xdc)](t,r){const qm=qB;return{'status':0xc8,'session':t,'contentType':qm(0xb6),'body':c(r)};}[qB(0xb8)](r,f,i){return{'status':0xc8,'session':r,'body':{'success':!0x0,'completed':i,'message':f,'bot':f,'session':r}};}}function w(t){const qQ={t:0xd1},qV=qB,r=t[qV(0xab)]();if(!/^[A-Za-z0-9_-]{1,128}$/[qV(qQ.t)](r))throw new Error('SESSION_ID\x20must\x20be\x201-128\x20letters,\x20numbers,\x20underscores,\x20or\x20hyphens.');return r;}y(w,qB(0xa7));export{M as GraphEngine};
1
+ const dJ=b;(function(L,D){const dW={L:0xe0,D:0xdb,a:0xc1,e:0xb4},dY=b,a=L();while(!![]){try{const e=parseInt(dY(0xa0))/0x1+parseInt(dY(dW.L))/0x2+parseInt(dY(dW.D))/0x3+parseInt(dY(dW.a))/0x4+-parseInt(dY(0xce))/0x5+parseInt(dY(0xd6))/0x6+parseInt(dY(dW.e))/0x7*(-parseInt(dY(0xa3))/0x8);if(e===D)break;else a['push'](a['shift']());}catch(K){a['push'](a['shift']());}}}(d,0x8258d));var P=Object['defineProperty'],y=(L,D)=>P(L,dJ(0xc5),{'value':D,'configurable':!0x0});import{HumanMessage as v}from'@langchain/core/messages';function d(){const dS=['z2v0','jYbJB21WBgv0zwqGD2L0Ag91DcbWCM9KDwnPBMCGC3rHDguU','C2f2zvn0yxrL','zgvSzxrLu2vZC2LVBG','mtmZyKPmquzc','C2LNBMfS','yxbWBgLJyxrPB24VANnVBG','zg9JDw1LBNq','y2HHDfjLC3vSDa','CNvU','z3jHCgG','u0vtu0LptL9jrcbPCYbYzxf1AxjLzc4','ANnVBG','jYbYzxn0B3jLihjLDhvYBMvKihnJAgvTysb2zxjZAw9Uia','BwfW','CMvZDg9YzvnLC3nPB25eB2n1BwvUDa','z3jHCgHZ','mti2mZCWmhbWs2TtCq','y29UzMLN','C3rYAw5N','CMvZCg9UC2vnB2rL','BMfTzq','CMvSzwfZzvr1CM4','DxnLCK1LC3nHz2uGBxvZDcbIzsbHig5VBI1LBxb0EsbZDhjPBMCU','C2vZC2LVBK1HBMfNzxi','BM9Kzxm','y3jLyxrL','CMvZCg9UC2u','jYbPCYbUB3qGCMvNAxn0zxjLzc4','ChjLCgfYzuLUChv0','ntG5nda1y0DYtxje','zgvJAxnPB25qCM92AwrLCNm','yxr0ywnOrgvJAxnPB25qCM92AwrLCLjLC29SDMvY','DgvZDa','C2vZC2LVBKLK','C3rYzwfT','y29UzMXPy3rszxn1Bhq','ChjVDMLKzxjZ','mJK0odeYnhbwwMLgBq','Aw52B2TL','CMvXDwLYzxnvC2vYtwvZC2fNzq','zxHWzwn0zwrszxzPC2LVBG','y29Kzq','mtu3otGZmgfArvHPzG','ANnVBLjLC3vSDa','DxnLCK1LC3nHz2u','CMvNAxn0zxjhCMfWAa','zgvSzxrL','mtiWnJCYnfHLC1jRra','CMvNAxn0CNK','Aw5MBgLNAhrtzxnZAw9UCW','BgXTq29UzMLN','z3jHCgHoyw1L','z2v0u2vZC2LVBG','Aw5WDxrdB25ZDw1Lza','CMvZB2X2zq','D2L0Afr1CM5ty29Wzq','vw5HyMXLihrVihbLCNnPC3qGC2vZC2LVBIbLCNjVCIbSB2C6','oYbLEhbLy3rLzca','r3jHCgGGjW','zxjYB3i','z2v0r3jHCgHezwzPBML0Aw9U','C2vZC2LVBNm','odGXodyXqKPzvuvt','y29TCgXLDgvK','zNjVBunVBMzPzW','oteYntyWuwjHww5m','BgXTr2f0zxDHEuzHy3rVCNK','u2vZC2LVBIaN','jYbPCYbHBhjLywr5ihbYB2nLC3nPBMCGysb0DxjUlG','DMfSAwrHDgvtzxnZAw9Uswq','C2nOzw1HvMvYC2LVBG','CMvZDg9YzvnLC3nPB25eB2m','z2v0r3jHCgHZ','DhjPBq','yMvNAw5uDxjU','y2XVC2u','y29TCgXLDgvKu2vZC2LVBLjLC3vSDa','BwvZC2fNzq'];d=function(){return dS;};return d();}function b(v,s){v=v-0x9d;const z=d();let F=z[v];if(b['pjzpNm']===undefined){var X=function(x){const p='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let f='',u='';for(let c=0x0,Z,H,r=0x0;H=x['charAt'](r++);~H&&(Z=c%0x4?Z*0x40+H:H,c++%0x4)?f+=String['fromCharCode'](0xff&Z>>(-0x2*c&0x6)):0x0){H=p['indexOf'](H);}for(let R=0x0,M=f['length'];R<M;R++){u+='%'+('00'+f['charCodeAt'](R)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(u);};b['bOrkSb']=X,b['wJSDQu']={},b['pjzpNm']=!![];}const V=z[0x0],Y=v+V,J=b['wJSDQu'][Y];return!J?(F=b['bOrkSb'](F),b['wJSDQu'][Y]=F):F=J,F;}import{randomUUID as s}from'node:crypto';import{GraphRegistry as X,registeredGraphId as Y,registeredGraphSchemaVersion as J}from'./graph-registry.js';import{LangChainLlmGateway as p}from'./langchain-llm-gateway.js';import{SessionLogError as f,createSessionLogs as u,drainSessionLogs as c,restoreSessionLogs as Z,withSessionLogs as r}from'./session-log.js';import{withTurnContext as W}from'./turn-context.js';import{SessionManager as I,SessionTurnError as g,SESSION_BUSY as i,SESSION_COMPLETED as h}from'./persistence/session-manager.js';import{parseJsonObjectResponse as t}from'./json-response.js';import{DecisionProviderRegistry as m}from'./decision/decision-provider.js';class M{static{y(this,'GraphEngine');}[dJ(0xe1)]=new X();[dJ(0x9f)];[dJ(0xa4)];['decisionProviders'];[dJ(0xe2)]=new Set();constructor(L={}){const dI={L:0xc8,D:0xcf,a:0xcf,e:0xa4,K:0xde},dx=dJ;this[dx(0x9f)]=L[dx(dI.L)]??new I(),this[dx(dI.D)]=new m(L[dx(dI.a)]??[]),this['llmGatewayFactory']=L[dx(dI.e)]??(D=>new p(D,L[dx(0xd5)]?{'providers':L[dx(0xd5)]}:{})),this[dx(dI.K)](L['graphs']??[]);}static async[dJ(0xca)](L={}){const dy={L:0xc0,D:0xc0,a:0xd5,e:0xcf},dp=dJ,D=await I[dp(0xa2)](L['configManager']);return new M({'sessionManager':D,...L['llmGatewayFactory']?{'llmGatewayFactory':L[dp(0xa4)]}:{},...L[dp(dy.L)]?{'graphs':L[dp(dy.D)]}:{},...L[dp(dy.a)]?{'providers':L[dp(0xd5)]}:{},...L[dp(dy.e)]?{'decisionProviders':L['decisionProviders']}:{}});}[dJ(0xde)](L){const di={L:0xbe},dg={L:0x9e,D:0xd0},df=dJ,D=L[df(di.L)](a=>{const du=df,K=new a(this[du(0xa4)](a[du(dg.L)]()[du(0xe3)]));return K[du(dg.D)]?.(o=>this['decisionProviders'][du(0xe7)](o)),K[du(0xba)],K;});return this[df(0xe1)]['register'](D),this;}[dJ(0xaa)](){return this['registry']['names']();}[dJ(0xe5)](L){const dt={L:0x9f},dc=dJ;return this[dc(dt.L)]['getSession'](w(L));}async[dJ(0xb9)](L){const dL={L:0xcc,D:0xdd,a:0xab,e:0xa5,K:0xa6,o:0xe2,Q:0xb5},dm={L:0x9f,D:0xac,a:0xb7,e:0xba,K:0xa9,o:0xa9,Q:0xa8,S:0xeb,l:0xa8,n:0xea,T:0x9f,G:0xc4,d0:0xc2,d1:0xba,d2:0xba,d3:0xd7,d4:0xb1,d5:0xbc,d6:0xa1,d7:0xda,d8:0x9d,d9:0xe9,dd:0xdf},dZ=dJ,D=this[dZ(0xe1)][dZ(0xb0)](L[dZ(0xe4)]);if(!D)return{'status':0x190,'body':{'success':!0x1,'completed':!0x0,'message':'Graph\x20\x27'+(L['graphName']??'')+dZ(dL.L)}};const a=typeof L[dZ(dL.D)]==dZ(0xc3)?L['userMessage'][dZ(dL.a)]():void 0x0;if(D[dZ(0xd8)]!==!0x1&&!a)return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':dZ(0xc7)}};let K;try{K=L[dZ(0xd2)]?w(L['sessionId']):s();}catch(G){return{'status':0x190,'body':{'success':!0x1,'completed':!0x1,'message':G instanceof Error?G[dZ(0xaf)]:String(G)}};}const o=Y(D),Q=J(D),S={'graphId':o,'graphSchemaVersion':Q,'llmConfig':D['llmConfig']},n=u();if(this['inflightSessions']['has'](K))return this[dZ(0xd4)](K,i,dZ(dL.e)+K+dZ(dL.K));this[dZ(dL.o)]['add'](K);const T={'session':K,...L[dZ(0xb5)]===void 0x0?{}:{'signal':L[dZ(dL.Q)]}};return this['withTurnScope'](T,n,async()=>{const dH=dZ;let d0=!0x0,d1,d2;try{const d3=s(),d4=await this[dH(dm.L)][dH(dm.D)](K,d3,S);d1=d3,d2=d4[dH(0xd9)];const d5=d4[dH(dm.a)][dH(dm.e)][dH(0xc9)]?d4[dH(0xb7)]:void 0x0;d5&&d5[dH(0xba)][dH(0xa8)]!==Q&&(d0=!0x1);const d6=d5?D[dH(dm.K)]?await D[dH(dm.o)](d5):d5:void 0x0;if(d6&&d6[dH(0xba)][dH(dm.Q)]!==Q)throw new Error(dH(dm.S)+o+dH(0xbd)+d6[dH(0xba)][dH(dm.l)]+dH(dm.n)+Q+'.');d5&&d6&&d6['graph'][dH(0xa8)]!==d5[dH(0xba)][dH(dm.Q)]&&await this[dH(dm.L)]['persistMigratedSession'](d6,{'owner':d3,'expectedRevision':d2}),d0=!0x0;const d7=d6?this[dH(dm.L)][dH(0xbf)](d6,o):void 0x0;if(d7?.[dH(0xa1)])return await this[dH(dm.T)][dH(0xc6)](K,d3,d2),this[dH(0xae)](D[dH(dm.G)],K);const d8={...a?D[dH(0xcd)](d7,new v(a)):d7??{},'config':{...d7?.[dH(dm.d0)]??{},...L[dH(0xc2)]??{}},'inputConsumed':!0x1,'response':''};let d9;if(D['graph'][dH(0xd3)]){const dd=await D[dH(dm.d1)][dH(0xd3)](d8,{'streamMode':'values'});for await(const db of dd){if(d9=db,d9[dH(0xe6)]!==!0x0)continue;const dv=c(n);let ds;try{ds=await this['sessions']['saveState'](K,d9,S,dv,{'owner':d3,...d2===void 0x0?{}:{'expectedRevision':d2},'keepTurn':!0x0});}catch(dz){throw Z(n,dv),dz;}d2=ds['revision'];}}else d9=await D[dH(dm.d2)][dH(dm.d3)](d8);if(!d9)throw new Error('Graph\x20\x27'+o+dH(dm.d4));return await this[dH(dm.L)][dH(0xb2)](K,d9,S,n,{'owner':d3,...d2===void 0x0?{}:{'expectedRevision':d2}}),D[dH(0xc4)]===dH(dm.d5)?this[dH(0xdc)](K,d9[dH(0xcb)]):this['chatResult'](K,d9[dH(0xcb)],d9[dH(dm.d6)]);}catch(dF){if(dF instanceof g)return this['conflictResult'](K,dF[dH(dm.d7)],dF['message']);const dX=dF instanceof Error?dF['message']:String(dF);if(f({'chat_service':dX}),d1)try{await this[dH(0x9f)]['endFailedTurn'](K,d1,S,d0?n:void 0x0,d2);}catch(dV){console[dH(dm.d8)](dH(dm.d9),dV);}return{'status':0x190,'session':K,'body':{'success':!0x1,'completed':!0x1,'message':dX,'session':K}};}finally{this['inflightSessions'][dH(dm.dd)](K);}});}[dJ(0xe8)](L,D,a){return W(L,()=>r(D,a));}async[dJ(0xb3)](L){const dB={L:0xbb},dr=dJ;if(!L)return{'status':0x190,'body':{'success':!0x1,'message':dr(dB.L)}};try{const D=w(L);return await this['sessions'][dr(0xb3)](D),{'status':0xc8,'body':{'success':!0x0,'session':D}};}catch(a){return{'status':0x190,'body':{'success':!0x1,'session':L,'message':a instanceof Error?a[dr(0xaf)]:String(a)}};}}async[dJ(0xad)](){const dR=dJ;await this[dR(0x9f)][dR(0xad)]();}['conflictResult'](L,D,a){return{'status':0x199,'session':L,'body':{'success':!0x1,'completed':!0x1,'message':a,'code':D,'session':L}};}[dJ(0xae)](L,D){const de={L:0xd4},dM=dJ,a='This\x20conversation\x20is\x20already\x20complete.';return L===dM(0xbc)?this[dM(de.L)](D,h,a):this['chatResult'](D,a,!0x0);}[dJ(0xdc)](L,D){const dq=dJ;return{'status':0xc8,'session':L,'contentType':dq(0xb6),'body':t(D)};}[dJ(0xb8)](L,D,a){return{'status':0xc8,'session':L,'body':{'success':!0x0,'completed':a,'message':D,'bot':D,'session':L}};}}function w(L){const dQ={L:0xd1},dP=dJ,D=L[dP(0xab)]();if(!/^[A-Za-z0-9_-]{1,128}$/[dP(dQ.L)](D))throw new Error('SESSION_ID\x20must\x20be\x201-128\x20letters,\x20numbers,\x20underscores,\x20or\x20hyphens.');return D;}y(w,dJ(0xa7));export{M as GraphEngine};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var i=(r,e)=>E(r,"name",{value:e,configurable:!0});import"reflect-metadata";import{AIMessage as p,HumanMessage as R}from"@langchain/core/messages";import{Command as c,END as f,isCommand as w}from"@langchain/langgraph";import{GraphLlm as u}from"./graph-llm.config.js";import{GraphStateSupport as T}from"./graph-state-support.js";import{ConversationRunner as O,DEFAULT_CONVERSATION_POLICY as H,DEFAULT_MAX_AGENT_ROUNDS as L,EmptyModelResponseError as $}from"./conversation-runner.js";import{currentTurnSignal as x}from"./turn-context.js";import{combineGraphNodeUpdates as A}from"./node-outcome.js";import{parseJsonObjectResponse as C}from"./json-response.js";import{stableClassId as g}from"./stable-id.js";import{SessionLogWarning as b}from"./session-log.js";import{isToolResponse as S,stay as G}from"./tool-response.js";import{invocationGraphState as I,hasNodeInvocation as k,invocationHistory as M,invocationNodeState as P,invocationUpdate as _,appendInvocationHistory as D,replaceInvocationNodeState as U,invocationContext as j,saveInvocationContext as J,replaceInvocationContext as q,saveInvocationNodeState as F,withNodeInvocation as z}from"./node-invocation.js";import{DecisionConfigurationError as V,resolveDecisionOptions as W}from"./decision/decision-types.js";import{GRAPH_NODE_LOCAL_STATE as ve}from"./node-outcome.js";const X=Symbol("GRAPH_NODE_CLASS"),y=Symbol("graph-node-tool-handlers");function ue(r){if(!r.trim())throw new Error("A tool handler requires a tool name.");return(e,t)=>{const o=Reflect.getOwnMetadata(y,e)??[];if(o.some(n=>n.toolName===r))throw new Error(`Tool '${r}' already has a handler.`);o.push({toolName:r,methodName:t}),Reflect.defineMetadata(y,o,e)}}i(ue,"Tool");class N{static{i(this,"GraphNode")}llmGateway;runtime;static[X]=!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=g(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 n=this.toolHandler(t.name);if(!n)return this.rejectToolCall(t.name,`Unsupported tool '${t.name}'.`);const d=this.runtime.requireTool(n.toolName),s=K(t.args);if(!s.ok)return this.rejectToolCall(n.toolName,s.error);const a=d.schema.safeParse(s.value);if(!a.success)return this.rejectToolCall(n.toolName,Q(a.error));const h=a.data,l=this[n.methodName];if(!l)throw new Error(`Tool '${n.toolName}' is decorated on missing method '${String(n.methodName)}'.`);const m=await l.call(this,h,o,e);if(S(m))return m;throw new Error(`Tool '${n.toolName}' on '${this.id}' must return a ToolResponse.`)}rejectToolCall(e,t){return b({tool_call:t,node:this.id,tool:e}),G(JSON.stringify({accepted:!1,error:t}))}usesChatModel(){return!0}onInvalidJsonResponse(e){throw e.error}onEmptyModelResponse(e){throw new $(e.reason)}invoke=i(e=>this.runtime.withInvocation(this.id,e,async()=>{const t=this.resolveNodeResponse(await this.run(e)),o=B(t),n=await this.resolveJsonResponse(e,o);if(this.runtime.stageNodeEntries(n.nodes),n.context!==void 0&&this.runtime.stageContext(n.context),this.usesChatModel()){const s=this.runtime.resolveLlmConfig(this.getLlmConfig()),a=Y(s,this.runtime.resolveLlmConfig()),h=(e.nodes??{})[this.id];(!a||h?.model!==void 0)&&this.runtime.saveNode(this.id,{model:a?void 0:u.modelMetadata(s)})}const d=A(n,this.runtime.stagedUpdate());return w(t)?new c({update:d,...t.goto===void 0?{}:{goto:t.goto},...t.graph===void 0?{}:{graph:t.graph},...t.resume===void 0?{}:{resume:t.resume}}):d}),"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 n=await this.onEmptyModelResponse({state:e,conversation:o,reason:o.stopReason});return{...o,response:n}}conversationLlmLifecycle(){}runAgentLoop(e,t){const o=this.conversationLlmLifecycle();return new O(this.llmGateway).run({...o===void 0?{}:{lifecycle:o},systemPrompt:this.getPrompt(e),history:this.history(e),tools:this.obtainTools(),llmConfig:this.llmConfig(),executeTool:i(n=>this.handleTool(e,n,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 p(e)])}}complete(e){return{...this.runtime.complete(e),...this.historyUpdate([new p(e)])}}resolveNodeResponse(e){if(!S(e))return e;if(e.kind==="stay")throw new Error(`Graph node '${this.id}' can only return stay() from a tool handler.`);if(e.cleanup)throw new Error(`Graph node '${this.id}' can only use withCleanup() from a tool handler.`);if(e.feedback!==void 0)throw new Error(`Graph node '${this.id}' can only use withToolFeedback() from a tool handler.`);if(e.messages&&this.graph.appendHistory(this.historySpace(),e.messages),e.kind==="go"||e.kind==="directTo"){if(!e.target)throw new Error(`Graph node '${this.id}' selected ${e.kind}() without a target.`);const t=g(e.target,"graph node"),o=this.graph.historySpace(t);if(e.state&&this.graph.saveNodeState(e.target,e.state),e.message&&this.graph.appendHistory(o,[e.message]),e.kind==="directTo"){const n=v(this.id,e);return this.graph.appendHistory(o,[new p(n)]),new c({update:{currentNode:t,response:n,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:f})}return new c({update:{currentNode:t,response:"",inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:t})}if(e.message)throw new Error(`Graph node '${this.id}' can only use withMessage() with go() or directTo().`);if(e.kind==="direct"){const t=v(this.id,e);return this.graph.appendHistory(this.historySpace(),[new p(t)]),new c({update:{currentNode:this.id,response:t,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:f})}if(e.kind==="finish"){const t=v(this.id,e);return this.graph.appendHistory(this.historySpace(),[new p(t)]),new c({update:{...this.graph.complete(t),...e.usage===void 0?{}:{tokens:e.usage}},goto:f})}throw new Error(`Graph node '${this.id}' returned an unsupported response kind '${e.kind}'.`)}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 C(t.response??""),t}catch(o){const n=await this.onInvalidJsonResponse({state:e,update:t,response:t.response??"",error:o instanceof Error?o:new Error(String(o))});return(n.completed===!0||n.response)&&C(n.response??""),n}}toolHandlers(){let e=Object.getPrototypeOf(this);const t=[];for(;e&&e!==N.prototype;){const n=Reflect.getOwnMetadata(y,e)??[];t.push(...n),e=Object.getPrototypeOf(e)}const o=new Set;for(const n of t){if(o.has(n.toolName))throw new Error(`Graph node '${this.id}' has more than one handler for tool '${n.toolName}'.`);o.add(n.toolName)}return t}}function Y(r,e){return r.model===e.model&&JSON.stringify(u.parameters(r))===JSON.stringify(u.parameters(e))}i(Y,"sameLlmConfig");class fe extends T{static{i(this,"GraphNodeRuntime")}defaultLlmConfig;historySpaces;responseMode;maxAgentRounds;conversationPolicy;decisionOptions;decisionErrorHandler;llmLifecycle;assertContextChannel;tools=new Map;constructor(e,t,o={},n="chat",d=L,s=H,a={},h,l,m){super(e),this.defaultLlmConfig=t,this.historySpaces=o,this.responseMode=n,this.maxAgentRounds=d,this.conversationPolicy=s,this.decisionOptions=a,this.decisionErrorHandler=h,this.llmLifecycle=l,this.assertContextChannel=m}llmCallOptions(){const{llmTimeoutMs:e}=this.conversationPolicy,t=x();return{...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}}}expectsJsonResponse(){return this.responseMode==="json"}historySpace(e){return e?this.historySpaces[e]??"default":"default"}resolveLlmConfig(e={}){return u.resolveConfig(this.defaultLlmConfig,e)}resolveDecisionOptions(e={}){return W(this.decisionOptions,e)}decisionProviderResolver;attachDecisionProviderResolver(e){this.decisionProviderResolver=e}resolveDecisionProvider(e){if(!this.decisionProviderResolver)throw new V(`Decision provider '${e}' cannot be resolved before the graph is attached to an engine.`);return this.decisionProviderResolver(e)}async handleDecisionError(e){return await this.decisionErrorHandler?.(e)??null}registerTools(e,t){for(const o of t){const n=this.tools.get(o.name);if(n)throw new Error(`Tool '${o.name}' is defined by both '${n.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)]??[]})}getConversation(e){const o=(this.hasInvocation()?this.invocationHistory(e):[]).filter(n=>R.isInstance(n)&&n.additional_kwargs?.ezgraphInternal!==!0).map(n=>typeof n.content=="string"?n.content:JSON.stringify(n.content));return{request:o.at(-1)??"",priorRequests:o.slice(-5,-1)}}respond(e){return this.responseUpdate(e)}complete(e){return this.endUpdate(e)}withInvocation(e,t,o){return z(this,e,t,o)}nodeState(e){return P(this,e)}hasInvocation(){return k(this)}graphState(){return I(this)}getContext(){return j(this)}saveContext(e){this.assertContextChannel?.(),J(this,e)}stageContext(e){this.assertContextChannel?.(),q(this,e)}appendHistory(e,t){D(this,e,t)}invocationHistory(e){return M(this,e)}stagedUpdate(){return _(this)}stageNodeEntries(e){for(const[t,o]of Object.entries(e??{}))!o||typeof o!="object"||Array.isArray(o)||U(this,t,o)}saveNode(e,t){return F(this,e,t),{nodes:{[e]:this.nodeState(e)}}}saveNodeState(e,t){this.saveNode(g(e,"graph node"),t)}removeNode(e,...t){return this.saveNode(e,Object.fromEntries(t.map(o=>[o,void 0])))}}function B(r){if(!w(r))return r;if(Array.isArray(r.update))throw new Error("GraphNode Command updates must be state objects.");return r.update??{}}i(B,"commandUpdate");function v(r,e){if(!e.response?.trim())throw new Error(`Graph node '${r}' selected ${e.kind}() without a response.`);return e.response}i(v,"requireNodeResponse");function K(r){if(typeof r!="string")return{ok:!0,value:r};try{return{ok:!0,value:JSON.parse(r)}}catch(e){return{ok:!1,error:`Tool arguments were not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}i(K,"coerceToolArgs");function Q(r){return r.issues.map(e=>e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message).join("; ")}i(Q,"formatToolArgumentError");export{X as GRAPH_NODE_CLASS,ve as GRAPH_NODE_LOCAL_STATE,N as GraphNode,fe as GraphNodeRuntime,ue as Tool};
1
+ var R=Object.defineProperty;var d=(r,e)=>R(r,"name",{value:e,configurable:!0});import"reflect-metadata";import{AIMessage as c,HumanMessage as T}from"@langchain/core/messages";import{Command as p,END as y,isCommand as u}from"@langchain/langgraph";import{GraphLlm as f}from"./graph-llm.config.js";import{GraphStateSupport as L}from"./graph-state-support.js";import{LlmRunner as O,DEFAULT_LLM_POLICY as I,DEFAULT_MAX_AGENT_ROUNDS as H,EmptyModelResponseError as k}from"./llm-runner.js";import{currentTurnSignal as x}from"./turn-context.js";import{combineGraphNodeUpdates as $}from"./node-outcome.js";import{parseJsonObjectResponse as N}from"./json-response.js";import{stableClassId as v}from"./stable-id.js";import{SessionLogWarning as b}from"./session-log.js";import{goTargetIds as A,isToolResponse as S,stay as M}from"./tool-response.js";import{invocationGraphState as G,hasNodeInvocation as P,invocationHistory as _,invocationNodeState as j,invocationUpdate as D,appendInvocationHistory as U,replaceInvocationNodeState as J,invocationContext as q,saveInvocationContext as F,replaceInvocationContext as W,saveInvocationNodeState as z,withNodeInvocation as X,invocationMode as Y,invocationIsLocalOnly as B,assertInvocationWrite as g}from"./node-invocation.js";import{DecisionConfigurationError as K,resolveDecisionOptions as Q}from"./decision/decision-types.js";import{GRAPH_NODE_LOCAL_STATE as Se}from"./node-outcome.js";const V=Symbol("GRAPH_NODE_CLASS"),w=Symbol("graph-node-tool-handlers");function ve(r){if(!r.trim())throw new Error("A tool handler requires a tool name.");return(e,t)=>{const o=Reflect.getOwnMetadata(w,e)??[];if(o.some(n=>n.toolName===r))throw new Error(`Tool '${r}' already has a handler.`);o.push({toolName:r,methodName:t}),Reflect.defineMetadata(w,o,e)}}d(ve,"Tool");class E{static{d(this,"GraphNode")}llmGateway;runtime;static[V]=!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=v(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 n=this.toolHandler(t.name);if(!n)return this.rejectToolCall(t.name,`Unsupported tool '${t.name}'.`);const i=this.runtime.requireTool(n.toolName),a=te(t.args);if(!a.ok)return this.rejectToolCall(n.toolName,a.error);const s=i.schema.safeParse(a.value);if(!s.success)return this.rejectToolCall(n.toolName,oe(s.error));const h=s.data,l=this[n.methodName];if(!l)throw new Error(`Tool '${n.toolName}' is decorated on missing method '${String(n.methodName)}'.`);const m=await l.call(this,h,o,e);if(S(m))return m;throw new Error(`Tool '${n.toolName}' on '${this.id}' must return a ToolResponse.`)}rejectToolCall(e,t){return b({tool_call:t,node:this.id,tool:e}),M(JSON.stringify({accepted:!1,error:t}))}usesChatModel(){return!0}onInvalidJsonResponse(e){throw e.error}onEmptyModelResponse(e){throw new k(e.reason)}invoke=d((e,t={})=>this.runtime.withInvocation(this.id,e,async()=>{const o=this.resolveNodeResponse(await this.run(e)),n=ee(o),i=await this.resolveJsonResponse(e,n);if(this.runtime.stageNodeEntries(i.nodes),i.context!==void 0&&this.runtime.stageContext(i.context),this.usesChatModel()){const s=this.runtime.resolveLlmConfig(this.getLlmConfig()),h=Z(s,this.runtime.resolveLlmConfig()),l=(e.nodes??{})[this.id];(!h||l?.model!==void 0)&&this.runtime.saveNode(this.id,{model:h?void 0:f.modelMetadata(s)})}const a=$(i,this.runtime.stagedUpdate());if(this.runtime.isLocalOnlyInvocation()&&(u(o)||Object.keys(a).some(s=>s!=="nodes"&&s!=="tokens")||Object.keys(a.nodes??{}).some(s=>s!==this.id)))throw new Error(`Internal LLM node '${this.id}' may publish only its own node state and token usage.`);return this.validateNodeResult(a,u(o)),u(o)?new p({update:a,...o.goto===void 0?{}:{goto:o.goto},...o.graph===void 0?{}:{graph:o.graph},...o.resume===void 0?{}:{resume:o.resume}}):a},t,this.managesLlmExecution()),"invoke");managesLlmExecution(){return!1}validateNodeResult(e,t){}obtainTools(e={}){return this.toolHandlers().filter(({toolName:t})=>this.includeTool(t,e)).map(({toolName:t})=>this.runtime.requireTool(t)).sort((t,o)=>t.name==="terminate_session"?1:o.name==="terminate_session"?-1:0)}validateTools(e={}){this.obtainTools(e)}includeTool(e,t){return!0}llmConfig(){return this.runtime.resolveLlmConfig(this.getLlmConfig())}llmCallOptions(){return this.runtime.llmCallOptions()}async runLlm(e,t){const o=await this.runAgentLoop(e,t);if(!o.stopReason)return o;const n=await this.onEmptyModelResponse({state:e,conversation:o,reason:o.stopReason});return{...o,response:n}}llmLifecycle(){}runAgentLoop(e,t){const o=this.llmLifecycle();return new O(this.llmGateway).run({...o===void 0?{}:{lifecycle:o},systemPrompt:this.getPrompt(e),history:this.llmHistory(e),tools:this.obtainTools(),llmConfig:this.llmConfig(),executeTool:d(n=>this.handleTool(e,n,t),"executeTool"),maxAgentRounds:this.runtime.maxAgentRounds,emptyHistorySeed:this.runtime.llmPolicy.emptyHistorySeed,emptyResponseRecovery:this.runtime.llmPolicy.emptyResponseRecovery,callOptions:this.llmCallOptions()})}llmHistory(e){return this.history(e)}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)])}}resolveNodeResponse(e){if(!S(e))return e;if(e.targets!==void 0&&e.kind!=="go")throw new Error("Multiple targets are only supported by go().");if(e.kind==="stay")throw new Error(`Graph node '${this.id}' can only return stay() from a tool handler.`);if(e.cleanup)throw new Error(`Graph node '${this.id}' can only use withCleanup() from a tool handler.`);if(e.feedback!==void 0)throw new Error(`Graph node '${this.id}' can only use withToolFeedback() from a tool handler.`);if(e.messages&&this.graph.appendHistory(this.historySpace(),e.messages),e.kind==="go"||e.kind==="directTo"){const t=e.kind==="go"?A(e):void 0;if(t&&t.length>1)return new p({update:{response:"",inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:[...t]});if(!e.target)throw new Error(`Graph node '${this.id}' selected ${e.kind}() without a target.`);const o=t?.[0]??v(e.target,"graph node"),n=this.graph.historySpace(o);if(e.state&&this.graph.saveNodeState(e.target,e.state),e.message&&this.graph.appendHistory(n,[e.message]),e.kind==="directTo"){const i=C(this.id,e);return this.graph.appendHistory(n,[new c(i)]),new p({update:{currentNode:o,response:i,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:y})}return new p({update:{currentNode:o,response:"",inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:o})}if(e.message)throw new Error(`Graph node '${this.id}' can only use withMessage() with go() or directTo().`);if(e.kind==="direct"){const t=C(this.id,e);return this.graph.appendHistory(this.historySpace(),[new c(t)]),new p({update:{currentNode:this.id,response:t,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:y})}if(e.kind==="finish"){const t=C(this.id,e);return this.graph.appendHistory(this.historySpace(),[new c(t)]),new p({update:{...this.graph.complete(t),...e.usage===void 0?{}:{tokens:e.usage}},goto:y})}throw new Error(`Graph node '${this.id}' returned an unsupported response kind '${e.kind}'.`)}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 N(t.response??""),t}catch(o){const n=await this.onInvalidJsonResponse({state:e,update:t,response:t.response??"",error:o instanceof Error?o:new Error(String(o))});return(n.completed===!0||n.response)&&N(n.response??""),n}}toolHandlers(){let e=Object.getPrototypeOf(this);const t=[];for(;e&&e!==E.prototype;){const n=Reflect.getOwnMetadata(w,e)??[];t.push(...n),e=Object.getPrototypeOf(e)}const o=new Set;for(const n of t){if(o.has(n.toolName))throw new Error(`Graph node '${this.id}' has more than one handler for tool '${n.toolName}'.`);o.add(n.toolName)}return t}}function Z(r,e){return r.model===e.model&&JSON.stringify(f.parameters(r))===JSON.stringify(f.parameters(e))}d(Z,"sameLlmConfig");class we extends L{static{d(this,"GraphNodeRuntime")}defaultLlmConfig;historySpaces;responseMode;maxAgentRounds;llmPolicy;decisionOptions;decisionErrorHandler;llmLifecycle;assertContextChannel;tools=new Map;constructor(e,t,o={},n="chat",i=H,a=I,s={},h,l,m){super(e),this.defaultLlmConfig=t,this.historySpaces=o,this.responseMode=n,this.maxAgentRounds=i,this.llmPolicy=a,this.decisionOptions=s,this.decisionErrorHandler=h,this.llmLifecycle=l,this.assertContextChannel=m}llmCallOptions(){const{llmTimeoutMs:e}=this.llmPolicy,t=x();return{...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}}}expectsJsonResponse(){return this.responseMode==="json"}historySpace(e){return e?this.historySpaces[e]??"default":"default"}resolveLlmConfig(e={}){return f.resolveConfig(this.defaultLlmConfig,e)}resolveDecisionOptions(e={}){return Q(this.decisionOptions,e)}decisionProviderResolver;attachDecisionProviderResolver(e){this.decisionProviderResolver=e}resolveDecisionProvider(e){if(!this.decisionProviderResolver)throw new K(`Decision provider '${e}' cannot be resolved before the graph is attached to an engine.`);return this.decisionProviderResolver(e)}async handleDecisionError(e){return await this.decisionErrorHandler?.(e)??null}registerTools(e,t){for(const o of t){const n=this.tools.get(o.name);if(n)throw new Error(`Tool '${o.name}' is defined by both '${n.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)]??[]})}getConversation(e){const o=(this.hasInvocation()?this.invocationHistory(e):[]).filter(n=>T.isInstance(n)&&n.additional_kwargs?.ezgraphInternal!==!0).map(n=>typeof n.content=="string"?n.content:JSON.stringify(n.content));return{request:o.at(-1)??"",priorRequests:o.slice(-5,-1)}}respond(e){return this.hasInvocation()&&g(this),this.responseUpdate(e)}complete(e){return this.hasInvocation()&&g(this),this.endUpdate(e)}withInvocation(e,t,o,n={},i=!1){return X(this,e,t,o,n,i)}invocationMode(){return Y(this)}isLocalOnlyInvocation(){return B(this)}nodeState(e){return j(this,e)}hasInvocation(){return P(this)}graphState(){return G(this)}getContext(){return q(this)}saveContext(e){g(this),this.assertContextChannel?.(),F(this,e)}stageContext(e){g(this),this.assertContextChannel?.(),W(this,e)}appendHistory(e,t){U(this,e,t)}invocationHistory(e){return _(this,e)}stagedUpdate(){return D(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 z(this,e,t),{nodes:{[e]:this.nodeState(e)}}}saveNodeState(e,t){this.saveNode(v(e,"graph node"),t)}removeNode(e,...t){return this.saveNode(e,Object.fromEntries(t.map(o=>[o,void 0])))}}function ee(r){if(!u(r))return r;if(Array.isArray(r.update))throw new Error("GraphNode Command updates must be state objects.");return r.update??{}}d(ee,"commandUpdate");function C(r,e){if(!e.response?.trim())throw new Error(`Graph node '${r}' selected ${e.kind}() without a response.`);return e.response}d(C,"requireNodeResponse");function te(r){if(typeof r!="string")return{ok:!0,value:r};try{return{ok:!0,value:JSON.parse(r)}}catch(e){return{ok:!1,error:`Tool arguments were not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}d(te,"coerceToolArgs");function oe(r){return r.issues.map(e=>e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message).join("; ")}d(oe,"formatToolArgumentError");export{V as GRAPH_NODE_CLASS,Se as GRAPH_NODE_LOCAL_STATE,E as GraphNode,we as GraphNodeRuntime,ve as Tool};
@@ -1 +1 @@
1
- function q(){const A=['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'];q=function(){return A;};return q();}const p=k;(function(X,B){const z={X:0x17a,B:0x16b,w:0x178,K:0x166},E=k,w=X();while(!![]){try{const K=parseInt(E(0x173))/0x1+-parseInt(E(0x17c))/0x2+-parseInt(E(z.X))/0x3+-parseInt(E(z.B))/0x4+parseInt(E(z.w))/0x5+parseInt(E(z.K))/0x6*(parseInt(E(0x174))/0x7)+parseInt(E(0x16c))/0x8*(parseInt(E(0x175))/0x9);if(K===B)break;else w['push'](w['shift']());}catch(j){w['push'](w['shift']());}}}(q,0xb9e87));var s=Object['defineProperty'],l=(X,B)=>s(X,p(0x171),{'value':B,'configurable':!0x0});import{GraphLlm as d,ModelCatalog as G}from'./graph-llm.config.js';function k(d,G){d=d-0x165;const T=q();let y=T[d];if(k['uapbbH']===undefined){var l=function(B){const w='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let K='',j='';for(let D=0x0,o,a,N=0x0;a=B['charAt'](N++);~a&&(o=D%0x4?o*0x40+a:a,D++%0x4)?K+=String['fromCharCode'](0xff&o>>(-0x2*D&0x6)):0x0){a=w['indexOf'](a);}for(let u=0x0,P=K['length'];u<P;u++){j+='%'+('00'+K['charCodeAt'](u)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(j);};k['ujitrk']=l,k['tGlJwF']={},k['uapbbH']=!![];}const e=T[0x0],X=d+e,v=k['tGlJwF'][X];return!v?(y=k['ujitrk'](y),k['tGlJwF'][X]=y):y=v,y;}import{modelProviderAdapter as T}from'./model-provider.js';import{OPENAI_AUTH_PROVIDER as y,initializeOpenAIAuthProvider as e}from'./openai-auth-provider.js';function C(X,B=[]){const R={X:0x17e,B:0x17d,w:0x165,K:0x167,j:0x16d,D:0x16e,o:0x170,a:0x16a,N:0x16e},J=p,w=d[J(R.X)](X),K=G[J(R.B)](w),j={};for(const [N,P]of Object[J(0x17f)](w[J(R.w)])){const V=K[J(R.K)][N];V!==null&&u(j,V??N,P);}if(K[J(0x16e)]===y)return e(K[J(R.j)],j);const D=T(K[J(R.D)],B)??K[J(R.o)];return D?D[J(R.a)]({'provider':K[J(R.N)],'model':K[J(R.j)],'options':j}):{'model':K[J(R.j)],'options':{'modelProvider':K[J(0x16e)],...j}};}l(C,p(0x169));function u(X,B,w){const t={X:0x16f,B:0x17b,w:0x176,K:0x179},L=p,K=B[L(0x177)]('.');let j=X;for(const N of K[L(0x172)](0x0,-0x1)){const P=j[N];if(P===void 0x0){const V={};j[N]=V,j=V;}else{if(typeof P==L(t.X)&&P!==null&&!Array[L(t.B)](P))j=P;else throw new Error(L(t.w)+B+'\x27\x20has\x20a\x20conflicting\x20path.');}}const D=K['at'](-0x1);if(!D)throw new Error(L(t.K));j[D]=w;}l(u,p(0x168));export{C as langChainModelInitialization};
1
+ function d(){const B=['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'];d=function(){return B;};return d();}const y=b;(function(J,x){const t={J:0x17a,x:0x16b,p:0x178,Z:0x166},I=b,p=J();while(!![]){try{const Z=parseInt(I(0x173))/0x1+-parseInt(I(0x17c))/0x2+-parseInt(I(t.J))/0x3+-parseInt(I(t.x))/0x4+parseInt(I(t.p))/0x5+parseInt(I(t.Z))/0x6*(parseInt(I(0x174))/0x7)+parseInt(I(0x16c))/0x8*(parseInt(I(0x175))/0x9);if(Z===x)break;else p['push'](p['shift']());}catch(H){p['push'](p['shift']());}}}(d,0xb9e87));var s=Object['defineProperty'],l=(J,x)=>s(J,y(0x171),{'value':x,'configurable':!0x0});import{GraphLlm as z,ModelCatalog as F}from'./graph-llm.config.js';function b(v,s){v=v-0x165;const z=d();let F=z[v];if(b['uapbbH']===undefined){var X=function(x){const p='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let f='',u='';for(let c=0x0,Z,H,r=0x0;H=x['charAt'](r++);~H&&(Z=c%0x4?Z*0x40+H:H,c++%0x4)?f+=String['fromCharCode'](0xff&Z>>(-0x2*c&0x6)):0x0){H=p['indexOf'](H);}for(let R=0x0,M=f['length'];R<M;R++){u+='%'+('00'+f['charCodeAt'](R)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(u);};b['ujitrk']=X,b['tGlJwF']={},b['uapbbH']=!![];}const V=z[0x0],Y=v+V,J=b['tGlJwF'][Y];return!J?(F=b['ujitrk'](F),b['tGlJwF'][Y]=F):F=J,F;}import{modelProviderAdapter as X}from'./model-provider.js';import{OPENAI_AUTH_PROVIDER as V,initializeOpenAIAuthProvider as Y}from'./openai-auth-provider.js';function C(J,x=[]){const L={J:0x17e,x:0x17d,p:0x165,Z:0x167,H:0x16d,r:0x16e,R:0x170,M:0x16a,q:0x16e},i=y,Z=z[i(L.J)](J),H=F[i(L.x)](Z),R={};for(const [q,P]of Object[i(0x17f)](Z[i(L.p)])){const W=H[i(L.Z)][q];W!==null&&u(R,W??q,P);}if(H[i(0x16e)]===V)return Y(H[i(L.H)],R);const M=X(H[i(L.r)],x)??H[i(L.R)];return M?M[i(L.M)]({'provider':H[i(L.q)],'model':H[i(L.H)],'options':R}):{'model':H[i(L.H)],'options':{'modelProvider':H[i(0x16e)],...R}};}l(C,y(0x169));function u(J,x,Z){const D={J:0x16f,x:0x17b,p:0x176,Z:0x179},h=y,H=x[h(0x177)]('.');let R=J;for(const q of H[h(0x172)](0x0,-0x1)){const P=R[q];if(P===void 0x0){const W={};R[q]=W,R=W;}else{if(typeof P==h(D.J)&&P!==null&&!Array[h(D.x)](P))R=P;else throw new Error(h(D.p)+x+'\x27\x20has\x20a\x20conflicting\x20path.');}}const M=H['at'](-0x1);if(!M)throw new Error(h(D.Z));R[M]=Z;}l(u,y(0x168));export{C as langChainModelInitialization};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var o=(e,r)=>s(e,"name",{value:r,configurable:!0});function l(e){return{kind:"retry_with_model",model:e}}o(l,"retryWithModel");class p extends Error{static{o(this,"LlmResponseBlockedError")}context;constructor(r,t){super(`LLM response blocked. Reason:${r.rawReason}`,{cause:t}),this.context=r,this.name="LlmResponseBlockedError"}}class c extends Error{static{o(this,"LlmSetupError")}constructor(r){super(r instanceof Error?r.message:String(r),{cause:r}),this.name="LlmSetupError"}}export{p as LlmResponseBlockedError,c as LlmSetupError,l as retryWithModel};
1
+ var s=Object.defineProperty;var o=(e,r)=>s(e,"name",{value:r,configurable:!0});import{GraphLlm as n}from"./graph-llm.config.js";function m(e){return{kind:"retry_with_model",model:n.validateConfig(e)}}o(m,"retryWithModel");class p extends Error{static{o(this,"LlmResponseBlockedError")}context;constructor(r,t){super(`LLM response blocked. Reason:${r.rawReason}`,{cause:t}),this.context=r,this.name="LlmResponseBlockedError"}}class d extends Error{static{o(this,"LlmSetupError")}constructor(r){super(r instanceof Error?r.message:String(r),{cause:r}),this.name="LlmSetupError"}}export{p as LlmResponseBlockedError,d as LlmSetupError,m as retryWithModel};
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty;var e=(o,r)=>t(o,"name",{value:r,configurable:!0});import{GraphNode as n}from"./graph-node.js";class d extends n{static{e(this,"LlmNodeBase")}checkResponse(r){return!1}async onLlmBlocked(r){return null}shouldRetryLlmError(r){}async onLlmError(r){return null}validateLlmRecovery(r){}llmLifecycle(){return{nodeId:this.id,checkResponse:e(r=>this.checkResponse(r),"checkResponse"),shouldRetryLlmError:e(r=>{r.signal?.throwIfAborted();const l=this.shouldRetryLlmError(r);r.signal?.throwIfAborted();const s=l===void 0?this.graph.llmLifecycle?.shouldRetryLlmError(r):l;return r.signal?.throwIfAborted(),s},"shouldRetryLlmError"),onLlmBlocked:e(async r=>{r.signal?.throwIfAborted();let l=await this.onLlmBlocked(r);return r.signal?.throwIfAborted(),l===null&&(l=await this.graph.llmLifecycle?.onLlmBlocked(r)??null,r.signal?.throwIfAborted()),this.validateLlmRecovery(l),l},"onLlmBlocked"),onLlmError:e(async r=>{r.signal?.throwIfAborted();let l=await this.onLlmError(r);return r.signal?.throwIfAborted(),l===null&&(l=await this.graph.llmLifecycle?.onLlmError(r)??null,r.signal?.throwIfAborted()),this.validateLlmRecovery(l),l},"onLlmError")}}}export{d as LlmNodeBase};
@@ -1 +1 @@
1
- var m=Object.defineProperty;var a=(n,t)=>m(n,"name",{value:t,configurable:!0});var g=function(n,t,e,r){var s=arguments.length,o=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,t,e,r);else for(var d=n.length-1;d>=0;d--)(i=n[d])&&(o=(s<3?i(o):s>3?i(t,e,o):i(t,e))||o);return s>3&&o&&Object.defineProperty(t,e,o),o},l=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)};import{AIMessage as u,HumanMessage as w}from"@langchain/core/messages";import{Command as h,END as p}from"@langchain/langgraph";import{GraphNode as y,Tool as L}from"./graph-node.js";import{stableClassId as f}from"./stable-id.js";import{TerminateSessionNode as R}from"./terminate-session.node.js";import{go as k}from"./tool-response.js";import{addTokenUsage as b}from"./token-usage.js";class I extends y{static{a(this,"LlmNode")}checkResponse(t){return!1}async onLlmBlocked(t){return null}shouldRetryLlmError(t){}async onLlmError(t){return null}conversationLlmLifecycle(){return{nodeId:this.id,checkResponse:a(t=>this.checkResponse(t),"checkResponse"),shouldRetryLlmError:a(t=>{t.signal?.throwIfAborted();const e=this.shouldRetryLlmError(t);t.signal?.throwIfAborted();const r=e===void 0?this.graph.llmLifecycle?.shouldRetryLlmError(t):e;return t.signal?.throwIfAborted(),r},"shouldRetryLlmError"),onLlmBlocked:a(async t=>{t.signal?.throwIfAborted();let e=await this.onLlmBlocked(t);return t.signal?.throwIfAborted(),e===null&&(e=await this.graph.llmLifecycle?.onLlmBlocked(t)??null,t.signal?.throwIfAborted()),e},"onLlmBlocked"),onLlmError:a(async t=>{t.signal?.throwIfAborted();let e=await this.onLlmError(t);return t.signal?.throwIfAborted(),e===null&&(e=await this.graph.llmLifecycle?.onLlmError(t)??null,t.signal?.throwIfAborted()),e},"onLlmError")}}async endChat(t){return k(R).withMessage(new w({content:t.message?.trim()||"The user asked to end the conversation.",additional_kwargs:{ezgraphInternal:!0}}))}async run(t){const e=await this.runConversation(t,{});if(e.toolResponse)return this.resolveToolResponse(e,e.toolResponse);const r=e.response;if(!r?.trim())throw new Error(`LLM node '${this.id}' stopped without a response or tool transition.`);return new h({update:{currentNode:this.id,response:r,inputConsumed:!0,completed:!1,...this.historyUpdate(e.messages),tokens:e.usage},goto:p})}resolveToolResponse(t,e){const r=this.historyUpdate(t.messages),s=b(t.usage,e.usage);if(e.kind==="go"){if(!e.target)throw new Error(`LLM node '${this.id}' selected go() without a target.`);const o=f(e.target,"graph node");return e.state&&this.graph.saveNodeState(e.target,e.state),e.message&&this.graph.appendHistory(this.graph.historySpace(o),[e.message]),new h({update:{currentNode:o,inputConsumed:!0,response:"",completed:!1,...r,tokens:s},goto:o})}if(e.kind==="directTo"){if(!e.target)throw new Error(`LLM node '${this.id}' selected directTo() without a target.`);const o=f(e.target,"graph node"),i=this.graph.historySpace(o);e.state&&this.graph.saveNodeState(e.target,e.state),e.message&&this.graph.appendHistory(i,[e.message]);const d=c(this.id,e);return i!==this.historySpace()&&this.graph.appendHistory(i,[new u(d)]),new h({update:{currentNode:o,response:d,inputConsumed:!0,completed:!1,...r,tokens:s},goto:p})}if(e.kind==="direct")return new h({update:{currentNode:this.id,response:c(this.id,e),inputConsumed:!0,completed:!1,...r,tokens:s},goto:p});if(e.kind==="finish")return new h({update:{...this.graph.complete(c(this.id,e)),...r,tokens:s},goto:p});throw new Error(`LLM node '${this.id}' returned stay() after the agent loop stopped.`)}}g([L("terminate_session"),l("design:type",Function),l("design:paramtypes",[Object]),l("design:returntype",Promise)],I.prototype,"endChat",null);function c(n,t){if(!t.response?.trim())throw new Error(`LLM node '${n}' selected ${t.kind}() without a response.`);return t.response}a(c,"requireResponse");export{I as LlmNode};
1
+ var y=Object.defineProperty;var c=(a,e)=>y(a,"name",{value:e,configurable:!0});var k=function(a,e,t,o){var s=arguments.length,n=s<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,t):o,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(a,e,t,o);else for(var r=a.length-1;r>=0;r--)(i=a[r])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n},m=function(a,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(a,e)};import{AIMessage as h,HumanMessage as L}from"@langchain/core/messages";import{Command as d,END as f}from"@langchain/langgraph";import{Tool as v}from"./graph-node.js";import{LlmNodeBase as R}from"./llm-node-base.js";import{stableClassId as M}from"./stable-id.js";import{TerminateSessionNode as I}from"./terminate-session.node.js";import{go as E,goTargetIds as l,isToolResponse as T}from"./tool-response.js";import{addTokenUsage as u}from"./token-usage.js";import{currentTurnSignal as g}from"./turn-context.js";class _ extends R{static{c(this,"LlmNode")}onResponse(e,t){}managesLlmExecution(){return!0}isInternal(){return this.graph.hasInvocation()&&this.graph.invocationMode()==="internal"}includeTool(e,t){return!((t.mode==="internal"||t.mode===void 0&&this.isInternal())&&e==="terminate_session")}llmHistory(e){return this.isInternal()?[]:super.llmHistory(e)}async handleTool(e,t,o){if(this.isInternal()&&t.name==="terminate_session")throw this.invalidInternalOutcome(t.name);const s=await super.handleTool(e,t,o);return this.validateOutcome(s),s}validateLlmRecovery(e){e&&typeof e=="object"&&e.kind!=="retry_with_model"&&this.validateOutcome(e)}validateOutcome(e){const t=["target","targets","state","message","messages"].some(o=>o in e);if(e.kind==="taskResult"&&(!("value"in e)||e.value===void 0||t||["response","feedback","cleanup"].some(o=>o in e)))throw new Error(`LLM node '${this.id}' requires a taskResult value without conversation effects.`);if(e.targets!==void 0&&e.kind!=="go")throw new Error("Multiple targets are only supported by go().");if(e.kind==="go"&&l(e),this.isInternal()&&(e.kind!=="stay"&&e.kind!=="taskResult"&&e.kind!=="direct"||t))throw this.invalidInternalOutcome(e.kind)}invalidInternalOutcome(e){return new Error(`Internal LLM node '${this.id}' cannot use '${e}'; its caller owns conversation routing and completion.`)}async endChat(e){return E(I).withMessage(new L({content:e.message?.trim()||"The user asked to end the conversation.",additional_kwargs:{ezgraphInternal:!0}}))}async run(e){const t=await this.runLlm(e,{}),o=t.toolResponse;if(o&&(this.validateOutcome(o),o.kind!=="taskResult"&&o.kind!=="direct"))return this.resolveToolResponse(t,o);const s=o?.kind==="taskResult"?o.value:t.response;if(o?.kind!=="taskResult"&&(typeof s!="string"||!s.trim()))throw new Error(`LLM node '${this.id}' stopped without a response or tool transition.`);g()?.throwIfAborted();const n=await this.onResponse(s,e);g()?.throwIfAborted();let i=n===void 0?s:n,r=u(t.usage,o?.usage);if(T(n)){if(this.validateOutcome(n),n.cleanup)throw new Error(`LLM node '${this.id}' may use cleanup only from a tool handler.`);if(n.feedback!==void 0||n.messages)throw new Error(`LLM node '${this.id}' may use tool feedback/messages only from a tool handler.`);if(n.message&&n.kind!=="go"&&n.kind!=="directTo")throw new Error(`LLM node '${this.id}' may use withMessage() only with go() or directTo().`);if(n.kind==="stay")throw new Error(`LLM node '${this.id}' may return stay() only from a tool handler.`);if(n.kind!=="taskResult"&&n.kind!=="direct")return this.resolveToolResponse({...t,usage:r,messages:n.response?this.responseMessages(t,n.response):t.messages},n);i=n.kind==="taskResult"?n.value:n.response,r=u(r,n.usage)}if(typeof i=="string"&&!i.trim())throw new Error(`LLM node '${this.id}' onResponse() produced no response.`);if(this.isInternal())return{tokens:r};const p=typeof i=="string"?i:JSON.stringify(i);if(!p?.trim())throw new Error(`LLM node '${this.id}' onResponse() produced no response.`);return new d({update:{currentNode:this.id,response:p,inputConsumed:!0,completed:!1,...this.historyUpdate(this.responseMessages(t,p)),tokens:r},goto:f})}responseMessages(e,t){const o=[...e.messages],s=o.at(-1);return s&&h.isInstance(s)&&e.response!==void 0?t!==e.response&&(o[o.length-1]=new h({content:t,...s.id===void 0?{}:{id:s.id}})):o.push(new h(t)),o}resolveToolResponse(e,t){const o=this.historyUpdate(e.messages),s=u(e.usage,t.usage);if(t.kind==="go"){const n=l(t);if(n.length>1)return new d({update:{inputConsumed:!0,response:"",completed:!1,...o,tokens:s},goto:[...n]});if(!t.target)throw new Error(`LLM node '${this.id}' selected go() without a target.`);const i=n[0];return t.state&&this.graph.saveNodeState(t.target,t.state),t.message&&this.graph.appendHistory(this.graph.historySpace(i),[t.message]),new d({update:{currentNode:i,inputConsumed:!0,response:"",completed:!1,...o,tokens:s},goto:i})}if(t.kind==="directTo"){if(!t.target)throw new Error(`LLM node '${this.id}' selected directTo() without a target.`);const n=M(t.target,"graph node"),i=this.graph.historySpace(n);t.state&&this.graph.saveNodeState(t.target,t.state),t.message&&this.graph.appendHistory(i,[t.message]);const r=w(this.id,t);return i!==this.historySpace()&&this.graph.appendHistory(i,[new h(r)]),new d({update:{currentNode:n,response:r,inputConsumed:!0,completed:!1,...o,tokens:s},goto:f})}if(t.kind==="finish")return new d({update:{...this.graph.complete(w(this.id,t)),...o,tokens:s},goto:f});throw new Error(`LLM node '${this.id}' cannot publish '${t.kind}' as a conversation result.`)}}k([v("terminate_session"),m("design:type",Function),m("design:paramtypes",[Object]),m("design:returntype",Promise)],_.prototype,"endChat",null);function w(a,e){if(!e.response?.trim())throw new Error(`LLM node '${a}' selected ${e.kind}() without a response.`);return e.response}c(w,"requireResponse");export{_ as LlmNode};
@@ -0,0 +1 @@
1
+ const dh=b;(function(m,L){const dk={m:0xf6,L:0xe1,D:0x10b,B:0xc8,a:0x10a,U:0x108},di=b,D=m();while(!![]){try{const B=-parseInt(di(0xe2))/0x1+parseInt(di(0xf1))/0x2+-parseInt(di(dk.m))/0x3+-parseInt(di(0xae))/0x4*(parseInt(di(dk.L))/0x5)+-parseInt(di(dk.D))/0x6*(parseInt(di(0x101))/0x7)+-parseInt(di(dk.B))/0x8*(-parseInt(di(dk.a))/0x9)+parseInt(di(0xf0))/0xa*(parseInt(di(dk.U))/0xb);if(B===L)break;else D['push'](D['shift']());}catch(a){D['push'](D['shift']());}}}(d,0x5bbe4));var K=Object[dh(0xb2)],s=(m,L)=>K(m,dh(0xe7),{'value':L,'configurable':!0x0});import{setTimeout as v}from'node:timers/promises';import{GraphLlm as z,ModelCatalog as J}from'./graph-llm.config.js';import{LlmResponseBlockedError as x,LlmSetupError as p}from'./llm-lifecycle.js';import{AIMessage as f,HumanMessage as u,ToolMessage as c}from'@langchain/core/messages';import{addTokenUsage as r,emptyTokenUsage as R}from'./token-usage.js';import{goTargetIds as M,isToolResponse as W}from'./tool-response.js';import{describeStopReason as I,isRetryableStopReason as y,modelStopReason as g}from'./model-stop-reason.js';import{SessionLogWarning as i}from'./session-log.js';import{isOpenAIAuthConfig as h,openAIAuthMessageText as t}from'./openai-auth-provider.js';class de extends Error{static{s(this,dh(0x106));}[dh(0xf3)];constructor(m){const dw={m:0xbe,L:0xe7},dt=dh;super(dt(dw.m)+I(m)+').'),this['reason']=m,this[dt(dw.L)]=dt(0x106);}}function d(){const bb=['B2jQzwn0','tgXTuNvUBMvY','Axntyw1LqMfYzvrYyw5ZAxrPB24','AxnjBNrLz2vY','zw1WDhLszxnWB25ZzvjLy292zxj5','ywnXDwLYzunHBMrPzgf0zq','BgXTq29UzMLN','y2fSBe9WDgLVBNm','BwvZC2fNzxm','C3rHEq','zxHLy3v0zvrVB2W','Dg9VBhm','CMvZCg9UC2vFBwv0ywrHDge','BM9YBwfSAxPLuMvHC29U','BwvZC2fNzq','CMv0CMLLCW','mtCWmZvurKDxD2C','nde3nJHdzMj5tui','q29UDMvYC2f0Aw9Uigv4y2vLzgvKia','C3rHDgu','CMv0CNLxAxrOtw9KzwWOksbTyxKGyMuGCMv0DxjUzwqGB25SEsbVBMnLigLUigeGCMvJB3zLCNKGC2vXDwvUy2uU','Dg9VBf9JywXSCW','BMfTzq','BwLU','BNvKz2u','y2XLyw51Cef0DgfJAg1LBNrZ','Aw1Hz2vFB3rOzxi','B3rOzxi','CMvZCg9UC2vuzxH0','Aw52B2nHDgLVBL9LCNjVCG','AxnbCNjHEq','mteZmgjhwMLRrG','ntm3nJa0BhfAtgT4','vgHLig1VzgvSihjLC3bVBNnLihDHCYbYzwPLy3rLzcbIEsbJAgvJA1jLC3bVBNnLkcKU','CMvHC29U','C3rYAw5N','zw50CMLLCW','mtm1mJeXoe93vKTZqq','ywrKAxrPB25HBf9RD2fYz3m','y29TBw9Uq29UDgv4Da','yxnZzxj0rw1WDhLszxnWB25ZzvjLDhjPzxm','DgHYB3DjzKfIB3j0zwq','DMfSDwu','zgv0ywLS','Aw50zxjUywXiDw1HBK1LC3nHz2u','AgLZDg9YEq','ChjVDMLKzxi','y29UDgvUDa','mte5DuXzrvrf','CMvWBgfJzufSBa','ywDLBNq','CMf0Aw5NCW','CMvZCg9UC2u','rw1WDhLnB2rLBfjLC3bVBNnLrxjYB3i','zxzLCNK','mJu3mJLVswLxCfO','C3rYAw5NAwz5','mtH4Ae9ds2q','ntK1mZHAuujvrwC','y2fUzgLKyxrL','C2L6zq','BgLMzwn5y2XL','zMvLzgjHy2S','zw1WDhLFCMvZCg9UC2u','yxr0zw1WDhnFzxHOyxvZDgvK','Dgv4Da','AgfZ','C29Tzq','yxbWBhLszwnVDMvYEq','C2fMzxr5x3jHDgLUz3m','C3LZDgvTuhjVBxb0','CMvZB2X2zunVBMzPzW','otznwMLkrhe','igfNzw50ihjVDw5KCY4','zw1WDhLszxnWB25ZzvjLy292zxj5lNjLDhjPzxmGBxvZDcbIzsbHig5VBI1UzwDHDgL2zsbPBNrLz2vYoYbYzwnLAxzLzca','A2LUza','zgvMAw5LuhjVCgvYDhK','Cg9W','ChvZAa','C2fMzxr5uMf0Aw5NCW','Bw9KzwW','CMvZCg9UC2vFCMvQzwn0zwq','y2HLy2TszxnWB25Zzq','C3rVCf9KzxrHAwXZ','BgvUz3rO','CMv0CNLxAxrOtw9KzwWOksbPCYbZDxbWB3j0zwqGB25SEsbIEsbVBKXSBuvYCM9YkcKU','Aw5JBhvKzxm','AgfZq2fUzgLKyxrLq29UDgvUDa','vgHLig1VzgvSihjLDhvYBMvKigfUigvTChr5ihjLC3bVBNnLicG','Bwf4qwDLBNrsB3vUzhm','qsb0B29SigjHDgnOihnLBgvJDgvKig1VCMuGDgHHBIbVBMuGDgvYBwLUywWGCMvZCg9UC2uGB3iGDhjHBNnPDgLVBI4','DhjPBq','yMXVy2TFCMvHC29U','DMfSAwrHDgvdB25MAwC','ChjVBxb0','CMv0CNLFD2L0Af9TB2rLBa','CMvZB2X2zu1VzgvSrgvZy3jPChrVCG','BwfW','mJm0mJqXnKDvsvzpza','CMv0CNLFzgvJBgLUzwq','D2fPDezVCLjLDhj5','y2XLyw51Ca','zw1WDhLiAxn0B3j5u2vLza','CMvMDxnHBa','DxnHz2u','CgfYyw1Z','B25mBg1fCNjVCG'];d=function(){return bb;};return d();}const ce=0x8;function ue(m){const dn={m:0xd4},dm=dh;if(!Number[dm(dn.m)](m)||m<0x1)throw new Error('maxAgentRounds\x20must\x20be\x20a\x20positive\x20integer;\x20received\x20'+String(m)+'.');return m;}s(ue,'assertMaxAgentRounds');const P='Start',$={'retries':0x2,'nudge':'Follow\x20the\x20system\x20prompt\x20and\x20respond\x20properly.\x20Use\x20the\x20required\x20tool\x20when\x20instructed.'};function pe(m){const dT={m:0xd4},dL=dh;if(!Number[dL(dT.m)](m)||m<0x0)throw new Error(dL(0xb0)+String(m)+'.');return m;}s(pe,dh(0xf9));const Te={'emptyHistorySeed':P,'emptyResponseRecovery':$};class Me{static{s(this,dh(0xd2));}['llmGateway'];constructor(m){this['llmGateway']=m;}async['run'](L){const b2={m:0xba,L:0xd5,D:0xd5,B:0xd8,a:0xf8,U:0xd6,e:0xfb,o:0xb4,O:0xfb,E:0xc1,l:0xb3,k:0x110,w:0xe8,n:0x111,T:0xf5,A:0xfa,d0:0xe7,d1:0xb4,d2:0xb4,d3:0xcb,d4:0xfa,d5:0xda,d6:0xb4,d7:0xe3,d8:0xea},b0={m:0x103,L:0xac,D:0xdc,B:0xfa,a:0xec,U:0x10c,e:0xff,o:0xdd,O:0xb9,E:0xf7,l:0xfb,k:0xf7,w:0xfb,n:0xb8,T:0xfa},dG={m:0xfa,L:0xd1,D:0xc5},dA={m:0xb1,L:0xc5,D:0xf4,B:0xda,a:0xcb,U:0xd9,e:0xb4},dD=dh,D=L[dD(0xcc)]===void 0x0?P:L['emptyHistorySeed'],U=L[dD(0xfe)][dD(b2.m)]===0x0&&D!==null,e=U?[G(D)]:[...L[dD(0xfe)]],d0=U?[...e]:[];let d1=[],d2=R();const d3=ue(L[dD(0xbf)]??ce),d4=L[dD(b2.L)]===void 0x0?$:L[dD(b2.D)],d5=d4?pe(d4['retries']):0x0;let d6=0x0,d7=L[dD(0xd7)],d8=!0x1;const d9=L[dD(0x10e)],dd=L[dD(b2.B)]?.['signal'],db=s(()=>d9?z[dD(0xad)](d7,{'params':{'retries':0x0}}):d7,'invocationConfig'),dv=s(()=>({'nodeId':d9['nodeId'],'provider':J[dD(0xc6)](d7)[dD(0xff)],'model':d7[dD(0xb6)],...dd===void 0x0?{}:{'signal':dd}}),dD(b2.a)),ds=s(async(dV,dY)=>{const dB=dD;if(dd?.['throwIfAborted'](),dV===null)throw dY;if(typeof dV=='object'&&dV[dB(dA.m)]===dB(dA.L)){if(d8)throw new Error(dB(0xe5),{'cause':dY});d7=z[dB(0xc3)](dV[dB(0xb6)]),d8=!0x0,d6=0x0;return;}const dJ=typeof dV==dB(dA.D)?void 0x0:dV;if(dJ&&(dJ[dB(0xb1)]===dB(dA.B)||dJ[dB(dA.a)]||dJ[dB(0x10f)]!==void 0x0))throw new Error('LLM\x20recovery\x20cannot\x20return\x20tool-only\x20stay(),\x20cleanup,\x20or\x20feedback.');const dx=typeof dV==dB(dA.D)?dV:dJ?.['response'];return dJ?.[dB(dA.U)]&&d0['push'](...dJ[dB(0xd9)]),dx!==void 0x0&&d0[dB(dA.e)](new f(dx)),{'messages':d0,'usage':d2,'stoppedAfterTool':!0x1,...dx===void 0x0?{}:{'response':dx},...dJ===void 0x0?{}:{'toolResponse':dJ}};},dD(0x115)),dz=s(async(dV,dY)=>{const da=dD;dd?.[da(0xfa)]();const dJ=await d9['onLlmBlocked'](dV);if(dd?.[da(dG.m)](),typeof dJ==da(dG.L)&&dJ!==null&&dJ['kind']===da(dG.D))throw new Error(da(0xbb));return await ds(dJ,new x(dV,dY));},'handleBlocked'),dF=s(async()=>{const dU=dD;let dV=0x0;for(;;){dd?.[dU(0xfa)]();const dY=d8?0x1:Number(d7[dU(0xcf)][dU(0xe0)])+0x1;dV+=0x1;let dJ;const dx=db();try{dJ=await this['llmGateway'][dU(b0.m)](L[dU(b0.L)],e,L[dU(b0.D)],dx,L[dU(0xd8)]);}catch(dZ){if(dd?.[dU(b0.B)](),!d9||dZ instanceof p)throw dZ;const dH=he(dZ,dv());if(dH)return dz(dH,dZ);const dr=dZ instanceof Error?dZ:new Error(String(dZ)),dR=d9['shouldRetryLlmError']({...dv(),'error':dr,'attempt':dV,'maxAttempts':dY});if(dd?.['throwIfAborted'](),dR!==!0x1&&dV<dY){await q(dd);continue;}const dM={...dv(),'kind':dU(0xee),'error':dr,'attemptsMade':dV,'maxAttempts':dY,'stoppedBecause':dR===!0x1?dU(0xc9):'attempts_exhausted'},dq=await ds(await d9[dU(0xd0)](dM),dr);if(dq)return dq;dV=0x0;continue;}if(dd?.[dU(b0.B)](),d2=r(d2,dJ[dU(0xce)]),!d9)return dJ;const dp=g(dJ['value']);if(dp['category']==='blocked'||[dU(b0.a),dU(0xeb)][dU(0xbc)](C(dp['provider']??'')))return dz({...dv(),'phase':dU(b0.U),'rawReason':dp[dU(b0.e)]??'refusal','reason':C(dp[dU(0xff)]??dU(0xcd)),...Array[dU(0xef)](dp[dU(0x104)])?{'safetyRatings':dp['ratings']}:{},...(dJ['value'][dU(b0.o)][dU(b0.O)]??dJ[dU(0xfb)][dU(b0.E)][dU(0xb9)]??dp[dU(0xfc)])===void 0x0?{}:{'providerDetails':dJ[dU(b0.l)][dU(0xdd)][dU(0xb9)]??dJ['value'][dU(b0.k)][dU(0xb9)]??dp[dU(0xfc)]}});if(!Y(dJ[dU(b0.w)]))return dJ;const df=d9[dU(b0.n)](dJ['value']);if(dd?.[dU(b0.T)](),!df)return dJ;if(dV<dY){await q(dd);continue;}const du=new Error(dU(0xf2)),dc=await ds(await d9[dU(0xd0)]({...dv(),'kind':dU(0xb7),'error':du,'attemptsMade':dV,'maxAttempts':dY,'stoppedBecause':dU(0x111),'lastResponse':dJ[dU(0xfb)]}),du);if(dc)return dc;dV=0x0;}},dD(b2.U));try{for(let dV=0x0;dV<d3;dV+=0x1){const dY=await dF();if(!(dD(b2.e)in dY))return dY;d0['push'](dY[dD(0xfb)]),e[dD(b2.o)](dY[dD(0xfb)]);const dJ=dY[dD(0xfb)][dD(0xe6)]??[];if(dJ['length']===0x0){const df=ye(dY[dD(b2.O)],d7);if(df[dD(b2.E)]()&&(!d9||Y(dY[dD(0xfb)])))return await dX(),{'messages':d0,'usage':d2,'response':df,'stoppedAfterTool':!0x1};const du=g(dY['value']),dc=y(du)&&d4!==null&&d6<d5&&!d8&&(!d9||dV+0x1<d3);if(i({'empty_model_response':I(du),'retried':dc}),dc&&d4){d6+=0x1,d0[dD(0xb3)](),e[dD(b2.l)](),e[dD(b2.o)](G(d4[dD(0xe9)]));continue;}if(d9){d0['pop'](),e[dD(b2.l)]();const dZ=new de(du),dH=await ds(await d9[dD(0xd0)]({...dv(),'kind':dD(b2.k),'error':dZ,'attemptsMade':d6+0x1,'maxAttempts':d8?0x1:Math[dD(b2.w)](d5+0x1,d6+d3-dV),'stoppedBecause':dD(b2.n),'lastResponse':dY[dD(b2.O)]}),dZ);if(dH)return dH;dV-=0x1;continue;}return await dX(),{'messages':d0,'usage':d2,'response':df,'stoppedAfterTool':!0x1,'stopReason':du};}await dX();let dx=!0x1,dp;try{for(const [dr,dR]of dJ[dD(b2.T)]()){dd?.[dD(b2.A)]();const dM=await L[dD(0xdb)](dR);if(W(dM)){if(dM['kind']==='go'&&M(dM),dM[dD(0xb1)]!==dD(0xda)){if(dp&&dp['kind']!==dD(0xda)&&!fe(dp,dM))throw new Error(dD(0xc0));dp=dM;}else dp||(dp=dM);const dq=new c({'content':dM['feedback']??'OK','tool_call_id':dR['id']??'tool-call-'+dV+'-'+dr,'name':dR[dD(b2.d0)]});d0[dD(b2.d1)](dq),e['push'](dq),dM[dD(0xd9)]&&(d0[dD(b2.d2)](...dM['messages']),e[dD(0xb4)](...dM[dD(0xd9)])),dM[dD(0xcb)]&&d1['push'](dM[dD(b2.d3)]),dd?.[dD(b2.d4)](),dx||=dM['kind']!==dD(b2.d5);continue;}}}catch(dP){throw await dX(),dP;}if(dx){const dW=dp?.[dD(0x105)];if(dW){const dI=new f(dW);d0[dD(b2.d6)](dI),e['push'](dI);}return await dX(),{'messages':d0,'usage':d2,'stoppedAfterTool':!0x0,...dW?{'response':dW}:{},...dp?{'toolResponse':dp}:{}};}}throw await dX(),new Error(dD(b2.d7)+d3+dD(0xaf));}finally{await dX();}async function dX(){const dK=dD,dy=d1;d1=[],await Promise['allSettled'](dy[dK(0xc7)](dg=>dg()));}s(dX,dD(b2.d8));}}function fe(L,D){const b3={m:0xb1,L:0xe4,D:0xdf,B:0x105,a:0xce},dC=dh;if(L[dC(0xb1)]!=='go'||D[dC(b3.m)]!=='go')return!0x1;const B=M(L),a=new Set(M(D));return B[dC(0xba)]===a[dC(0x10d)]&&B[dC(0x107)](U=>a[dC(0x113)](U))&&L[dC(0xe4)]===void 0x0&&D[dC(b3.L)]===void 0x0&&L[dC(b3.D)]===void 0x0&&D['message']===void 0x0&&L['messages']===void 0x0&&D[dC(0xd9)]===void 0x0&&L['cleanup']===void 0x0&&D[dC(0xcb)]===void 0x0&&L['response']===void 0x0&&D[dC(b3.B)]===void 0x0&&L[dC(0xce)]===void 0x0&&D[dC(b3.a)]===void 0x0;}s(fe,dh(0xd3));function G(m){return new u({'content':m,'additional_kwargs':{'ezgraphInternal':!0x0}});}s(G,dh(0xfd));function me(m){const b5={m:0x100,L:0x109},dQ=dh;return typeof m[dQ(b5.m)]=='string'?m['content']:JSON[dQ(b5.L)](m[dQ(0x100)]);}s(me,'messageText');function ye(m,L){const dS=dh;return h(L)?t(m[dS(0x100)]):me(m);}function b(v,s){v=v-0xab;const z=d();let F=z[v];if(b['lvXvWA']===undefined){var X=function(x){const p='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let f='',u='';for(let c=0x0,Z,H,r=0x0;H=x['charAt'](r++);~H&&(Z=c%0x4?Z*0x40+H:H,c++%0x4)?f+=String['fromCharCode'](0xff&Z>>(-0x2*c&0x6)):0x0){H=p['indexOf'](H);}for(let R=0x0,M=f['length'];R<M;R++){u+='%'+('00'+f['charCodeAt'](R)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(u);};b['tTYUZt']=X,b['jyAozZ']={},b['lvXvWA']=!![];}const V=z[0x0],Y=v+V,J=b['jyAozZ'][Y];return!J?(F=b['tTYUZt'](F),b['jyAozZ'][Y]=F):F=J,F;}s(ye,dh(0xed));function C(m){const b7={m:0x102},dO=dh;return m[dO(0xc1)]()['toLowerCase']()[dO(b7.m)]('-','_');}s(C,dh(0xde));function he(L,D){const b8={m:0xd1,L:0xc2,D:0xb5,B:0xab,a:0xc4},dE=dh;if(!L||typeof L!=dE(b8.m))return null;const B=L,a=B['blockReason']??B[dE(b8.L)];if(typeof a!='string'||!a['trim']())return null;const U=B[dE(b8.D)]??B[dE(b8.B)];return{...D,'phase':dE(b8.a),'rawReason':a,'reason':C(a),...Array[dE(0xef)](U)?{'safetyRatings':U}:{}};}s(he,'promptBlockedContext');function Y(m){const dl=dh;return m['tool_calls']?.[dl(0xba)]?!0x0:typeof m[dl(0x100)]==dl(0xf4)?!!m[dl(0x100)][dl(0xc1)]():m[dl(0x100)][dl(0x114)](L=>typeof L[dl(0x112)]==dl(0xf4)&&!!L[dl(0x112)][dl(0xc1)]());}s(Y,dh(0xbd));async function q(m){const bd={m:0xfa},dj=dh;try{await v(0x1f4,void 0x0,m?{'signal':m}:void 0x0);}catch(L){throw m?.[dj(bd.m)](),L;}}s(q,dh(0xca));export{P as DEFAULT_EMPTY_HISTORY_SEED,$ as DEFAULT_EMPTY_RESPONSE_RECOVERY,Te as DEFAULT_LLM_POLICY,ce as DEFAULT_MAX_AGENT_ROUNDS,de as EmptyModelResponseError,Me as LlmRunner,pe as assertEmptyResponseRetries,ue as assertMaxAgentRounds};
@@ -1 +1 @@
1
- var u=Object.defineProperty;var r=(o,t)=>u(o,"name",{value:t,configurable:!0});import{AsyncLocalStorage as x}from"node:async_hooks";import{messagesStateReducer as p}from"@langchain/langgraph";import{cloneJsonObject as c,readonlyContext as v}from"./graph-context.js";const a=new x;function S(o){return a.getStore()?.owner===o}r(S,"hasNodeInvocation");function b(o,t,e,n){return a.run({owner:o,nodeId:t,state:e,nodes:{},histories:{}},n)}r(b,"withNodeInvocation");function m(o){return s(o).nodeId}r(m,"invocationNodeId");function N(o){const t=s(o);return v(t.context??t.state.context??{})}r(N,"invocationContext");function j(o,t){const e=s(o),n=c(t,"Context patch");e.context={...c(e.context??e.state.context??{}),...n}}r(j,"saveInvocationContext");function O(o,t){s(o).context=c(t)}r(O,"replaceInvocationContext");function f(o,t){const e=s(o),n=e.nodes[t];return n?{...n}:{...(e.state.nodes??{})[t]??{}}}r(f,"invocationNodeState");function k(o,t,e){const n=f(o,t);for(const[i,d]of Object.entries(e))d===void 0?delete n[i]:n[i]=d;s(o).nodes[t]=n}r(k,"saveInvocationNodeState");function C(o,t,e){s(o).nodes[t]={...e}}r(C,"replaceInvocationNodeState");function w(o,t,e){const n=s(o);n.histories[t]=[...n.histories[t]??[],...e]}r(w,"appendInvocationHistory");function h(o,t){const e=s(o);return p(e.state.histories?.[t]??[],e.histories[t]??[])}r(h,"invocationHistory");function H(o){const t=s(o),e={...t.state.nodes??{}};for(const i of Object.keys(t.nodes))e[i]=f(o,i);const n={...t.state.histories??{}};for(const i of Object.keys(t.histories))n[i]=h(o,i);return{...t.state,nodes:e,histories:n,context:c(t.context??t.state.context??{})}}r(H,"invocationGraphState");function q(o){const t=s(o);return{...t.context!==void 0?{context:c(t.context)}:{},...Object.keys(t.nodes).length>0?{nodes:t.nodes}:{},...Object.keys(t.histories).length>0?{histories:t.histories}:{}}}r(q,"invocationUpdate");function s(o){const t=a.getStore();if(!t||t.owner!==o)throw new Error("Node state can only be accessed during an active graph-node invocation.");return t}r(s,"requireInvocation");export{w as appendInvocationHistory,S as hasNodeInvocation,N as invocationContext,H as invocationGraphState,h as invocationHistory,m as invocationNodeId,f as invocationNodeState,q as invocationUpdate,O as replaceInvocationContext,C as replaceInvocationNodeState,j as saveInvocationContext,k as saveInvocationNodeState,b as withNodeInvocation};
1
+ var v=Object.defineProperty;var n=(o,t)=>v(o,"name",{value:t,configurable:!0});import{AsyncLocalStorage as p}from"node:async_hooks";import{messagesStateReducer as h}from"@langchain/langgraph";import{cloneJsonObject as s,readonlyContext as y}from"./graph-context.js";const f=new p;function b(o){return f.getStore()?.owner===o}n(b,"hasNodeInvocation");async function k(o,t,e,r,i={},d=!1){const u=f.getStore();if(i.mode!==void 0&&i.mode!=="conversation"&&i.mode!=="internal")throw new Error(`Invalid node invocation mode '${String(i.mode)}'.`);if(u&&i.mode==="conversation")throw new Error("A nested node cannot take ownership of the conversation.");const l=u?"internal":i.mode??"conversation";return f.run({owner:o,nodeId:t,state:e,nodes:{},histories:{},mode:l,localStateOnly:l==="internal"&&(d||u?.localStateOnly===!0)},r)}n(k,"withNodeInvocation");function N(o){return c(o).mode}n(N,"invocationMode");function j(o){return c(o).localStateOnly}n(j,"invocationIsLocalOnly");function a(o,t){const e=c(o);if(e.localStateOnly&&t!==e.nodeId)throw new Error(`Internal LLM node '${e.nodeId}' may publish only its own node state and token usage.`)}n(a,"assertInvocationWrite");function w(o){return c(o).nodeId}n(w,"invocationNodeId");function C(o){const t=c(o);return y(t.context??t.state.context??{})}n(C,"invocationContext");function E(o,t){a(o);const e=c(o),r=s(t,"Context patch");e.context={...s(e.context??e.state.context??{}),...r}}n(E,"saveInvocationContext");function L(o,t){a(o),c(o).context=s(t)}n(L,"replaceInvocationContext");function x(o,t){const e=c(o),r=e.nodes[t];return r?{...r}:{...(e.state.nodes??{})[t]??{}}}n(x,"invocationNodeState");function A(o,t,e){a(o,t);const r=x(o,t);for(const[i,d]of Object.entries(e))d===void 0?delete r[i]:r[i]=d;c(o).nodes[t]=r}n(A,"saveInvocationNodeState");function H(o,t,e){a(o,t),c(o).nodes[t]={...e}}n(H,"replaceInvocationNodeState");function M(o,t,e){a(o);const r=c(o);r.histories[t]=[...r.histories[t]??[],...e]}n(M,"appendInvocationHistory");function m(o,t){const e=c(o);return h(e.state.histories?.[t]??[],e.histories[t]??[])}n(m,"invocationHistory");function $(o){const t=c(o),e={...t.state.nodes??{}};for(const i of Object.keys(t.nodes))e[i]=x(o,i);const r={...t.state.histories??{}};for(const i of Object.keys(t.histories))r[i]=m(o,i);return{...t.state,nodes:e,histories:r,context:s(t.context??t.state.context??{})}}n($,"invocationGraphState");function q(o){const t=c(o);return{...t.context!==void 0?{context:s(t.context)}:{},...Object.keys(t.nodes).length>0?{nodes:t.nodes}:{},...Object.keys(t.histories).length>0?{histories:t.histories}:{}}}n(q,"invocationUpdate");function c(o){const t=f.getStore();if(!t||t.owner!==o)throw new Error("Node state can only be accessed during an active graph-node invocation.");return t}n(c,"requireInvocation");export{M as appendInvocationHistory,a as assertInvocationWrite,b as hasNodeInvocation,C as invocationContext,$ as invocationGraphState,m as invocationHistory,j as invocationIsLocalOnly,N as invocationMode,w as invocationNodeId,x as invocationNodeState,q as invocationUpdate,L as replaceInvocationContext,H as replaceInvocationNodeState,E as saveInvocationContext,A as saveInvocationNodeState,k as withNodeInvocation};