@picoflow/ezgraph 0.0.12 → 0.0.13

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
@@ -74,6 +74,36 @@ export const WeatherGraphState = createGraphStateAnnotation(
74
74
  export type WeatherGraphStateType = typeof WeatherGraphState.State;
75
75
  ```
76
76
 
77
+ ## Persist graph-wide runtime context
78
+
79
+ Every new graph state includes an empty `context` object, saved as
80
+ `SessionDocument.graph.context`. During a node invocation, use the graph facade:
81
+
82
+ ```ts
83
+ this.graph.saveContext({ rating: { calculatedAt: now.toISOString() } });
84
+ const context = this.graph.getContext();
85
+ ```
86
+
87
+ The same APIs are available on `BaseGraph` for graph-owned policies running
88
+ inside a node invocation. `saveContext()` replaces supplied top-level branches
89
+ and preserves the others; nested objects and arrays are replaced, not deep-merged.
90
+ `null` is ordinary data. The root must be an object containing only JSON values.
91
+ Writes are validated and cloned; reads are detached, deeply frozen snapshots.
92
+
93
+ Changes become durable with a successful node outcome and its checkpoint.
94
+ A failed node discards its staged changes; earlier checkpoints remain saved.
95
+ Only one node may write context per parallel superstep; parallel workers should
96
+ write node state and consolidate global context in a join node. Custom state
97
+ schemas must declare `context: new GraphContextChannel()`;
98
+ `createGraphStateAnnotation()` does so automatically. `GraphContextChannel` is
99
+ exported by the package for custom `Annotation.Root()` schemas.
100
+ Outside execution, read `GraphEngine.getSession(id).graph.context` from the
101
+ returned session document. Older version-16 documents restore with `{}`.
102
+
103
+ Context holds shared runtime metadata. Request options remain in `config`, and
104
+ node-owned business facts remain in `nodes`. Context is not automatically sent
105
+ to the model.
106
+
77
107
  ## Write an LLM node
78
108
 
79
109
  `LlmNode` supports both one-request extraction and multi-turn chat. A single
@@ -1 +1 @@
1
- var c=Object.defineProperty;var n=(o,e)=>c(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 E,stableClassId as a}from"./stable-id.js";class d{static{n(this,"BaseGraph")}llmGateway;static id(){return this.name}static assertName(e){return d.assertId(e)}static assertId(e){return E(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=v(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:n(s=>this.onLlmBlocked(s),"onLlmBlocked"),shouldRetryLlmError:n(s=>this.shouldRetryLlmError(s),"shouldRetryLlmError"),onLlmError:n(s=>this.onLlmError(s),"onLlmError")})}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}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 i=await s.migrate(r);if(i.graph.id!==this.id)throw new Error(`Graph '${this.id}' migration from schema version ${t} changed the persisted graph ID.`);r={...i,graph:{...i.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 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}}n(v,"resolveConversationPolicy");function R(o){return Object.fromEntries((o??[]).map(([e,r])=>[a(e,"graph node"),r]))}n(R,"historySpaceMap");function N(o,e){const r=new Map;let t;for(const s of o??[]){const i=m(s.from);if(i>=e)throw new Error(`A graph migration from version ${i} cannot target schema version ${e}.`);if(r.has(i))throw new Error(`More than one graph migration starts at version ${i}.`);if(t!==void 0&&i!==t+1)throw new Error(`Graph migrations must be ordered and contiguous; version ${t} must be followed by ${t+1}.`);r.set(i,s),t=i}return r}n(N,"migrationMap");export{d 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 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};
@@ -0,0 +1 @@
1
+ var O=Object.defineProperty;var a=(o,r)=>O(o,"name",{value:r,configurable:!0});import{BaseChannel as h,InvalidUpdateError as m}from"@langchain/langgraph";class w extends h{static{a(this,"GraphContextChannel")}lc_graph_name="GraphContextChannel";value;constructor(r={}){super(),this.value=f(r)}fromCheckpoint(r){return new w(r===void 0?{}:r)}update(r){if(r.length===0)return!1;if(r.length!==1)throw new m("Graph context can only receive one value per step. Parallel writers must consolidate context in a join node.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=f(r[0]),!0}get(){return g(this.value)}checkpoint(){return f(this.value)}isAvailable(){return!0}}function f(o,r="Graph context"){const c=new Set;function n(e,t){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="object"||e===null)throw new TypeError(`${t} must contain only valid JSON values.`);if(c.has(e))throw new TypeError(`${t} contains a circular reference.`);if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError(`${t} must not contain symbol properties.`);const i=Array.isArray(e),u=Object.getPrototypeOf(e);if(!i&&u!==Object.prototype&&u!==null)throw new TypeError(`${t} must contain plain JSON objects.`);c.add(e);try{if(i){if(Object.keys(e).length!==e.length||Object.getOwnPropertyNames(e).length!==e.length+1)throw new TypeError(`${t} must be a dense JSON array without extra properties.`);return Array.from({length:e.length},(s,l)=>{const y=Object.getOwnPropertyDescriptor(e,String(l));if(!y||!("value"in y))throw new TypeError(`${t}[${l}] must be a JSON value.`);return n(y.value,`${t}[${l}]`)})}const b={};for(const s of Object.getOwnPropertyNames(e)){const l=Object.getOwnPropertyDescriptor(e,s);if(!l.enumerable||!("value"in l))throw new TypeError(`${t}.${s} must be an enumerable JSON value.`);Object.defineProperty(b,s,{value:n(l.value,`${t}.${s}`),enumerable:!0,configurable:!0,writable:!0})}return b}finally{c.delete(e)}}if(a(n,"clone"),!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`${r} must be a JSON object.`);return n(o,r)}a(f,"cloneJsonObject");function g(o){function r(n){if(!(n===null||typeof n!="object")){for(const e of Object.values(n))r(e);Object.freeze(n)}}a(r,"freeze");const c=f(o);return r(c),c}a(g,"readonlyContext");export{w as GraphContextChannel,f as cloneJsonObject,g as readonlyContext};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var i=(n,e)=>E(n,"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 u,isCommand as w}from"@langchain/langgraph";import{GraphLlm as m}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 A}from"./turn-context.js";import{combineGraphNodeUpdates as b}from"./node-outcome.js";import{parseJsonObjectResponse as S}from"./json-response.js";import{stableClassId as f}from"./stable-id.js";import{SessionLogWarning as G}from"./session-log.js";import{isToolResponse as N,stay as k}from"./tool-response.js";import{invocationGraphState as I,hasNodeInvocation as M,invocationHistory as P,invocationNodeState as _,invocationUpdate as D,appendInvocationHistory as U,replaceInvocationNodeState as j,saveInvocationNodeState as x,withNodeInvocation as J}from"./node-invocation.js";import{DecisionConfigurationError as q,resolveDecisionOptions as F}from"./decision/decision-types.js";import{GRAPH_NODE_LOCAL_STATE as fe}from"./node-outcome.js";const z=Symbol("GRAPH_NODE_CLASS"),g=Symbol("graph-node-tool-handlers");function ce(n){if(!n.trim())throw new Error("A tool handler requires a tool name.");return(e,t)=>{const o=Reflect.getOwnMetadata(g,e)??[];if(o.some(r=>r.toolName===n))throw new Error(`Tool '${n}' already has a handler.`);o.push({toolName:n,methodName:t}),Reflect.defineMetadata(g,o,e)}}i(ce,"Tool");class C{static{i(this,"GraphNode")}llmGateway;runtime;static[z]=!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=f(o,"graph node")}get graph(){return this.runtime}defineTool(){return[]}getLlmConfig(){return{}}route(e){throw new Error(`Graph node '${this.id}' does not define a branch route.`)}async handleTool(e,t,o){const r=this.toolHandler(t.name);if(!r)return this.rejectToolCall(t.name,`Unsupported tool '${t.name}'.`);const d=this.runtime.requireTool(r.toolName),s=X(t.args);if(!s.ok)return this.rejectToolCall(r.toolName,s.error);const a=d.schema.safeParse(s.value);if(!a.success)return this.rejectToolCall(r.toolName,Y(a.error));const h=a.data,l=this[r.methodName];if(!l)throw new Error(`Tool '${r.toolName}' is decorated on missing method '${String(r.methodName)}'.`);const v=await l.call(this,h,o,e);if(N(v))return v;throw new Error(`Tool '${r.toolName}' on '${this.id}' must return a ToolResponse.`)}rejectToolCall(e,t){return G({tool_call:t,node:this.id,tool:e}),k(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=W(t),r=await this.resolveJsonResponse(e,o);if(this.runtime.stageNodeEntries(r.nodes),this.usesChatModel()){const s=this.runtime.resolveLlmConfig(this.getLlmConfig()),a=V(s,this.runtime.resolveLlmConfig()),h=(e.nodes??{})[this.id];(!a||h?.model!==void 0)&&this.runtime.saveNode(this.id,{model:a?void 0:m.modelMetadata(s)})}const d=b(r,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 r=await this.onEmptyModelResponse({state:e,conversation:o,reason:o.stopReason});return{...o,response:r}}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(r=>this.handleTool(e,r,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(!N(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=f(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 r=y(this.id,e);return this.graph.appendHistory(o,[new p(r)]),new c({update:{currentNode:t,response:r,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:u})}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=y(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:u})}if(e.kind==="finish"){const t=y(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:u})}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 S(t.response??""),t}catch(o){const r=await this.onInvalidJsonResponse({state:e,update:t,response:t.response??"",error:o instanceof Error?o:new Error(String(o))});return(r.completed===!0||r.response)&&S(r.response??""),r}}toolHandlers(){let e=Object.getPrototypeOf(this);const t=[];for(;e&&e!==C.prototype;){const r=Reflect.getOwnMetadata(g,e)??[];t.push(...r),e=Object.getPrototypeOf(e)}const o=new Set;for(const r of t){if(o.has(r.toolName))throw new Error(`Graph node '${this.id}' has more than one handler for tool '${r.toolName}'.`);o.add(r.toolName)}return t}}function V(n,e){return n.model===e.model&&JSON.stringify(m.parameters(n))===JSON.stringify(m.parameters(e))}i(V,"sameLlmConfig");class le extends T{static{i(this,"GraphNodeRuntime")}defaultLlmConfig;historySpaces;responseMode;maxAgentRounds;conversationPolicy;decisionOptions;decisionErrorHandler;llmLifecycle;tools=new Map;constructor(e,t,o={},r="chat",d=L,s=H,a={},h,l){super(e),this.defaultLlmConfig=t,this.historySpaces=o,this.responseMode=r,this.maxAgentRounds=d,this.conversationPolicy=s,this.decisionOptions=a,this.decisionErrorHandler=h,this.llmLifecycle=l}llmCallOptions(){const{llmTimeoutMs:e}=this.conversationPolicy,t=A();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 m.resolveConfig(this.defaultLlmConfig,e)}resolveDecisionOptions(e={}){return F(this.decisionOptions,e)}decisionProviderResolver;attachDecisionProviderResolver(e){this.decisionProviderResolver=e}resolveDecisionProvider(e){if(!this.decisionProviderResolver)throw new q(`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 r=this.tools.get(o.name);if(r)throw new Error(`Tool '${o.name}' is defined by both '${r.owner}' and '${e}'.`);this.tools.set(o.name,{definition:o,owner:e})}}requireTool(e){const t=this.tools.get(e);if(!t)throw new Error(`Tool '${e}' is not defined in this graph.`);return t.definition}input(e){return this.latestInput({messages:e.histories[this.historySpace(e.currentNode)]??[]})}getConversation(e){const o=(this.hasInvocation()?this.invocationHistory(e):[]).filter(r=>R.isInstance(r)&&r.additional_kwargs?.ezgraphInternal!==!0).map(r=>typeof r.content=="string"?r.content:JSON.stringify(r.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 J(this,e,t,o)}nodeState(e){return _(this,e)}hasInvocation(){return M(this)}graphState(){return I(this)}appendHistory(e,t){U(this,e,t)}invocationHistory(e){return P(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 x(this,e,t),{nodes:{[e]:this.nodeState(e)}}}saveNodeState(e,t){this.saveNode(f(e,"graph node"),t)}removeNode(e,...t){return this.saveNode(e,Object.fromEntries(t.map(o=>[o,void 0])))}}function W(n){if(!w(n))return n;if(Array.isArray(n.update))throw new Error("GraphNode Command updates must be state objects.");return n.update??{}}i(W,"commandUpdate");function y(n,e){if(!e.response?.trim())throw new Error(`Graph node '${n}' selected ${e.kind}() without a response.`);return e.response}i(y,"requireNodeResponse");function X(n){if(typeof n!="string")return{ok:!0,value:n};try{return{ok:!0,value:JSON.parse(n)}}catch(e){return{ok:!1,error:`Tool arguments were not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}i(X,"coerceToolArgs");function Y(n){return n.issues.map(e=>e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message).join("; ")}i(Y,"formatToolArgumentError");export{z as GRAPH_NODE_CLASS,fe as GRAPH_NODE_LOCAL_STATE,C as GraphNode,le as GraphNodeRuntime,ce as Tool};
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 +1 @@
1
- var u=Object.defineProperty;var e=(d,n)=>u(d,"name",{value:n,configurable:!0});import{Annotation as o,messagesStateReducer as c}from"@langchain/langgraph";import{replaceNodeStates as a}from"./node-state.js";import{addTokenUsage as f,emptyTokenUsage as i}from"./token-usage.js";import{addDecisionUsage as m,emptyDecisionUsage as p}from"./decision/decision-types.js";const A="end";function N(d,n){return o.Root({histories:o({reducer:e((t,r)=>l(t??{},r??{}),"reducer"),default:e(()=>({}),"default")}),currentNode:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>d,"default")}),config:o({reducer:e((t,r)=>({...t,...r}),"reducer"),default:e(()=>({}),"default")}),nodes:o({reducer:a,default:e(()=>n?n():{},"default")}),tokens:o({reducer:f,default:i}),decisionUsage:o({reducer:m,default:p}),inputConsumed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")}),response:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>"","default")}),completed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")})})}e(N,"createGraphStateAnnotation");function l(d,n){const t={...d};for(const[r,s]of Object.entries(n))t[r]=c(t[r]??[],s);return t}e(l,"mergeHistories");export{A as GRAPH_END_NODE,N as createGraphStateAnnotation};
1
+ var u=Object.defineProperty;var e=(d,n)=>u(d,"name",{value:n,configurable:!0});import{Annotation as o,messagesStateReducer as a}from"@langchain/langgraph";import{GraphContextChannel as c}from"./graph-context.js";import{replaceNodeStates as f}from"./node-state.js";import{addTokenUsage as i,emptyTokenUsage as m}from"./token-usage.js";import{addDecisionUsage as p,emptyDecisionUsage as l}from"./decision/decision-types.js";const A="end";function C(d,n){return o.Root({context:new c,histories:o({reducer:e((t,r)=>g(t??{},r??{}),"reducer"),default:e(()=>({}),"default")}),currentNode:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>d,"default")}),config:o({reducer:e((t,r)=>({...t,...r}),"reducer"),default:e(()=>({}),"default")}),nodes:o({reducer:f,default:e(()=>n?n():{},"default")}),tokens:o({reducer:i,default:m}),decisionUsage:o({reducer:p,default:l}),inputConsumed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")}),response:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>"","default")}),completed:o({reducer:e((t,r)=>r,"reducer"),default:e(()=>!1,"default")})})}e(C,"createGraphStateAnnotation");function g(d,n){const t={...d};for(const[r,s]of Object.entries(n))t[r]=a(t[r]??[],s);return t}e(g,"mergeHistories");export{A as GRAPH_END_NODE,C as createGraphStateAnnotation};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var s=(o,t)=>f(o,"name",{value:t,configurable:!0});import{AsyncLocalStorage as u}from"node:async_hooks";import{messagesStateReducer as p}from"@langchain/langgraph";const c=new u;function y(o){return c.getStore()?.owner===o}s(y,"hasNodeInvocation");function l(o,t,e,n){return c.run({owner:o,nodeId:t,state:e,nodes:{},histories:{}},n)}s(l,"withNodeInvocation");function I(o){return i(o).nodeId}s(I,"invocationNodeId");function d(o,t){const e=i(o),n=e.nodes[t];return n?{...n}:{...(e.state.nodes??{})[t]??{}}}s(d,"invocationNodeState");function S(o,t,e){const n=d(o,t);for(const[r,a]of Object.entries(e))a===void 0?delete n[r]:n[r]=a;i(o).nodes[t]=n}s(S,"saveInvocationNodeState");function N(o,t,e){i(o).nodes[t]={...e}}s(N,"replaceInvocationNodeState");function b(o,t,e){const n=i(o);n.histories[t]=[...n.histories[t]??[],...e]}s(b,"appendInvocationHistory");function h(o,t){const e=i(o);return p(e.state.histories?.[t]??[],e.histories[t]??[])}s(h,"invocationHistory");function j(o){const t=i(o),e={...t.state.nodes??{}};for(const r of Object.keys(t.nodes))e[r]=d(o,r);const n={...t.state.histories??{}};for(const r of Object.keys(t.histories))n[r]=h(o,r);return{...t.state,nodes:e,histories:n}}s(j,"invocationGraphState");function k(o){const t=i(o);return{...Object.keys(t.nodes).length>0?{nodes:t.nodes}:{},...Object.keys(t.histories).length>0?{histories:t.histories}:{}}}s(k,"invocationUpdate");function i(o){const t=c.getStore();if(!t||t.owner!==o)throw new Error("Node state can only be accessed during an active graph-node invocation.");return t}s(i,"requireInvocation");export{b as appendInvocationHistory,y as hasNodeInvocation,j as invocationGraphState,h as invocationHistory,I as invocationNodeId,d as invocationNodeState,k as invocationUpdate,N as replaceInvocationNodeState,S as saveInvocationNodeState,l as withNodeInvocation};
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 +1 @@
1
- const qu=l;(function(R,t){const k2={R:0x185,t:0x121,A:0x11f,r:0x18a,i:0x180,Y:0x172},qN=l,A=R();while(!![]){try{const r=parseInt(qN(0x182))/0x1+parseInt(qN(k2.R))/0x2+-parseInt(qN(k2.t))/0x3+-parseInt(qN(k2.A))/0x4*(-parseInt(qN(k2.r))/0x5)+-parseInt(qN(0x12c))/0x6*(parseInt(qN(0x157))/0x7)+parseInt(qN(k2.i))/0x8*(-parseInt(qN(k2.Y))/0x9)+-parseInt(qN(0x139))/0xa*(-parseInt(qN(0x145))/0xb);if(r===t)break;else A['push'](A['shift']());}catch(i){A['push'](A['shift']());}}}(d,0x2daed));var Z=Object[qu(0x19b)],c=(R,t)=>Z(R,qu(0x14e),{'value':t,'configurable':!0x0});import{mapChatMessagesToStoredMessages as e,mapStoredMessagesToChatMessages as B}from'@langchain/core/messages';import{BaseGraph as w}from'../base-graph.js';import{ConfigManager as K}from'../config-manager.js';import{GRAPH_END_NODE as D}from'../graph-state.js';import{GraphLlm as o}from'../graph-llm.config.js';import{replaceNodeStates as a}from'../node-state.js';import{createSessionLogs as u}from'../session-log.js';import{emptyTokenUsage as n,normalizeTokenUsage as m}from'../token-usage.js';import{assertGraphSchemaVersion as E}from'../stable-id.js';import{addDecisionUsage as s,emptyDecisionUsage as L,normalizeDecisionUsage as z}from'../decision/decision-types.js';const h=0x10,g=qu(0x166),P='SESSION_CONFLICT',_e=qu(0x1af);class f extends Error{static{c(this,qu(0x15a));}['code'];constructor(R,A){const k3={R:0x14e},qP=qu;super(A),this[qP(k3.R)]=qP(0x15a),this[qP(0x15e)]=R;}}class N{static{c(this,'SessionManager');}[qu(0x11d)];['turnLeaseMs'];constructor(R=new V(),A=G()){const k4={R:0x136},qn=qu;this['container']=R,this[qn(k4.R)]=A;}static async[qu(0x165)](q0=new K()){const k5={R:0x194,t:0x18f,A:0x17e,r:0x159,i:0x158,Y:0x126,H:0x19f,M:0x1b4,O:0x13e,b:0x18b,q0:0x1b9,q1:0x154,q2:0x178,q3:0x156,q4:0x163,q5:0x131,q6:0x19e,q7:0x142,q8:0x1ae,q9:0x140,qq:0x119,qk:0x15c,qd:0x13c,qG:0x14a,qT:0x125,qy:0x191,ql:0x187,qe:0x193,qX:0x1bf,qv:0x118,qB:0x1bc,qw:0x155,qK:0x197},qm=qu,q1=q0[qm(0x125)](qm(0x186),'memory')[qm(0x1a9)]()[qm(0x146)](),q2=G(q0[qm(0x125)](qm(k5.R)));if(q1===qm(0x15f))return new N(new V(),q2);if(q1===qm(k5.t)){const {SqliteSessionDocumentContainer:qv}=await import('./sqlite-session-document.container.js');return new N(new qv(q0['get'](qm(k5.A),qm(0x16f))),q2);}if(q1===qm(0x1b4)||q1==='mongo'){const qB=p(q0,qm(k5.r)),qw=p(q0,qm(k5.i)),qK=p(q0,qm(0x190));if(!qB||!qw||!qK)throw new Error(qm(k5.Y));const [{MongoClient:qj},{MongoDbSessionDocumentContainer:qD}]=await Promise[qm(k5.H)]([import(qm(k5.M)),import('./mongodb-session-document.container.js')]),qo=new qj(qB);await qo['connect']();const qa=qo['db'](qw)[qm(k5.O)](qK);return await qa[qm(k5.b)]({'id':0x1},{'unique':!0x0}),new N(new qD(qa,qo),q2);}if(q1!==qm(0x181)&&q1!==qm(0x148))throw new Error('Unsupported\x20SESSION_STORE\x20\x27'+q1+qm(0x128));const q3=p(q0,qm(k5.q0),qm(k5.q1),qm(k5.q2)),q4=p(q0,qm(k5.q3),qm(k5.q4)),q5=p(q0,qm(k5.q5)),q6=p(q0,qm(k5.q6)),q7=p(q0,qm(k5.q7)),q8=p(q0,qm(k5.q8),'COSMOS_DATABASE',qm(k5.q9))??qm(k5.qq),q9=p(q0,qm(0x14b),'COSMOS_CONTAINER',qm(0x1b1))??qm(0x13a);if(!q3||!q4&&(!q5||!q6||!q7))throw new Error(qm(0x1b5));const [{CosmosClient:qq},{ClientSecretCredential:qk}]=await Promise[qm(0x19f)]([import(qm(k5.qk)),import(qm(0x18c))]),qd=q4?new qq({'endpoint':q3,'key':q4}):new qq({'endpoint':q3,'aadCredentials':new qk(q5,q6,q7)}),{database:qG}=await qd[qm(k5.qd)][qm(k5.qG)]({'id':q8}),qT=Number(q0[qm(k5.qT)](qm(k5.qy),qm(0x141))),{container:qy}=await qG['containers'][qm(0x14a)]({'id':q9,'partitionKey':{'paths':[qm(k5.ql)]},...Number[qm(0x116)](qT)&&qT>0x0?{'throughput':qT}:{}}),{resource:ql}=await qy[qm(k5.qe)](),qe=ql?.[qm(k5.qX)]?.[qm(k5.qv)]??[];if(!qe[qm(k5.qB)](qm(k5.ql)))throw new Error('Cosmos\x20container\x20\x27'+q9+'\x27\x20must\x20use\x20partition\x20key\x20/id;\x20found\x20'+(qe[qm(k5.qw)](',\x20')||qm(k5.qK))+'.');const {CosmosSessionDocumentContainer:qX}=await import('./cosmos-session-document.container.js');return new N(new qX(qy,()=>qd[qm(0x15b)]()),q2);}async[qu(0x12b)](R){const k6={R:0x188},qV=qu,A=await this[qV(0x167)](R);return A?.[qV(k6.R)]===h?A:void 0x0;}async['readDocument'](R){const k7={R:0x11d},qE=qu;try{const {resource:A}=await this[qE(k7.R)]['item'](R,R)[qE(0x193)]();return A;}catch(r){if(j(r))return;throw r;}}async[qu(0x16c)](R,A,Y){const k8={R:0x134,t:0x167,A:0x136,r:0x13b,i:0x16a,Y:0x13f,H:0x151,M:0x124,O:0x11d,b:0x16a,q0:0x1ad,q1:0x11e,q2:0x1be,q3:0x170},qC=qu,H=w[qC(0x16b)](Y[qC(0x1c0)]),M=E(Y[qC(k8.R)]),O=await this[qC(k8.t)](R);O&&O['version']===h&&T(O,H);const b=new Date(),q0={'owner':A,'expiresAt':new Date(b[qC(0x152)]()+this[qC(k8.A)])['toISOString']()};if(!O){const q2=this[qC(k8.r)](R,Y,H,M,q0,b[qC(0x124)]());if(await this['container'][qC(0x1be)]({'expectedRevision':null},q2)===qC(0x170))throw new f(g,qC(k8.i)+R+qC(k8.Y));return{'kind':qC(k8.H),'document':q2,'expectedRevision':q2['revision']};}if(O['version']!==h){const q3=this[qC(0x13b)](R,Y,H,M,q0,b[qC(k8.M)]());if(await this[qC(k8.O)][qC(0x1be)]({'expectedRevision':S(O),'replaceIncompatible':!0x0},q3)===qC(0x170))throw new f(g,qC(k8.b)+R+'\x27\x20is\x20already\x20processing\x20a\x20turn.');return{'kind':'leased','document':q3,'expectedRevision':q3[qC(k8.q0)]};}if(F(O['turn'])&&O[qC(0x184)]?.[qC(k8.q1)]!==A)throw new f(g,qC(0x16a)+R+qC(0x13f));const q1={...O,'revision':S(O)+0x1,'turn':q0};if(await this['container'][qC(k8.q2)]({'expectedRevision':S(O),'requireFreeLease':!0x0,'allowOwner':A},q1)===qC(k8.q3))throw new f(g,qC(0x16a)+R+qC(k8.Y));return{'kind':qC(0x151),'document':q1,'expectedRevision':S(q1)};}async[qu(0x162)](R,A){const i=await this['getSession'](R);if(i)return this['restoreSessionDocument'](i,A);}[qu(0x150)](R,A){const kq={R:0x16b,t:0x18e,A:0x14c,r:0x171},qp=qu,Y=w[qp(kq.R)](A);T(R,Y);const {graph:H}=R;if(!H[qp(0x196)])return;const M=a({},H[qp(0x196)]),O=se(H[qp(kq.t)]);return{'currentNode':H['currentNode'],'config':H[qp(0x135)]??{},'completed':R[qp(kq.A)]==='completed'||H[qp(0x1b3)]===D,'nodes':M,'tokens':m(R[qp(0x11c)]),'decisionUsage':z(R[qp(kq.r)]),'histories':O,'inputConsumed':!0x0,'response':''};}async[qu(0x12f)](R,A,Y,H=u(),M={}){const kk={R:0x167,t:0x124,A:0x196,r:0x192,i:0x117,Y:0x11b,H:0x17d,M:0x183,O:0x184,b:0x129,q0:0x11d,q1:0x1be,q2:0x18d,q3:0x170,q4:0x16a,q5:0x13f},qJ=qu,b=w[qJ(0x16b)](Y[qJ(0x1c0)]),q0=E(Y['graphSchemaVersion']),q1=await this[qJ(kk.R)](R),q2=q1?.['version']===h?q1:void 0x0;q2&&(T(q2,b),q(q2,q0));const q3=new Date()[qJ(kk.t)](),q4=ne(a({},A[qJ(kk.A)])),{tokens:q5,histories:q6}=A,q7=this[qJ(kk.r)](q1,M),q8={'version':h,'id':R,'revision':q7===null?0x0:q7+0x1,'status':A[qJ(0x176)]?qJ(0x176):qJ(kk.i),'tokens':m(q5),'decisionUsage':z(A['decisionUsage']),'errors':[...q2?.[qJ(0x160)]??[],...H[qJ(0x160)]],'warnings':[...q2?.[qJ(kk.Y)]??[],...H[qJ(0x11b)]],'decisions':[...q2?.[qJ(0x16e)]??[],...H['decisions']],'graph':{'id':b,'schemaVersion':q0,'currentNode':A[qJ(0x1b3)],'config':A[qJ(0x135)],'histories':ie(q6),'model':o[qJ(kk.H)](Y[qJ(kk.M)]),'nodes':q4},...M[qJ(0x195)]&&q2?.[qJ(kk.O)]?{'turn':{'owner':q2['turn'][qJ(0x11e)],'expiresAt':new Date(Date[qJ(kk.b)]()+this['turnLeaseMs'])[qJ(0x124)]()}}:{},'createdAt':q2?.['createdAt']??q3,'modifiedAt':q3};if(await this[qJ(kk.q0)][qJ(kk.q1)](this[qJ(kk.q2)](q1,M,q7),q8)===qJ(kk.q3))throw new f(M['owner']?P:g,M[qJ(0x11e)]?qJ(0x16a)+R+qJ(0x1ba):qJ(kk.q4)+R+qJ(kk.q5));return q8;}async['appendLogs'](R,A,Y,H={}){const kd={R:0x16b,t:0x14c,A:0x171,r:0x160,i:0x11b,Y:0x143,H:0x18e,M:0x183,O:0x143,b:0x196,q0:0x1a5,q1:0x11d,q2:0x1be,q3:0x170,q4:0x123,q5:0x16a,q6:0x15d,q7:0x16a},qs=qu,M=w[qs(kd.R)](Y['graphId']),O=E(Y[qs(0x134)]),b=await this[qs(0x12b)](R);b&&(T(b,M),q(b,O));const q0=new Date()[qs(0x124)](),q1=this['commitExpectedRevision'](b,H),q2={'version':h,'id':R,'revision':q1===null?0x0:q1+0x1,'status':A['errors'][qs(0x15d)]>0x0?qs(0x122):b?.[qs(kd.t)]??qs(0x117),'tokens':b?.[qs(0x11c)]??n(),'decisionUsage':A[qs(0x16e)][qs(0x19d)]((q3,q4)=>s(q3,q4['usage']),z(b?.[qs(kd.A)])),'errors':[...b?.[qs(0x160)]??[],...A[qs(kd.r)]],'warnings':[...b?.['warnings']??[],...A[qs(kd.i)]],'decisions':[...b?.['decisions']??[],...A['decisions']],'graph':{'id':M,'schemaVersion':O,...b?{'currentNode':b[qs(0x143)]['currentNode'],'config':b[qs(kd.Y)]['config']}:{},'histories':b?.[qs(0x143)][qs(kd.H)]??{},'model':o['modelMetadata'](Y[qs(kd.M)]),...b?.[qs(kd.Y)]['nodes']?{'nodes':b[qs(kd.O)][qs(kd.b)]}:{}},'createdAt':b?.[qs(kd.q0)]??q0,'modifiedAt':q0};if(await this[qs(kd.q1)][qs(kd.q2)](this[qs(0x18d)](b,H,q1),q2)===qs(kd.q3)){if(H[qs(0x11e)]){console[qs(kd.q4)](qs(kd.q5)+R+qs(0x1a6)+A[qs(0x160)][qs(kd.q6)]+qs(0x175)+A[qs(0x11b)][qs(kd.q6)]+'\x20warning(s)\x20were\x20dropped.');return;}throw new f(g,qs(kd.q7)+R+qs(0x13f));}return q2;}async[qu(0x1c1)](R,A,Y,H,M){const qL=qu;if(H&&(H[qL(0x160)]['length']>0x0||H['warnings'][qL(0x15d)]>0x0||H[qL(0x16e)][qL(0x15d)]>0x0)){await this[qL(0x17c)](R,H,Y,{'owner':A,...M!==void 0x0?{'expectedRevision':M}:{}});return;}await this[qL(0x1a2)](R,A,M);}async[qu(0x1a2)](R,A,Y){const kT={R:0x184},qz=qu,H=await this[qz(0x12b)](R);if(!H||H[qz(kT.R)]?.[qz(0x11e)]!==A)return;const M=Y??S(H),{turn:O,...b}=H,q0={...b,'modifiedAt':new Date()[qz(0x124)]()};await this['container'][qz(0x1be)]({'expectedRevision':M,'requireOwner':A},q0);}async[qu(0x16d)](R){const ky={R:0x1bd,t:0x1a1},qR=qu;try{await this[qR(0x11d)][qR(ky.R)](R,R)[qR(ky.t)]();}catch(A){if(!j(A))throw A;}}async['persistMigratedSession'](R,A={}){const kl={R:0x188,t:0x1b8,A:0x16b,r:0x12b,i:0x184,Y:0x1a5,H:0x11d,M:0x1be,O:0x11e,b:0x11e},qc=qu;if(R[qc(kl.R)]!==h)throw new Error(qc(kl.t)+R[qc(kl.R)]+qc(0x17b)+h+'.');w[qc(kl.A)](R[qc(0x143)]['id']),E(R[qc(0x143)][qc(0x153)]);const Y=await this[qc(kl.r)](R['id']),H=A['expectedRevision']??S(Y||R),M=Y?.[qc(kl.i)]??R[qc(0x184)],O={...R,'revision':H,'createdAt':Y?.[qc(kl.Y)]??R[qc(0x1a5)],'modifiedAt':Y?.['modifiedAt']??R['modifiedAt'],...M?{'turn':M}:{}};if(await this[qc(kl.H)][qc(kl.M)]({'expectedRevision':H,...A[qc(kl.O)]?{'requireOwner':A[qc(0x11e)]}:{'requireFreeLease':!0x0}},O)===qc(0x170))throw new f(A[qc(kl.b)]?P:g,qc(0x16a)+R['id']+'\x27\x20changed\x20before\x20its\x20migration\x20could\x20be\x20saved.');}async[qu(0x1b0)](){await this['container']['close']?.();}['placeholderDocument'](R,A,Y,H,M,O){const kX={R:0x117},qg=qu;return{'version':h,'id':R,'revision':0x0,'status':qg(kX.R),'tokens':n(),'decisionUsage':L(),'errors':[],'warnings':[],'decisions':[],'graph':{'id':Y,'schemaVersion':H,'histories':{},'model':o['modelMetadata'](A[qg(0x183)])},'turn':M,'createdAt':O,'modifiedAt':O};}['commitExpectedRevision'](R,A){const qt=qu;return A[qt(0x1ac)]!==void 0x0?A[qt(0x1ac)]:R?S(R):null;}[qu(0x18d)](R,A,i){const kB={R:0x188},qA=qu;return A[qA(0x11e)]?{'expectedRevision':i,'requireOwner':A[qA(0x11e)]}:R&&R[qA(kB.R)]!==h?{'expectedRevision':i,'replaceIncompatible':!0x0}:{'expectedRevision':i,'requireFreeLease':!0x0};}}function p(R,...A){for(const i of A){const Y=R['get'](i);if(Y)return Y;}}c(p,qu(0x127));function T(R,t){const kK={R:0x189},qr=qu;if(R[qr(0x143)]['id']!==t)throw new Error(qr(0x16a)+R['id']+qr(0x169)+R[qr(0x143)]['id']+qr(kK.R)+t+qr(0x12d));}c(T,qu(0x19a));function d(){const kt=['qgf6DxjLl2LKzw50Axr5','y29TBwL0uhjLzgLJyxrL','AgLZDg9YAwvZ','C3fSAxrL','tu9or09eqL9dt0Xmrunusu9o','q09ttu9tx1riuK9vr0Hqvvq','y29TBwL0rxHWzwn0zwrszxzPC2LVBG','CMvHza','u0vtu0LptL9uvvjox0Xfqvnfx01t','A2vLCfr1CM4','BM9Kzxm','BM9Uzq','lcbUB3qG','CMvZCg9UC2vFBwv0ywrHDge','yxnZzxj0u2vZC2LVBKDYyxbO','zgvMAw5LuhjVCgvYDhK','zxPNCMfWAeLUDgvYBMfS','CMvKDwnL','q09ttu9FrejFq0Xjru5ux0Le','ywXS','BwfW','zgvSzxrL','CMvSzwfZzvr1CM4','C3rVCMviAxn0B3jPzxm','CMvTB3zLtgvNywn5vg9VBfrYywnLCW','y3jLyxrLzef0','jYbSB3n0igL0CYbSzwfZzsbIzwzVCMuGBg9NCYb3zxjLigfWCgvUzgvKoYa','yxnZAwDU','DxbZzxj0','DhjPBq','jYbZy2HLBweGDMvYC2LVBIa','CgfYC2u','zxHWzwn0zwrszxzPC2LVBG','CMv2AxnPB24','q09ttu9FrejFsuq','u0vtu0LptL9dt01qtevuruq','y2XVC2u','q09ttu9eqL9trvntsu9ox0Le','B2jQzwn0','y3vYCMvUDe5Vzgu','Bw9Uz29KyG','q29ZBw9ZihnLC3nPB24GCgvYC2LZDgvUy2uGCMvXDwLYzxmGq09ttu9eqL9vuKWGyw5Kienpu01prejFs0vzlcbVCIbdt1nnt19ftKrqt0LovcWGqvPvuKvFvevoqu5ux0Lelcbdt1nnt19eqL9dteLftLrFsuqSigfUzcbdt1nnt19eqL9dteLftLrFu0vduKvulG','AxnbCNjHEq','Dgv4Da','q2fUBM90ihbLCNnPC3qGC2vZC2LVBIbKB2n1BwvUDcb2zxjZAw9Uia','q09ttu9Fru5eue9jtLq','jYbJAgfUz2vKigjLzM9Yzsb0AgLZihr1CM4Gy291BgqGyMuGC2f2zwqU','zg9JDw1LBNrZ','Aw5JBhvKzxm','AxrLBq','y29TCgfYzufUzfn3yxa','CgfYDgL0Aw9Us2v5','z3jHCgHjza','zw5KrMfPBgvKvhvYBG','lIbszxn0B3jLig9Yig1Pz3jHDguGAxqGyMvMB3jLihnHDMLUzY4','AxngAw5PDgu','Aw5FChjVz3jLC3m','Cgf0Ahm','BgfUz2DYyxbO','zNjVBuvUDhjPzxm','D2fYBMLUz3m','Dg9Rzw5Z','y29UDgfPBMvY','B3DUzxi','mtm5odq0B1nVq1Lf','tM90igzVDw5K','otGWmZCZALHLvKzt','zxjYB3i','D2fYBG','Dg9ju09tDhjPBMC','z2v0','tw9Uz29eqIbZzxnZAw9UihbLCNnPC3rLBMnLihjLCxvPCMvZie1ptKDprejFvvjmlcbnt05ht0rcx05btuuSigfUzcbnt05ht0rcx0npteXfq1rjt04U','zMLYC3q','jY4GvxnLicDTzw1VCNKNlcaNC3fSAxrLjYWGj21VBMDVzgiNlcbVCIaNy29ZBw9ZjY4','BM93','C2LNBMf0DxjLqMvHCMLUz0nVBNrLBNrcBg9JAW','z2v0u2vZC2LVBG','nLfhD2fPBW','jY4Gu3rHCNqGysbUzxCGC2vZC2LVBIb0BYbYDw4GysbKAwzMzxjLBNqGz3jHCgGU','DxnHz2vFBwv0ywrHDge','C2f2zvn0yxrL','CMvXDwLYzu93BMvY','qvPvuKvFvevoqu5ux0Le','y29TCgfJDfn0B3jLze1LC3nHz2vZ','twvTB3j5u2vZC2LVBKrVy3vTzw50q29UDgfPBMvY','z3jHCgHty2HLBwfwzxjZAw9U','y29UzMLN','DhvYBKXLyxnLtxm','CMvWBgfJzuLUy29TCgf0AwjSzq','Aw52ywXPzf90B29Sx2nHBgXZ','mtbnBKDXvey','C2vZC2LVBNm','CgXHy2vOB2XKzxjeB2n1BwvUDa','zgf0ywjHC2vZ','AxnmAxzLu2vZC2LVBLr1CM4','y29SBgvJDgLVBG','jYbPCYbHBhjLywr5ihbYB2nLC3nPBMCGysb0DxjUlG','q09ttu9eqL9jra','ndaW','q09ttu9FrejFq0Xjru5ux1nfq1jfva','z3jHCgG','C2L6zq','ntm2nJCXm0vksejuvq','Dg9mB3DLCKnHC2u','ywXSB3DpD25LCG','y29ZBw9Zzgi','C2v0','y3jLyxrLswzoB3rfEgLZDhm','q09ttu9FrejFu0vtu0LptL9dt05uquLorvjFsuq','C3rHDhvZ','nJaWmda','BMfTzq','DgHVDwDODa','CMvZDg9YzvnLC3nPB25eB2n1BwvUDa','BgvHC2vK','z2v0vgLTzq','C2nOzw1HvMvYC2LVBG','q09ttu9tx0vorfbpsu5u','AM9PBG','q09ttu9eqL9lrvK','mtGZnJy5nuzxzK5KuW','tu9or09eqL9oqu1f','tu9or09eqL9vuKW','u2vZC2LVBLr1CM5fCNjVCG','zgLZCg9Zzq','qgf6DxjLl2nVC21VCW','BgvUz3rO','y29Kzq','BwvTB3j5','zxjYB3jZ','DhLWzq','CMvZDg9Yzvn0yxrL','q09ttu9tx0Tfwq','DgHVDwDODfnPz25HDhvYzq','zNjVBunVBMzPzW','u0vtu0LptL9cvvnz','CMvHzerVy3vTzw50','zw50CMLLCW','jYbIzwXVBMDZihrVigDYyxbOicC','u2vZC2LVBIaN','yxnZzxj0swq','yMvNAw5uDxjU','zgvSzxrLu2vZC2LVBG','zgvJAxnPB25Z','lI9KyxrHl3nLC3nPB25ZlNnXBgL0zq','y29UzMXPy3q','zgvJAxnPB25vC2fNzq','ovnzEgPoAq','Dg9VBf9JywXSCW','AxnoB3rgB3vUza','igvYCM9YkhmPigfUzca','y29TCgXLDgvK','zxHWAxjLC0f0','q09ttu9eqL9vuKW','AxrLBxm','AxnszwnVCMq','oYbLEhbLy3rLzca','yxbWzw5Ktg9NCW','Bw9KzwXnzxrHzgf0yq','u1fmsvrfx0rcx1bbveG','ywrKAxrPB25HBf9RD2fYz3m','mZK4ntm2ExffzunM','y29ZBw9Z','odm2nJrfu2vZDfO','BgXTq29UzMLN','DhvYBG','mtu5nte2Ag1Tq1H1','u0vtu0LptL9tve9srq','l2LK','DMvYC2LVBG','jYWGBM90icC','mJvkzNrVENa','y3jLyxrLsw5KzxG'];d=function(){return kt;};return d();}function q(R,t){const kj={R:0x143,t:0x16a,A:0x1aa,r:0x153,i:0x1c2},qf=qu;if(R[qf(kj.R)]['schemaVersion']!==t)throw new Error(qf(kj.t)+R['id']+'\x27\x20uses\x20graph\x20\x27'+R[qf(0x143)]['id']+qf(kj.A)+R['graph'][qf(kj.r)]+qf(0x198)+t+qf(kj.i));}function l(q,k){q=q-0x116;const G=d();let T=G[q];if(l['iLIAun']===undefined){var y=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);};l['NebsVu']=y,l['KBVcIO']={},l['iLIAun']=!![];}const e=G[0x0],X=q+e,v=l['KBVcIO'][X];return!v?(T=l['NebsVu'](T),l['KBVcIO'][X]=T):T=v,T;}c(q,'assertSessionGraphSchema');function ne(R){const ko={R:0x11a,t:0x1a0},kD={R:0x1b2},qi=qu;return Object[qi(ko.R)](Object[qi(0x168)](R)[qi(ko.t)](([A,i])=>{const qh=qi;if(!i||typeof i!=qh(kD.R))return[A,i];const {toolTrace:Y,...H}=i;return[A,H];}));}c(ne,qu(0x1a4));function oe(R){const ka={R:0x17f,t:0x19c,A:0x199,r:0x12e,i:0x161,Y:0x173,H:0x173,M:0x15d,O:0x1b6,b:0x138,q0:0x138};return R['map'](A=>{const qQ=l,r={...A['data']},Y=A[qQ(0x161)]==='ai'&&Array['isArray'](r[qQ(0x173)])&&r['tool_calls'][qQ(0x15d)]>0x0?ae(r['additional_kwargs']):void 0x0,H=v(r[qQ(0x17f)])&&r[qQ(ka.R)][qQ(ka.t)]===!0x0;return delete r['additional_kwargs'],(Y||H)&&(r[qQ(ka.R)]={...Y?{'originalTextContentBlock':Y}:{},...H?{'ezgraphInternal':!0x0}:{}}),delete r[qQ(ka.A)],delete r[qQ(ka.r)],A[qQ(ka.i)]==='ai'&&(Array[qQ(0x1b6)](r[qQ(ka.Y)])&&r[qQ(ka.H)][qQ(ka.M)]===0x0&&delete r['tool_calls'],Array[qQ(ka.O)](r['invalid_tool_calls'])&&r[qQ(ka.b)]['length']===0x0&&delete r[qQ(ka.q0)]),{...A,'data':r};});}c(oe,qu(0x132));function ie(R){const qZ=qu;return Object[qZ(0x11a)](Object['entries'](R)[qZ(0x1a0)](([A,r])=>[A,oe(e(r))]));}c(ie,qu(0x1a3));function se(R={}){const kP={R:0x168},qY=qu;return Object[qY(0x11a)](Object[qY(kP.R)](R)[qY(0x1a0)](([A,r])=>[A,B(r)]));}c(se,'restoreHistories');function ae(R){const kn={R:0x164,t:0x164,A:0x14f},qH=qu;if(!v(R))return;const t=R['originalTextContentBlock'];if(!(!v(t)||typeof t[qH(kn.R)]!='string'))return{...typeof t[qH(0x1b7)]=='string'?{'text':t['text']}:{},'thoughtSignature':t[qH(kn.t)],...t[qH(kn.A)]===!0x0?{'thought':!0x0}:{}};}c(ae,qu(0x12a));function v(R){const km={R:0x1b6},qW=qu;return R!==null&&typeof R==qW(0x1b2)&&!Array[qW(km.R)](R);}c(v,qu(0x17a));class V{static{c(this,qu(0x133));}[qu(0x1bb)]=new Map();get[qu(0x144)](){const qM=qu;return this[qM(0x1bb)]['size'];}[qu(0x179)]={'upsert':c(async e=>{const kE={R:0x1bb},qx=qu,t=e;return this[qx(kE.R)]['set'](t['id'],structuredClone(t)),{};},qu(0x1a8))};async[qu(0x1be)](R,A){const kC={R:0x125,t:0x170},qU=qu,i=this['documents'][qU(kC.R)](A['id']);return ce(i,R)?(this[qU(0x1bb)][qU(0x149)](A['id'],structuredClone(A)),'ok'):qU(kC.t);}['item'](R,A){const kJ={R:0x1bb,t:0x1a1},kp={R:0x125},qF=qu;return{'read':c(async()=>{const qO=l,i=this['documents'][qO(kp.R)](R);if(!i||i['id']!==A)throw Object[qO(0x1a7)](new Error(qO(0x120)),{'code':0x194});return{'resource':structuredClone(i)};},qF(0x193)),'delete':c(async()=>{const qS=qF,i=this[qS(kJ.R)][qS(0x125)](R);if(!i||i['id']!==A)throw Object['assign'](new Error(qS(0x120)),{'code':0x194});return this[qS(0x1bb)][qS(kJ.t)](R),{};},qF(0x1a1))};}}function j(R){const kL={R:0x1b2,t:0x15e},qb=qu;if(!R||typeof R!=qb(kL.R))return!0x1;const t=R;return t[qb(kL.t)]===0x194||t['statusCode']===0x194;}c(j,qu(0x174));function G(R=process.env.SESSION_TURN_LEASE_MS){const qI=qu,t=Number(R??qI(0x14d));return Number[qI(0x116)](t)&&t>0x0?t:0xea60;}c(G,'sessionTurnLeaseMs');function S(R){return R?.['revision']??0x0;}c(S,'sessionRevision');function F(R,A=Date[qu(0x129)]()){const kc={R:0x177,t:0x116},k0=qu;if(!R?.[k0(0x11e)]||!R[k0(0x177)])return!0x1;const r=Date[k0(0x1ab)](R[k0(kc.R)]);return Number[k0(kc.t)](r)&&r>A;}c(F,qu(0x13d));function ce(R,A,r=Date[qu(0x129)]()){const kg={R:0x1ac,t:0x130},k1=qu;return A[k1(0x137)]?R!==void 0x0&&R[k1(0x188)]!==h:A[k1(kg.R)]===null?R===void 0x0:!(!R||S(R)!==A['expectedRevision']||A[k1(kg.t)]&&R[k1(0x184)]?.[k1(0x11e)]!==A['requireOwner']||A['requireFreeLease']&&F(R[k1(0x184)],r)&&R['turn']?.['owner']!==A[k1(0x147)]);}c(ce,'matchesSessionWritePredicate');export{V as MemorySessionDocumentContainer,g as SESSION_BUSY,_e as SESSION_COMPLETED,P as SESSION_CONFLICT,h as SESSION_DOCUMENT_VERSION,N as SessionManager,f as SessionTurnError,F as isLiveSessionTurn,ce as matchesSessionWritePredicate,S as sessionRevision,G as sessionTurnLeaseMs};
1
+ const qN=d;(function(t,A){const k5={t:0xad,A:0xfd,r:0x125,i:0xa6,Z:0xce,Y:0xe8},qa=d,r=t();while(!![]){try{const i=-parseInt(qa(k5.t))/0x1*(-parseInt(qa(0x10b))/0x2)+-parseInt(qa(k5.A))/0x3+-parseInt(qa(k5.r))/0x4*(parseInt(qa(0xdc))/0x5)+-parseInt(qa(k5.i))/0x6*(parseInt(qa(0xd6))/0x7)+-parseInt(qa(0x122))/0x8+parseInt(qa(k5.Z))/0x9*(parseInt(qa(k5.Y))/0xa)+parseInt(qa(0x99))/0xb*(parseInt(qa(0xa8))/0xc);if(i===A)break;else r['push'](r['shift']());}catch(Z){r['push'](r['shift']());}}}(k,0x27bd1));var J=Object[qN(0xc6)],c=(t,A)=>J(t,qN(0xc9),{'value':A,'configurable':!0x0});import{mapChatMessagesToStoredMessages as l,mapStoredMessagesToChatMessages as e}from'@langchain/core/messages';import{BaseGraph as B}from'../base-graph.js';function k(){const kf=['CMvSzwfZzvr1CM4','DhjPBq','DgHVDwDODfnPz25HDhvYzq','y3vYCMvUDe5Vzgu','ndaW','Dg9ju09tDhjPBMC','Bw9Uz29KyG','jYbJAgfUz2vKigjLzM9Yzsb0AgLZihr1CM4Gy291BgqGyMuGC2f2zwqU','C3rVCMviAxn0B3jPzxm','AgLZDg9YAwvZ','mtyXmtq0nhLWs1DLEq','q09ttu9eqL9jra','mZm2mJG5mMTtveTHDq','CMvZDg9YzuHPC3rVCMLLCW','zxjYB3i','Dg9Rzw5Z','CMvHza','ntK0nJHzwhrsu2u','lIbszxn0B3jLig9Yig1Pz3jHDguGAxqGyMvMB3jLihnHDMLUzY4','q09ttu9FrejFq0Xjru5ux1nfq1jfva','u1fmsvrfx0rcx1bbveG','zgf0yq','CMv2AxnPB24','q29ZBw9ZihnLC3nPB24GCgvYC2LZDgvUy2uGCMvXDwLYzxmGq09ttu9eqL9vuKWGyw5Kienpu01prejFs0vzlcbVCIbdt1nnt19ftKrqt0LovcWGqvPvuKvFvevoqu5ux0Lelcbdt1nnt19eqL9dteLftLrFsuqSigfUzcbdt1nnt19eqL9dteLftLrFu0vduKvulG','y29Kzq','AxnmAxzLu2vZC2LVBLr1CM4','jYbZy2HLBweGDMvYC2LVBIa','zxHWAxjLC0f0','jYbJAgfUz2vKigjLzM9YzsbPDhmGBwLNCMf0Aw9UignVDwXKigjLihnHDMvKlG','twvTB3j5u2vZC2LVBKrVy3vTzw50q29UDgfPBMvY','DgHVDwDODa','u2vZC2LVBIaN','DhLWzq','lI9JB3nTB3mTC2vZC2LVBI1KB2n1BwvUDc5JB250ywLUzxiUANm','C3fSAxrL','AxrLBxm','zNjVBuvUDhjPzxm','yxnZAwDU','u0vtu0LptL9dt05gteLdva','oYbLEhbLy3rLzca','y29TBwL0rxHWzwn0zwrszxzPC2LVBG','q09ttu9tx0nptLrbsu5fuG','zgvMAw5LuhjVCgvYDhK','C3rYAw5N','CMvKDwnL','BMfTzq','yxnZzxj0swq','jYbPCYbHBhjLywr5ihbYB2nLC3nPBMCGysb0DxjUlG','CgfYC2u','D2fYBMLUz3m','nte4nerotgHcBq','CMvZCg9UC2vFBwv0ywrHDge','CMvXDwLYzuzYzwvmzwfZzq','zxPNCMfWAeLUDgvYBMfS','zw50CMLLCW','CgXHy2vOB2XKzxjeB2n1BwvUDa','y29UzMXPy3q','q09ttu9tx1riuK9vr0Hqvvq','n29TvvLjwG','q09ttu9eqL9trvntsu9ox0Le','qgf6DxjLl2nVC21VCW','C2f2zvn0yxrL','Aw5JBhvKzxm','tu9or09eqL9vuKW','nw92sfz6uW','qgf6DxjLl2LKzw50Axr5','yxnZzxj0u2vZC2LVBKDYyxbOu2nOzw1H','DhvYBG','zxjYB3jZ','lI9KyxrHl3nLC3nPB25ZlNnXBgL0zq','z3jHCgHty2HLBwfwzxjZAw9U','ihDHCM5PBMCOCYKGD2vYzsbKCM9WCgvKlG','zgf0ywjHC2vZ','ywrKAxrPB25HBf9RD2fYz3m','C2vZC2LVBLr1CM5mzwfZzu1Z','y29UDgfPBMvY','nti5meD6twLVAa','ywXS','lcbUB3qG','C2nOzw1HvMvYC2LVBG','BgfUz2DYyxbO','u0vtu0LptL9cvvnz','yxbWzw5Ktg9NCW','AxnbCNjHEq','jYbSB3n0igL0CYbSzwfZzsbIzwzVCMuGBg9NCYb3zxjLigfWCgvUzgvKoYa','C2LNBMf0DxjLqMvHCMLUz0nVBNrLBNrcBg9JAW','CMvXDwLYzu93BMvY','BgXTq29UzMLN','yxnZzxj0u2vZC2LVBKDYyxbO','l2LK','Bw9KAwzPzwrbDa','DxnHz2vFBwv0ywrHDge','zNjVBunVBMzPzW','Aw52ywXPzf90B29Sx2nHBgXZ','u2vZC2LVBLr1CM5fCNjVCG','jYb1C2vZigDYyxbOicC','y29TCgXLDgvK','mtC4otKYA3HSq3bk','jYbIzwXVBMDZihrVigDYyxbOicC','BgvHC2vK','q2fUBM90ihbLCNnPC3qGC2vZC2LVBIbKB2n1BwvUDcb2zxjZAw9Uia','DMvYC2LVBG','CMvZDg9YzvnLC3nPB25eB2n1BwvUDa','DhvYBKXLyxnLtxm','AxnszwnVCMq','zg9JDw1LBNrZ','q09ttu9eqL9lrvK','zMLYC3q','yMvNAw5uDxjU','y3jLyxrLswzoB3rfEgLZDhm','y29ZBw9Z','nNPfDeHQwa','CMvWBgfJzuLUy29TCgf0AwjSzq','B3jPz2LUywXuzxH0q29UDgvUDejSB2nR','C2v0','Bw9KzwXnzxrHzgf0yq','y29ZBw9Zzgi','Dg9VBf9JywXSCW','q09ttu9FrejFq0Xjru5ux0Le','zxHWzwn0zwrszxzPC2LVBG','y29UDgv4Da','y29UBMvJDa','C2vZC2LVBNm','CMvHzerVy3vTzw50','nJaWmda','z2v0','Cgf0Ahm','tM90igzVDw5K','zgvJAxnPB25Z','z3jHCgHjza','BwfW','C3rHDhvZ','zgvSzxrLu2vZC2LVBG','B2jQzwn0','mZu4mtuYsvfetg9P','z2v0vgLTzq','DxbZzxj0','oteWmJKYBNjPz0fp','zgLZCg9Zzq','jY4GvxnLicDTzw1VCNKNlcaNC3fSAxrLjYWGj21VBMDVzgiNlcbVCIaNy29ZBw9ZjY4','z2v0u2vZC2LVBG','BM9Kzxm','qvPvuKvFvevoqu5ux0Le','CMvZDg9Yzvn0yxrL','u0vtu0LptL9uvvjox0Xfqvnfx01t','BgvUz3rO','y29TBwL0uhjLzgLJyxrL','C3rHDhvZq29Kzq','BM93','z3jHCgG','CMvTB3zLtgvNywn5vg9VBfrYywnLCW','Dgv4Da','tu9or09eqL9dt0Xmrunusu9o','B3DUzxi','q09ttu9FrejFsuq','Bwf0y2HLC1nLC3nPB25xCML0zvbYzwrPy2f0zq','zgvSzxrL','AxnoB3rgB3vUza','y29UzMLN','jY4Gu3rHCNqGysbUzxCGC2vZC2LVBIb0BYbYDw4GysbKAwzMzxjLBNqGz3jHCgGU','CgfYDgL0Aw9Us2v5','y29TCgfYzufUzfn3yxa','AxrLBq','y2XVC2u','zgvJAxnPB25vC2fNzq','y3jLyxrLzef0','C2vZC2LVBLjLDMLZAw9U','ywXSB3DpD25LCG','Aw5FChjVz3jLC3m','AM9PBG','AxngAw5PDgu','mtfnAKDzEgO','y29TCgfJDfn0B3jLze1LC3nHz2vZ','C2L6zq'];k=function(){return kf;};return k();}import{ConfigManager as w}from'../config-manager.js';import{GRAPH_END_NODE as D}from'../graph-state.js';import{cloneJsonObject as o}from'../graph-context.js';import{GraphLlm as a}from'../graph-llm.config.js';import{replaceNodeStates as u}from'../node-state.js';import{createSessionLogs as n}from'../session-log.js';import{emptyTokenUsage as m,normalizeTokenUsage as E}from'../token-usage.js';import{assertGraphSchemaVersion as s}from'../stable-id.js';import{addDecisionUsage as L,emptyDecisionUsage as z,normalizeDecisionUsage as R}from'../decision/decision-types.js';const h=0x10,g=qN(0xed),q=qN(0xc2),Ce='SESSION_COMPLETED';class f extends Error{static{c(this,qN(0xfa));}[qN(0xb4)];constructor(A,r){const qu=qN;super(r),this[qu(0xc9)]=qu(0xfa),this[qu(0xb4)]=A;}}class N{static{c(this,'SessionManager');}['container'];[qN(0x103)];constructor(A=new V(),r=F()){const qP=qN;this['container']=A,this[qP(0x103)]=r;}static async[qN(0xf8)](r=new w()){const k8={t:0x119,A:0x9d,r:0x12c,i:0x119,Z:0xdb,Y:0xa2,H:0x110,M:0x106,O:0x12a,q0:0x112,q1:0x136,q2:0xa7,q3:0xec,q4:0xd7,q5:0xd8,q6:0xdd,q7:0xe4,q8:0x119,q9:0x11a,qq:0xbd},qn=qN,q0=r[qn(k8.t)]('SESSION_STORE','memory')[qn(k8.A)]()['toLowerCase'](),q1=F(r['get'](qn(k8.r)));if(q0==='memory')return new N(new V(),q1);if(q0===qn(0xbe)){const {SqliteSessionDocumentContainer:qX}=await import('./sqlite-session-document.container.js');return new N(new qX(r[qn(k8.i)](qn(0xb0),qn(0xe1))),q1);}if(q0===qn(0xa2)||q0==='mongo'){const qv=p(r,qn(k8.Z)),qB=p(r,'MONGODB_NAME'),qw=p(r,qn(0x134));if(!qv||!qB||!qw)throw new Error('MongoDB\x20session\x20persistence\x20requires\x20MONGODB_URL,\x20MONGODB_NAME,\x20and\x20MONGODB_COLLECTION.');const [{MongoClient:qK},{MongoDbSessionDocumentContainer:qj}]=await Promise[qn(0xe9)]([import(qn(k8.Y)),import('./mongodb-session-document.container.js')]),qD=new qK(qv);await qD[qn(0x115)]();const qo=qD['db'](qB)['collection'](qw);return await qo['createIndex']({'id':0x1},{'unique':!0x0}),new N(new qj(qo,qD),q1);}if(q0!==qn(0x10a)&&q0!==qn(k8.H))throw new Error('Unsupported\x20SESSION_STORE\x20\x27'+q0+qn(0x127));const q2=p(r,'COSMO_ENDPOINT','COSMOS_ENDPOINT','COSMODB_URL'),q3=p(r,qn(k8.M),'COSMOS_KEY'),q4=p(r,qn(k8.O)),q5=p(r,qn(k8.q0)),q6=p(r,qn(0xaf)),q7=p(r,qn(k8.q1),'COSMOS_DATABASE',qn(k8.q2))??qn(k8.q3),q8=p(r,'COSMO_DB_SESSION_CONTAINER_ID',qn(0xc5),qn(k8.q4))??qn(0x116);if(!q2||!q3&&(!q4||!q5||!q6))throw new Error(qn(0xb3));const [{CosmosClient:q9},{ClientSecretCredential:qq}]=await Promise['all']([import(qn(k8.q5)),import(qn(k8.q6))]),qk=q3?new q9({'endpoint':q2,'key':q3}):new q9({'endpoint':q2,'aadCredentials':new qq(q4,q5,q6)}),{database:qd}=await qk[qn(k8.q7)][qn(0x109)]({'id':q7}),qG=Number(r[qn(k8.q8)](qn(0xd5),qn(0xa0))),{container:qT}=await qd['containers'][qn(0x109)]({'id':q8,'partitionKey':{'paths':['/id']},...Number[qn(0x98)](qG)&&qG>0x0?{'throughput':qG}:{}}),{resource:qy}=await qT[qn(0xac)](),ql=qy?.[qn(0x13c)]?.[qn(k8.q9)]??[];if(!ql[qn(0xda)](qn(0xf5)))throw new Error('Cosmos\x20container\x20\x27'+q8+'\x27\x20must\x20use\x20partition\x20key\x20/id;\x20found\x20'+(ql[qn(0x145)](',\x20')||'none')+'.');const {CosmosSessionDocumentContainer:qe}=await import(qn(k8.qq));return new N(new qe(qT,()=>qk[qn(0x126)]()),q1);}async[qN(0x128)](A){const k9={t:0x117,A:0x101},qm=qN,r=await this[qm(k9.t)](A);return r?.[qm(k9.A)]===h?r:void 0x0;}async[qN(0x117)](A){const kq={t:0xe7},qV=qN;try{const {resource:r}=await this[qV(kq.t)][qV(0x13e)](A,A)[qV(0xac)]();return r;}catch(i){if(G(i))return;throw i;}}async[qN(0x108)](A,r,Z){const kk={t:0xca,A:0x117,r:0x123,i:0x103,Z:0xa1,Y:0x13d,H:0xcb,M:0xe7,O:0xd4,q0:0xff,q1:0xdf,q2:0xbb,q3:0xcb},qE=qN,Y=B[qE(kk.t)](Z[qE(0x11d)]),H=s(Z[qE(0xe2)]),M=await this[qE(kk.A)](A);M&&M[qE(0x101)]===h&&T(M,Y);const O=new Date(),q0={'owner':r,'expiresAt':new Date(O[qE(kk.r)]()+this[qE(kk.i)])[qE(0xa1)]()};if(!M){const q2=this['placeholderDocument'](A,Z,Y,H,q0,O[qE(kk.Z)]());if(await this['container'][qE(kk.Y)]({'expectedRevision':null},q2)==='conflict')throw new f(g,qE(0xbb)+A+qE(kk.H));return{'kind':qE(0xff),'document':q2,'expectedRevision':q2['revision']};}if(M[qE(0x101)]!==h){const q3=this['placeholderDocument'](A,Z,Y,H,q0,O['toISOString']());if(await this[qE(kk.M)][qE(0x13d)]({'expectedRevision':S(M),'replaceIncompatible':!0x0},q3)===qE(kk.O))throw new f(g,qE(0xbb)+A+'\x27\x20is\x20already\x20processing\x20a\x20turn.');return{'kind':qE(kk.q0),'document':q3,'expectedRevision':q3[qE(0xb2)]};}if(K(M[qE(0xdf)])&&M[qE(kk.q1)]?.[qE(0x135)]!==r)throw new f(g,'Session\x20\x27'+A+qE(kk.H));const q1={...M,'revision':S(M)+0x1,'turn':q0};if(await this['container']['compareAndSwap']({'expectedRevision':S(M),'requireFreeLease':!0x0,'allowOwner':r},q1)==='conflict')throw new f(g,qE(kk.q2)+A+qE(kk.q3));return{'kind':'leased','document':q1,'expectedRevision':S(q1)};}async[qN(0x12b)](A,r){const qC=qN,i=await this['getSession'](A);if(i)return this[qC(0x102)](i,r);}[qN(0x102)](A,r){const kG={t:0x129,A:0x129,r:0xa5,i:0x13a,Z:0x114,Y:0x11f,H:0xfc},qp=qN,i=B[qp(0xca)](r);T(A,i);const {graph:Z}=A;if(!Z[qp(kG.t)])return;const Y=u({},Z[qp(kG.A)]),H=ae(Z[qp(kG.r)]);return{'currentNode':Z[qp(0x9f)],'config':Z[qp(kG.i)]??{},'context':o(Z[qp(kG.Z)]===void 0x0?{}:Z['context']),'completed':A[qp(kG.Y)]===qp(kG.H)||Z[qp(0x9f)]===D,'nodes':Y,'tokens':E(A[qp(0xab)]),'decisionUsage':R(A['decisionUsage']),'histories':H,'inputConsumed':!0x0,'response':''};}async[qN(0xd9)](A,r,Z,Y=n(),H={}){const kT={t:0xe2,A:0xa1,r:0x129,i:0xfc,Z:0x140,Y:0xe0,H:0x11c,M:0x9f,O:0x114,q0:0x10f,q1:0x135,q2:0x13d,q3:0xd4,q4:0xbb,q5:0xcb},qJ=qN,M=B[qJ(0xca)](Z[qJ(0x11d)]),q0=s(Z[qJ(kT.t)]),q1=await this[qJ(0x117)](A),q2=q1?.[qJ(0x101)]===h?q1:void 0x0;q2&&(T(q2,M),j(q2,q0));const q3=new Date()[qJ(kT.A)](),q4=oe(u({},r[qJ(kT.r)])),{tokens:q5,histories:q6}=r,q7=this[qJ(0xc4)](q1,H),q8={'version':h,'id':A,'revision':q7===null?0x0:q7+0x1,'status':r[qJ(kT.i)]?'completed':'in_progress','tokens':E(q5),'decisionUsage':R(r[qJ(kT.Z)]),'errors':[...q2?.[qJ(0xe0)]??[],...Y[qJ(kT.Y)]],'warnings':[...q2?.[qJ(0xcd)]??[],...Y[qJ(0xcd)]],'decisions':[...q2?.['decisions']??[],...Y[qJ(kT.H)]],'graph':{'id':M,'schemaVersion':q0,'currentNode':r[qJ(kT.M)],'config':r[qJ(0x13a)],'context':o(r[qJ(kT.O)]===void 0x0?{}:r[qJ(kT.O)]),'histories':se(q6),'model':a[qJ(kT.q0)](Z[qJ(0xf3)]),'nodes':q4},...H['keepTurn']&&q2?.[qJ(0xdf)]?{'turn':{'owner':q2[qJ(0xdf)][qJ(kT.q1)],'expiresAt':new Date(Date[qJ(0x130)]()+this[qJ(0x103)])[qJ(0xa1)]()}}:{},'createdAt':q2?.['createdAt']??q3,'modifiedAt':q3};if(await this['container'][qJ(kT.q2)](this[qJ(0x12e)](q1,H,q7),q8)===qJ(kT.q3))throw new f(H['owner']?q:g,H[qJ(0x135)]?qJ(kT.q4)+A+qJ(0xa3):qJ(0xbb)+A+qJ(kT.q5));return q8;}async['appendLogs'](A,r,Z,Y={}){const ky={t:0xe2,A:0x128,r:0x140,i:0xe0,Z:0x11c,Y:0x9f,H:0x13a,M:0xa5,O:0x114,q0:0xf3,q1:0x131,q2:0x131,q3:0x141,q4:0x13d,q5:0x12e,q6:0x135,q7:0xbb,q8:0x12d},qs=qN,H=B[qs(0xca)](Z[qs(0x11d)]),M=s(Z[qs(ky.t)]),O=await this[qs(ky.A)](A);O&&(T(O,H),j(O,M));const q0=new Date()['toISOString'](),q1=this[qs(0xc4)](O,Y),q2={'version':h,'id':A,'revision':q1===null?0x0:q1+0x1,'status':r[qs(0xe0)]['length']>0x0?qs(0xaa):O?.['status']??'in_progress','tokens':O?.[qs(0xab)]??m(),'decisionUsage':r[qs(0x11c)][qs(0xc8)]((q3,q4)=>L(q3,q4['usage']),R(O?.[qs(ky.r)])),'errors':[...O?.[qs(ky.i)]??[],...r[qs(0xe0)]],'warnings':[...O?.[qs(0xcd)]??[],...r[qs(0xcd)]],'decisions':[...O?.[qs(ky.Z)]??[],...r[qs(0x11c)]],'graph':{'id':H,'schemaVersion':M,...O?{'currentNode':O['graph'][qs(ky.Y)],'config':O['graph'][qs(ky.H)]}:{},'histories':O?.[qs(0x131)][qs(ky.M)]??{},'context':o(O?.['graph'][qs(ky.O)]===void 0x0?{}:O[qs(0x131)]['context']),'model':a['modelMetadata'](Z[qs(ky.q0)]),...O?.[qs(ky.q1)][qs(0x129)]?{'nodes':O[qs(ky.q2)][qs(0x129)]}:{}},'createdAt':O?.[qs(ky.q3)]??q0,'modifiedAt':q0};if(await this['container'][qs(ky.q4)](this[qs(ky.q5)](O,Y,q1),q2)==='conflict'){if(Y[qs(ky.q6)]){console['warn'](qs(ky.q7)+A+qs(0xf0)+r[qs(ky.i)]['length']+'\x20error(s)\x20and\x20'+r['warnings'][qs(ky.q8)]+qs(0xe3));return;}throw new f(g,'Session\x20\x27'+A+qs(0xcb));}return q2;}async['endFailedTurn'](A,r,i,Z,Y){const kl={t:0xe0,A:0xcd,r:0x9c},qL=qN;if(Z&&(Z[qL(kl.t)][qL(0x12d)]>0x0||Z[qL(kl.A)][qL(0x12d)]>0x0||Z[qL(0x11c)][qL(0x12d)]>0x0)){await this[qL(0xee)](A,Z,i,{'owner':r,...Y!==void 0x0?{'expectedRevision':Y}:{}});return;}await this[qL(kl.r)](A,r,Y);}async[qN(0x9c)](A,r,Z){const ke={t:0x135,A:0x13d},qz=qN,Y=await this['getSession'](A);if(!Y||Y['turn']?.[qz(ke.t)]!==r)return;const H=Z??S(Y),{turn:M,...O}=Y,q0={...O,'modifiedAt':new Date()['toISOString']()};await this[qz(0xe7)][qz(ke.A)]({'expectedRevision':H,'requireOwner':r},q0);}async[qN(0x120)](A){const kX={t:0xe7},qR=qN;try{await this[qR(kX.t)][qR(0x13e)](A,A)[qR(0x138)]();}catch(r){if(!G(r))throw r;}}async['persistMigratedSession'](A,r={}){const kv={t:0x100,A:0xc3,r:0x131,i:0xeb,Z:0x128,Y:0xdf,H:0x114,M:0x141,O:0x141,q0:0xbb,q1:0xb8},qc=qN;if(A['version']!==h)throw new Error(qc(kv.t)+A[qc(0x101)]+qc(kv.A)+h+'.');B[qc(0xca)](A[qc(0x131)]['id']),s(A[qc(kv.r)][qc(kv.i)]);const i=await this[qc(kv.Z)](A['id']),Z=r[qc(0x113)]??S(i||A),Y=i?.[qc(0xdf)]??A[qc(kv.Y)],H={...A,'graph':{...A['graph'],'context':o(A[qc(kv.r)][qc(kv.H)]===void 0x0?{}:A['graph']['context'])},'revision':Z,'createdAt':i?.[qc(kv.M)]??A[qc(kv.O)],'modifiedAt':i?.[qc(0xf6)]??A[qc(0xf6)],...Y?{'turn':Y}:{}};if(await this['container'][qc(0x13d)]({'expectedRevision':Z,...r[qc(0x135)]?{'requireOwner':r[qc(0x135)]}:{'requireFreeLease':!0x0}},H)===qc(0xd4))throw new f(r[qc(0x135)]?q:g,qc(kv.q0)+A['id']+qc(kv.q1));}async[qN(0x13f)](){const qg=qN;await this['container'][qg(0x13f)]?.();}[qN(0xd3)](A,r,i,Z,Y,H){const kw={t:0x144},qt=qN;return{'version':h,'id':A,'revision':0x0,'status':qt(kw.t),'tokens':m(),'decisionUsage':z(),'errors':[],'warnings':[],'decisions':[],'graph':{'id':i,'schemaVersion':Z,'histories':{},'context':{},'model':a[qt(0x10f)](r[qt(0xf3)])},'turn':Y,'createdAt':H,'modifiedAt':H};}['commitExpectedRevision'](A,r){const kK={t:0x113},qA=qN;return r[qA(kK.t)]!==void 0x0?r[qA(kK.t)]:A?S(A):null;}[qN(0x12e)](A,r,i){const kj={t:0x135,A:0x101},qr=qN;return r[qr(kj.t)]?{'expectedRevision':i,'requireOwner':r['owner']}:A&&A[qr(kj.A)]!==h?{'expectedRevision':i,'replaceIncompatible':!0x0}:{'expectedRevision':i,'requireFreeLease':!0x0};}}function p(A,...i){const qf=qN;for(const Z of i){const Y=A[qf(0x119)](Z);if(Y)return Y;}}c(p,qN(0x107));function T(t,A){const ko={t:0x131,A:0xbb,r:0xfe,i:0x13b},qi=qN;if(t[qi(ko.t)]['id']!==A)throw new Error(qi(ko.A)+t['id']+qi(ko.r)+t['graph']['id']+'\x27,\x20not\x20\x27'+A+qi(ko.i));}c(T,qN(0xf4));function j(t,A){const ka={t:0x131,A:0xeb,r:0xfb,i:0xb6,Z:0x131,Y:0xeb,H:0xea,M:0xae},qh=qN;if(t[qh(ka.t)][qh(ka.A)]!==A)throw new Error('Session\x20\x27'+t['id']+qh(ka.r)+t['graph']['id']+qh(ka.i)+t[qh(ka.Z)][qh(ka.Y)]+qh(ka.H)+A+qh(ka.M));}c(j,qN(0xde));function oe(t){const ku={t:0x11e},kN={t:0x121},qQ=qN;return Object[qQ(0xc0)](Object[qQ(0xd2)](t)[qQ(ku.t)](([A,i])=>{const qZ=qQ;if(!i||typeof i!=qZ(kN.t))return[A,i];const {toolTrace:Z,...Y}=i;return[A,Y];}));}c(oe,qN(0x132));function ie(t){const kP={t:0xef,A:0x12d,r:0xe5,i:0xd1,Z:0xcf,Y:0xf7,H:0x111,M:0x12d,O:0xf9,q0:0x12d,q1:0xf9};return t['map'](A=>{const qY=d,i={...A[qY(0xb1)]},Z=A['type']==='ai'&&Array[qY(kP.t)](i[qY(0x111)])&&i[qY(0x111)][qY(kP.A)]>0x0?ce(i[qY(0xe5)]):void 0x0,Y=b(i[qY(kP.r)])&&i[qY(0xe5)][qY(kP.i)]===!0x0;return delete i[qY(0xe5)],(Z||Y)&&(i['additional_kwargs']={...Z?{'originalTextContentBlock':Z}:{},...Y?{'ezgraphInternal':!0x0}:{}}),delete i[qY(kP.Z)],delete i[qY(kP.Y)],A[qY(0xbc)]==='ai'&&(Array[qY(0xef)](i[qY(kP.H)])&&i[qY(0x111)][qY(kP.M)]===0x0&&delete i[qY(kP.H)],Array['isArray'](i[qY(kP.O)])&&i[qY(0xf9)][qY(kP.q0)]===0x0&&delete i[qY(kP.q1)]),{...A,'data':i};});}c(ie,qN(0x9a));function se(t){const km={t:0xd2,A:0x11e},qH=qN;return Object[qH(0xc0)](Object[qH(km.t)](t)[qH(km.A)](([A,i])=>[A,ie(l(i))]));}c(se,qN(0xa4));function ae(t={}){const kV={t:0xc0},qW=qN;return Object[qW(kV.t)](Object[qW(0xd2)](t)[qW(0x11e)](([A,i])=>[A,e(i)]));}c(ae,qN(0xa9));function ce(t){const kE={t:0x9e,A:0x133,r:0x9e},qM=qN;if(!b(t))return;const A=t[qM(0x10d)];if(!(!b(A)||typeof A[qM(kE.t)]!=qM(0xc7)))return{...typeof A[qM(kE.A)]==qM(0xc7)?{'text':A['text']}:{},'thoughtSignature':A[qM(kE.r)],...A[qM(0xba)]===!0x0?{'thought':!0x0}:{}};}c(ce,qN(0xf1));function b(t){const qx=qN;return t!==null&&typeof t==qx(0x121)&&!Array['isArray'](t);}c(b,qN(0x104));class V{static{c(this,qN(0xb9));}[qN(0x105)]=new Map();get[qN(0x9b)](){const qU=qN;return this[qU(0x105)][qU(0x9b)];}[qN(0xbf)]={'upsert':c(async e=>{const kJ={t:0x105},qO=qN,t=e;return this[qO(kJ.t)]['set'](t['id'],structuredClone(t)),{};},qN(0x124))};async[qN(0x13d)](A,r){const ks={t:0x105},qF=qN,i=this[qF(ks.t)][qF(0x119)](r['id']);return de(i,A)?(this['documents'][qF(0x10e)](r['id'],structuredClone(r)),'ok'):'conflict';}[qN(0x13e)](A,r){const kz={t:0x119,A:0xc1,r:0x11b},kL={t:0x105},qI=qN;return{'read':c(async()=>{const qS=d,i=this[qS(kL.t)][qS(0x119)](A);if(!i||i['id']!==r)throw Object[qS(0xc1)](new Error('Not\x20found'),{'code':0x194});return{'resource':structuredClone(i)};},'read'),'delete':c(async()=>{const qb=d,i=this[qb(0x105)][qb(kz.t)](A);if(!i||i['id']!==r)throw Object[qb(kz.A)](new Error(qb(kz.r)),{'code':0x194});return this[qb(0x105)]['delete'](A),{};},qI(0x138))};}}function G(t){const k0=qN;if(!t||typeof t!=k0(0x121))return!0x1;const A=t;return A[k0(0xb4)]===0x194||A[k0(0x12f)]===0x194;}c(G,qN(0x139));function F(t=process.env.SESSION_TURN_LEASE_MS){const kg={t:0x118},k1=qN,A=Number(t??k1(kg.t));return Number[k1(0x98)](A)&&A>0x0?A:0xea60;}function d(q,G){q=q-0x98;const T=k();let y=T[q];if(d['zZPXch']===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 k=0x0,u=K['length'];k<u;k++){j+='%'+('00'+K['charCodeAt'](k)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(j);};d['quHhSI']=l,d['AkYZlF']={},d['zZPXch']=!![];}const e=T[0x0],X=q+e,v=d['AkYZlF'][X];return!v?(y=d['quHhSI'](y),d['AkYZlF'][X]=y):y=v,y;}c(F,qN(0xe6));function S(t){const kt={t:0xb2},k2=qN;return t?.[k2(kt.t)]??0x0;}c(S,qN(0x142));function K(A,i=Date['now']()){const kA={t:0x135,A:0xcc,r:0xb7},k3=qN;if(!A?.[k3(kA.t)]||!A[k3(0xb7)])return!0x1;const Z=Date[k3(kA.A)](A[k3(kA.r)]);return Number['isFinite'](Z)&&Z>i;}c(K,qN(0xb5));function de(A,i,Z=Date[qN(0x130)]()){const kr={t:0x113,A:0xdf,r:0xf2,i:0xd0},k4=qN;return i[k4(0x10c)]?A!==void 0x0&&A['version']!==h:i[k4(kr.t)]===null?A===void 0x0:!(!A||S(A)!==i[k4(0x113)]||i['requireOwner']&&A[k4(kr.A)]?.[k4(0x135)]!==i[k4(kr.r)]||i[k4(kr.i)]&&K(A[k4(0xdf)],Z)&&A['turn']?.[k4(0x135)]!==i[k4(0x143)]);}c(de,qN(0x137));export{V as MemorySessionDocumentContainer,g as SESSION_BUSY,Ce as SESSION_COMPLETED,q as SESSION_CONFLICT,h as SESSION_DOCUMENT_VERSION,N as SessionManager,f as SessionTurnError,K as isLiveSessionTurn,de as matchesSessionWritePredicate,S as sessionRevision,F as sessionTurnLeaseMs};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{BaseGraph as r}from"./framework/base-graph.js";import{GRAPH_NODE_CLASS as t,GraphNode as i,GraphNodeRuntime as n,Tool as a}from"./framework/graph-node.js";import{LlmNode as p}from"./framework/llm-node.js";import{LLM_GATEWAY_FACTORY as E,assertLlmTimeoutMs as f}from"./framework/llm-gateway.js";import{ConversationRunner as L,DEFAULT_CONVERSATION_POLICY as d,DEFAULT_EMPTY_HISTORY_SEED as T,DEFAULT_EMPTY_RESPONSE_RECOVERY as g,DEFAULT_MAX_AGENT_ROUNDS as l,EmptyModelResponseError as D,assertEmptyResponseRetries as R,assertMaxAgentRounds as _}from"./framework/conversation-runner.js";import{describeStopReason as C,isRetryableStopReason as M,modelStopReason as A}from"./framework/model-stop-reason.js";import{currentTurnContext as O,currentTurnSignal as u,withTurnContext as I}from"./framework/turn-context.js";import{direct as G,directTo as U,finish as h,go as y,isToolResponse as v,stay as F}from"./framework/tool-response.js";import{GraphStateSupport as H}from"./framework/graph-state-support.js";import{GRAPH_END_NODE as B,createGraphStateAnnotation as V}from"./framework/graph-state.js";import{GraphRegistry as W}from"./framework/graph-registry.js";import{GraphEngine as z}from"./framework/graph-engine.js";import{ConfigManager as J}from"./framework/config-manager.js";import{StateGraphExt as X}from"./framework/state-graph-ext.js";import{TerminateSessionNode as K}from"./framework/terminate-session.node.js";import{SessionLogError as $,SessionLogDecision as ee,SessionLogWarning as oe,createSessionLogs as re,drainSessionLogs as se,restoreSessionLogs as te,withSessionLogs as ie}from"./framework/session-log.js";import{ProviderFileManager as ae}from"./framework/llm-file.js";import{SessionManager as pe,SessionTurnError as Se,SESSION_BUSY as Ee,SESSION_CONFLICT as fe,SESSION_COMPLETED as xe,SESSION_DOCUMENT_VERSION as Le,MemorySessionDocumentContainer as de,sessionTurnLeaseMs as Te,sessionRevision as ge,isLiveSessionTurn as le,matchesSessionWritePredicate as De}from"./framework/persistence/session-manager.js";import{MongoDbSessionDocumentContainer as _e}from"./framework/persistence/mongodb-session-document.container.js";import{SqliteSessionDocumentContainer as Ce}from"./framework/persistence/sqlite-session-document.container.js";import{CosmosSessionDocumentContainer as Ae}from"./framework/persistence/cosmos-session-document.container.js";import{mergeNodeStates as Oe,replaceNodeStates as ue}from"./framework/node-state.js";import{LangChainLlmGateway as Pe}from"./framework/langchain-llm-gateway.js";import{ModelProvider as Ue}from"./framework/model-provider.js";import{langChainModelInitialization as ye}from"./framework/langchain-provider.adapter.js";import{GRAPH_LLM_PROVIDERS as Fe,GRAPH_LLM_FAMILIES as Ye,GRAPH_LLM_CAPABILITIES as He,BUILT_IN_MODEL_CATALOG as ke,GraphLlm as Be,ModelCatalog as Ve,ModelProviderRegistry as be}from"./framework/graph-llm.config.js";import{addTokenUsage as we,emptyTokenUsage as ze,modelExecution as qe,normalizeTokenUsage as Je,tokenUsageFromMessage as Qe}from"./framework/token-usage.js";import{DecisionNode as je}from"./framework/decision/decision-node.js";import{DecisionRunner as Ze}from"./framework/decision/decision-runner.js";import{DecisionProvider as eo,DecisionProviderRegistry as oo}from"./framework/decision/decision-provider.js";import{TypeSafeClassifierAdapter as so}from"./framework/decision/typesafe-provider.js";import{DecisionConfigurationError as io,DecisionTimeoutError as no,DecisionValidationError as ao,DEFAULT_DECISION_OPTIONS as mo,addDecisionUsage as po,decisionUsage as So,emptyDecisionUsage as Eo,normalizeDecisionUsage as fo,resolveDecisionOptions as xo}from"./framework/decision/decision-types.js";import{assertJsonCompatible as To,validateDecisionQuestions as go,validateDecisionResult as lo}from"./framework/decision/decision-validation.js";import{retryWithModel as Ro,LlmResponseBlockedError as _o,LlmSetupError as co}from"./framework/llm-lifecycle.js";export{ke as BUILT_IN_MODEL_CATALOG,r as BaseGraph,J as ConfigManager,L as ConversationRunner,Ae as CosmosSessionDocumentContainer,d as DEFAULT_CONVERSATION_POLICY,mo as DEFAULT_DECISION_OPTIONS,T as DEFAULT_EMPTY_HISTORY_SEED,g as DEFAULT_EMPTY_RESPONSE_RECOVERY,l as DEFAULT_MAX_AGENT_ROUNDS,io as DecisionConfigurationError,je as DecisionNode,eo as DecisionProvider,oo as DecisionProviderRegistry,Ze as DecisionRunner,no as DecisionTimeoutError,ao as DecisionValidationError,D as EmptyModelResponseError,B as GRAPH_END_NODE,He as GRAPH_LLM_CAPABILITIES,Ye as GRAPH_LLM_FAMILIES,Fe as GRAPH_LLM_PROVIDERS,t as GRAPH_NODE_CLASS,z as GraphEngine,Be as GraphLlm,i as GraphNode,n as GraphNodeRuntime,W as GraphRegistry,H as GraphStateSupport,E as LLM_GATEWAY_FACTORY,Pe as LangChainLlmGateway,p as LlmNode,_o as LlmResponseBlockedError,co as LlmSetupError,de as MemorySessionDocumentContainer,Ve as ModelCatalog,Ue as ModelProvider,be as ModelProviderRegistry,_e as MongoDbSessionDocumentContainer,ae as ProviderFileManager,Ee as SESSION_BUSY,xe as SESSION_COMPLETED,fe as SESSION_CONFLICT,Le as SESSION_DOCUMENT_VERSION,ee as SessionLogDecision,$ as SessionLogError,oe as SessionLogWarning,pe as SessionManager,Se as SessionTurnError,Ce as SqliteSessionDocumentContainer,X as StateGraphExt,K as TerminateSessionNode,a as Tool,so as TypeSafeClassifierAdapter,po as addDecisionUsage,we as addTokenUsage,R as assertEmptyResponseRetries,To as assertJsonCompatible,f as assertLlmTimeoutMs,_ as assertMaxAgentRounds,V as createGraphStateAnnotation,re as createSessionLogs,O as currentTurnContext,u as currentTurnSignal,So as decisionUsage,C as describeStopReason,G as direct,U as directTo,se as drainSessionLogs,Eo as emptyDecisionUsage,ze as emptyTokenUsage,h as finish,y as go,le as isLiveSessionTurn,M as isRetryableStopReason,v as isToolResponse,ye as langChainModelInitialization,De as matchesSessionWritePredicate,Oe as mergeNodeStates,qe as modelExecution,A as modelStopReason,fo as normalizeDecisionUsage,Je as normalizeTokenUsage,ue as replaceNodeStates,xo as resolveDecisionOptions,te as restoreSessionLogs,Ro as retryWithModel,ge as sessionRevision,Te as sessionTurnLeaseMs,F as stay,Qe as tokenUsageFromMessage,go as validateDecisionQuestions,lo as validateDecisionResult,ie as withSessionLogs,I as withTurnContext};
1
+ import{GraphContextChannel as r}from"./framework/graph-context.js";import{BaseGraph as t}from"./framework/base-graph.js";import{GRAPH_NODE_CLASS as n,GraphNode as a,GraphNodeRuntime as p,Tool as m}from"./framework/graph-node.js";import{LlmNode as E}from"./framework/llm-node.js";import{LLM_GATEWAY_FACTORY as f,assertLlmTimeoutMs as L}from"./framework/llm-gateway.js";import{ConversationRunner as l,DEFAULT_CONVERSATION_POLICY as T,DEFAULT_EMPTY_HISTORY_SEED as g,DEFAULT_EMPTY_RESPONSE_RECOVERY as D,DEFAULT_MAX_AGENT_ROUNDS as R,EmptyModelResponseError as _,assertEmptyResponseRetries as c,assertMaxAgentRounds as C}from"./framework/conversation-runner.js";import{describeStopReason as A,isRetryableStopReason as N,modelStopReason as O}from"./framework/model-stop-reason.js";import{currentTurnContext as I,currentTurnSignal as G,withTurnContext as P}from"./framework/turn-context.js";import{direct as U,directTo as y,finish as v,go as F,isToolResponse as Y,stay as H}from"./framework/tool-response.js";import{GraphStateSupport as B}from"./framework/graph-state-support.js";import{GRAPH_END_NODE as b,createGraphStateAnnotation as W}from"./framework/graph-state.js";import{GraphRegistry as z}from"./framework/graph-registry.js";import{GraphEngine as J}from"./framework/graph-engine.js";import{ConfigManager as X}from"./framework/config-manager.js";import{StateGraphExt as K}from"./framework/state-graph-ext.js";import{TerminateSessionNode as $}from"./framework/terminate-session.node.js";import{SessionLogError as oe,SessionLogDecision as re,SessionLogWarning as se,createSessionLogs as te,drainSessionLogs as ie,restoreSessionLogs as ne,withSessionLogs as ae}from"./framework/session-log.js";import{ProviderFileManager as me}from"./framework/llm-file.js";import{SessionManager as Ee,SessionTurnError as xe,SESSION_BUSY as fe,SESSION_CONFLICT as Le,SESSION_COMPLETED as de,SESSION_DOCUMENT_VERSION as le,MemorySessionDocumentContainer as Te,sessionTurnLeaseMs as ge,sessionRevision as De,isLiveSessionTurn as Re,matchesSessionWritePredicate as _e}from"./framework/persistence/session-manager.js";import{MongoDbSessionDocumentContainer as Ce}from"./framework/persistence/mongodb-session-document.container.js";import{SqliteSessionDocumentContainer as Ae}from"./framework/persistence/sqlite-session-document.container.js";import{CosmosSessionDocumentContainer as Oe}from"./framework/persistence/cosmos-session-document.container.js";import{mergeNodeStates as Ie,replaceNodeStates as Ge}from"./framework/node-state.js";import{LangChainLlmGateway as he}from"./framework/langchain-llm-gateway.js";import{ModelProvider as ye}from"./framework/model-provider.js";import{langChainModelInitialization as Fe}from"./framework/langchain-provider.adapter.js";import{GRAPH_LLM_PROVIDERS as He,GRAPH_LLM_FAMILIES as ke,GRAPH_LLM_CAPABILITIES as Be,BUILT_IN_MODEL_CATALOG as Ve,GraphLlm as be,ModelCatalog as We,ModelProviderRegistry as we}from"./framework/graph-llm.config.js";import{addTokenUsage as qe,emptyTokenUsage as Je,modelExecution as Qe,normalizeTokenUsage as Xe,tokenUsageFromMessage as je}from"./framework/token-usage.js";import{DecisionNode as Ze}from"./framework/decision/decision-node.js";import{DecisionRunner as eo}from"./framework/decision/decision-runner.js";import{DecisionProvider as ro,DecisionProviderRegistry as so}from"./framework/decision/decision-provider.js";import{TypeSafeClassifierAdapter as io}from"./framework/decision/typesafe-provider.js";import{DecisionConfigurationError as ao,DecisionTimeoutError as po,DecisionValidationError as mo,DEFAULT_DECISION_OPTIONS as So,addDecisionUsage as Eo,decisionUsage as xo,emptyDecisionUsage as fo,normalizeDecisionUsage as Lo,resolveDecisionOptions as lo}from"./framework/decision/decision-types.js";import{assertJsonCompatible as go,validateDecisionQuestions as Do,validateDecisionResult as Ro}from"./framework/decision/decision-validation.js";import{retryWithModel as co,LlmResponseBlockedError as Co,LlmSetupError as Mo}from"./framework/llm-lifecycle.js";export{Ve as BUILT_IN_MODEL_CATALOG,t as BaseGraph,X as ConfigManager,l as ConversationRunner,Oe as CosmosSessionDocumentContainer,T as DEFAULT_CONVERSATION_POLICY,So as DEFAULT_DECISION_OPTIONS,g as DEFAULT_EMPTY_HISTORY_SEED,D as DEFAULT_EMPTY_RESPONSE_RECOVERY,R as DEFAULT_MAX_AGENT_ROUNDS,ao as DecisionConfigurationError,Ze as DecisionNode,ro as DecisionProvider,so as DecisionProviderRegistry,eo as DecisionRunner,po as DecisionTimeoutError,mo as DecisionValidationError,_ as EmptyModelResponseError,b as GRAPH_END_NODE,Be as GRAPH_LLM_CAPABILITIES,ke as GRAPH_LLM_FAMILIES,He as GRAPH_LLM_PROVIDERS,n as GRAPH_NODE_CLASS,r as GraphContextChannel,J as GraphEngine,be as GraphLlm,a as GraphNode,p as GraphNodeRuntime,z as GraphRegistry,B as GraphStateSupport,f as LLM_GATEWAY_FACTORY,he as LangChainLlmGateway,E as LlmNode,Co as LlmResponseBlockedError,Mo as LlmSetupError,Te as MemorySessionDocumentContainer,We as ModelCatalog,ye as ModelProvider,we as ModelProviderRegistry,Ce as MongoDbSessionDocumentContainer,me as ProviderFileManager,fe as SESSION_BUSY,de as SESSION_COMPLETED,Le as SESSION_CONFLICT,le as SESSION_DOCUMENT_VERSION,re as SessionLogDecision,oe as SessionLogError,se as SessionLogWarning,Ee as SessionManager,xe as SessionTurnError,Ae as SqliteSessionDocumentContainer,K as StateGraphExt,$ as TerminateSessionNode,m as Tool,io as TypeSafeClassifierAdapter,Eo as addDecisionUsage,qe as addTokenUsage,c as assertEmptyResponseRetries,go as assertJsonCompatible,L as assertLlmTimeoutMs,C as assertMaxAgentRounds,W as createGraphStateAnnotation,te as createSessionLogs,I as currentTurnContext,G as currentTurnSignal,xo as decisionUsage,A as describeStopReason,U as direct,y as directTo,ie as drainSessionLogs,fo as emptyDecisionUsage,Je as emptyTokenUsage,v as finish,F as go,Re as isLiveSessionTurn,N as isRetryableStopReason,Y as isToolResponse,Fe as langChainModelInitialization,_e as matchesSessionWritePredicate,Ie as mergeNodeStates,Qe as modelExecution,O as modelStopReason,Lo as normalizeDecisionUsage,Xe as normalizeTokenUsage,Ge as replaceNodeStates,lo as resolveDecisionOptions,ne as restoreSessionLogs,co as retryWithModel,De as sessionRevision,ge as sessionTurnLeaseMs,H as stay,je as tokenUsageFromMessage,Do as validateDecisionQuestions,Ro as validateDecisionResult,ae as withSessionLogs,P as withTurnContext};
@@ -1,3 +1,4 @@
1
+ export { GraphContextChannel, type DeepReadonly } from "../../src/framework/graph-context.js";
1
2
  export { BaseGraph, type GraphDefinition, type GraphNodeConstructor, type GraphSchemaMigration, type HistorySpace, } from "../../src/framework/base-graph.js";
2
3
  export { GRAPH_NODE_CLASS, GraphNode, GraphNodeRuntime, Tool, type EmptyModelResponseContext, type GraphNodeUpdate, type GraphNodeResponse, type GraphNodeResult, type InvalidJsonResponseContext, type ToolDefinition, type ToolInput, type GraphNodeLocalState, type GraphNodeTarget, } from "../../src/framework/graph-node.js";
3
4
  export { LlmNode, type LlmNodeRunResult, } from "../../src/framework/llm-node.js";
@@ -7,6 +7,7 @@ import type { GraphState } from "./graph-state.js";
7
7
  import { StateGraphExt, type GraphNodeClass } from "./state-graph-ext.js";
8
8
  import type { StateDefinitionInit } from "@langchain/langgraph";
9
9
  import type { SessionDocument } from "./persistence/session-manager.js";
10
+ import type { DeepReadonly, JsonObject } from "./graph-context.js";
10
11
  import { type ConversationPolicy } from "./conversation-runner.js";
11
12
  import type { GraphNodeLocalState, GraphNodeTarget } from "./node-outcome.js";
12
13
  import type { DecisionOptions, DecisionErrorContext, DecisionProviderAdapter } from "./decision/decision-types.js";
@@ -16,6 +17,7 @@ export type GraphSchemaMigration<State extends GraphState = GraphState> = Readon
16
17
  migrate(sessionDoc: SessionDocument<State>): SessionDocument<State> | Promise<SessionDocument<State>>;
17
18
  }>;
18
19
  export type GraphDefinition<NodeId extends string = string, State extends GraphState = GraphState & {
20
+ context: JsonObject;
19
21
  decisionUsage: NonNullable<GraphState["decisionUsage"]>;
20
22
  }> = Readonly<{
21
23
  llmConfig: GraphLlmConfig;
@@ -69,6 +71,8 @@ export declare abstract class BaseGraph<State extends GraphState> {
69
71
  };
70
72
  prepareInput(state: State | undefined, message: HumanMessage): Partial<State>;
71
73
  private initialNodeId;
74
+ getContext(): DeepReadonly<JsonObject>;
75
+ saveContext(patch: JsonObject): void;
72
76
  saveNodeState<NodeClass extends GraphNodeTarget>(NodeClass: NodeClass, patch: Partial<GraphNodeLocalState<NodeClass>>): void;
73
77
  restoreSessionDoc(sessionDoc: SessionDocument<State>): Promise<SessionDocument<State> | null>;
74
78
  protected onRestoreSessionDoc(sessionDoc: SessionDocument<State>): Promise<SessionDocument<State> | null>;
@@ -0,0 +1,18 @@
1
+ import type { JsonObject } from "./decision/decision-types.js";
2
+ import { BaseChannel } from "@langchain/langgraph";
3
+ export type { JsonValue, JsonObject } from "./decision/decision-types.js";
4
+ export type DeepReadonly<T> = T extends readonly (infer Item)[] ? readonly DeepReadonly<Item>[] : T extends object ? {
5
+ readonly [Key in keyof T]: DeepReadonly<T[Key]>;
6
+ } : T;
7
+ export declare class GraphContextChannel extends BaseChannel<JsonObject, JsonObject, JsonObject> {
8
+ lc_graph_name: string;
9
+ private value;
10
+ constructor(initial?: JsonObject);
11
+ fromCheckpoint(checkpoint?: JsonObject): this;
12
+ update(values: JsonObject[]): boolean;
13
+ get(): JsonObject;
14
+ checkpoint(): JsonObject;
15
+ isAvailable(): boolean;
16
+ }
17
+ export declare function cloneJsonObject(value: unknown, label?: string): JsonObject;
18
+ export declare function readonlyContext(value: unknown): DeepReadonly<JsonObject>;
@@ -8,7 +8,7 @@ import { SessionManager, type SessionDocument } from "./persistence/session-mana
8
8
  import type { DecisionProviderAdapter } from "./decision/decision-types.js";
9
9
  export type GraphConstructor = {
10
10
  new (llmGateway: LlmGateway): RegisteredGraph;
11
- getGraphDefinition(): GraphDefinition;
11
+ getGraphDefinition(): GraphDefinition<string, GraphState>;
12
12
  };
13
13
  export type GraphEngineOptions = Readonly<{
14
14
  sessionManager?: SessionManager;
@@ -1,5 +1,6 @@
1
1
  import type { ConversationLlmLifecycle, GraphLlmLifecycle } from "./llm-lifecycle.js";
2
2
  import type { GraphState } from "./graph-state.js";
3
+ import type { DeepReadonly, JsonObject } from "./graph-context.js";
3
4
  import type { LlmCallOptions, LlmGateway, LlmGatewayTool } from "./llm-gateway.js";
4
5
  import "reflect-metadata";
5
6
  import { type BaseMessage } from "@langchain/core/messages";
@@ -84,8 +85,9 @@ export declare class GraphNodeRuntime<State extends GraphState> extends GraphSta
84
85
  private readonly decisionOptions;
85
86
  private readonly decisionErrorHandler?;
86
87
  readonly llmLifecycle?: GraphLlmLifecycle | undefined;
88
+ private readonly assertContextChannel?;
87
89
  private readonly tools;
88
- constructor(endNode: State["currentNode"], defaultLlmConfig: GraphLlmConfig, historySpaces?: Readonly<Record<string, string>>, responseMode?: "chat" | "json", maxAgentRounds?: number, conversationPolicy?: ConversationPolicy, decisionOptions?: DecisionOptions, decisionErrorHandler?: ((context: DecisionErrorContext<State>) => GraphNodeResponse<State> | null | Promise<GraphNodeResponse<State> | null>) | undefined, llmLifecycle?: GraphLlmLifecycle | undefined);
90
+ constructor(endNode: State["currentNode"], defaultLlmConfig: GraphLlmConfig, historySpaces?: Readonly<Record<string, string>>, responseMode?: "chat" | "json", maxAgentRounds?: number, conversationPolicy?: ConversationPolicy, decisionOptions?: DecisionOptions, decisionErrorHandler?: ((context: DecisionErrorContext<State>) => GraphNodeResponse<State> | null | Promise<GraphNodeResponse<State> | null>) | undefined, llmLifecycle?: GraphLlmLifecycle | undefined, assertContextChannel?: (() => void) | undefined);
89
91
  llmCallOptions(): LlmCallOptions;
90
92
  expectsJsonResponse(): boolean;
91
93
  historySpace(currentNode?: string): string;
@@ -113,6 +115,9 @@ export declare class GraphNodeRuntime<State extends GraphState> extends GraphSta
113
115
  nodeState(nodeName: string): Record<string, unknown>;
114
116
  hasInvocation(): boolean;
115
117
  graphState(): State;
118
+ getContext(): DeepReadonly<JsonObject>;
119
+ saveContext(patch: JsonObject): void;
120
+ stageContext(context: JsonObject): void;
116
121
  appendHistory(space: string, messages: readonly BaseMessage[]): void;
117
122
  invocationHistory(space: string): BaseMessage[];
118
123
  stagedUpdate(): GraphNodeUpdate<State>;
@@ -1,4 +1,6 @@
1
1
  import type { BaseMessage } from "@langchain/core/messages";
2
+ import { GraphContextChannel } from "./graph-context.js";
3
+ import type { JsonObject } from "./graph-context.js";
2
4
  import { type GraphNodeStates } from "./node-state.js";
3
5
  import { type TokenUsage } from "./token-usage.js";
4
6
  import { type DecisionUsage } from "./decision/decision-types.js";
@@ -7,6 +9,7 @@ export type GraphState<CurrentNode extends string = string, Nodes extends object
7
9
  histories: Record<string, BaseMessage[]>;
8
10
  currentNode: CurrentNode;
9
11
  config: Record<string, unknown>;
12
+ context?: JsonObject;
10
13
  nodes: Nodes;
11
14
  tokens: TokenUsage;
12
15
  decisionUsage?: DecisionUsage;
@@ -15,6 +18,7 @@ export type GraphState<CurrentNode extends string = string, Nodes extends object
15
18
  completed: boolean;
16
19
  };
17
20
  export declare function createGraphStateAnnotation<CurrentNode extends string = string, Nodes extends object = GraphNodeStates>(defaultCurrentNode: string, createInitialNodes?: () => Nodes): import("@langchain/langgraph").AnnotationRoot<{
21
+ context: GraphContextChannel;
18
22
  histories: import("@langchain/langgraph").BaseChannel<Record<string, BaseMessage<import("@langchain/core/messages").MessageStructure<import("@langchain/core/messages").MessageToolSet>, import("@langchain/core/messages").MessageType>[]>, Record<string, BaseMessage<import("@langchain/core/messages").MessageStructure<import("@langchain/core/messages").MessageToolSet>, import("@langchain/core/messages").MessageType>[]> | import("@langchain/langgraph").OverwriteValue<Record<string, BaseMessage<import("@langchain/core/messages").MessageStructure<import("@langchain/core/messages").MessageToolSet>, import("@langchain/core/messages").MessageType>[]>>, unknown>;
19
23
  currentNode: import("@langchain/langgraph").BaseChannel<CurrentNode, CurrentNode | import("@langchain/langgraph").OverwriteValue<CurrentNode>, unknown>;
20
24
  config: import("@langchain/langgraph").BaseChannel<Record<string, unknown>, Record<string, unknown> | import("@langchain/langgraph").OverwriteValue<Record<string, unknown>>, unknown>;
@@ -1,8 +1,12 @@
1
1
  import type { BaseMessage } from "@langchain/core/messages";
2
2
  import type { GraphState } from "./graph-state.js";
3
+ import { type DeepReadonly, type JsonObject } from "./graph-context.js";
3
4
  export declare function hasNodeInvocation(owner: object): boolean;
4
5
  export declare function withNodeInvocation<State extends GraphState, Result>(owner: object, nodeId: string, state: State, run: () => Promise<Result>): Promise<Result>;
5
6
  export declare function invocationNodeId(owner: object): string;
7
+ export declare function invocationContext(owner: object): DeepReadonly<JsonObject>;
8
+ export declare function saveInvocationContext(owner: object, patch: JsonObject): void;
9
+ export declare function replaceInvocationContext(owner: object, context: JsonObject): void;
6
10
  export declare function invocationNodeState(owner: object, nodeId: string): Record<string, unknown>;
7
11
  export declare function saveInvocationNodeState(owner: object, nodeId: string, patch: Record<string, unknown>): void;
8
12
  export declare function replaceInvocationNodeState(owner: object, nodeId: string, value: Record<string, unknown>): void;
@@ -1,6 +1,7 @@
1
1
  import { type StoredMessage } from '@langchain/core/messages';
2
2
  import { ConfigManager } from '../config-manager.js';
3
3
  import { type GraphState } from '../graph-state.js';
4
+ import { type JsonObject } from '../graph-context.js';
4
5
  import { type GraphLlmConfig, type GraphLlmModelMetadata } from '../graph-llm.config.js';
5
6
  import { type SessionLogs } from '../session-log.js';
6
7
  import { type TokenUsage } from '../token-usage.js';
@@ -42,6 +43,7 @@ export type SessionGraphDocument<State extends GraphState = GraphState> = {
42
43
  schemaVersion: number;
43
44
  currentNode?: State['currentNode'];
44
45
  config?: State['config'];
46
+ context?: JsonObject;
45
47
  histories: Record<string, StoredMessage[]>;
46
48
  nodes?: State['nodes'];
47
49
  model: GraphLlmModelMetadata;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@picoflow/ezgraph",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "Provider-neutral graph primitives built on LangGraph and LangChain.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",