@langchain/langgraph-api 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/experimental/embed/protocol.mjs +86 -15
  2. package/dist/graph/load.d.mts +1 -1
  3. package/dist/graph/load.utils.d.mts +1 -1
  4. package/dist/protocol/service.d.mts +9 -1
  5. package/dist/protocol/service.mjs +65 -25
  6. package/package.json +7 -7
  7. package/dist/src/api/assistants.d.mts +0 -3
  8. package/dist/src/api/assistants.mjs +0 -194
  9. package/dist/src/api/meta.d.mts +0 -3
  10. package/dist/src/api/meta.mjs +0 -65
  11. package/dist/src/api/protocol.d.mts +0 -7
  12. package/dist/src/api/protocol.mjs +0 -157
  13. package/dist/src/api/runs.d.mts +0 -3
  14. package/dist/src/api/runs.mjs +0 -335
  15. package/dist/src/api/store.d.mts +0 -3
  16. package/dist/src/api/store.mjs +0 -111
  17. package/dist/src/api/threads.d.mts +0 -3
  18. package/dist/src/api/threads.mjs +0 -143
  19. package/dist/src/graph/load.utils.d.mts +0 -22
  20. package/dist/src/graph/load.utils.mjs +0 -59
  21. package/dist/src/protocol/service.d.mts +0 -101
  22. package/dist/src/protocol/service.mjs +0 -568
  23. package/dist/src/protocol/session/event-normalizers.d.mts +0 -52
  24. package/dist/src/protocol/session/index.d.mts +0 -261
  25. package/dist/src/protocol/session/index.mjs +0 -826
  26. package/dist/src/protocol/session/namespace.d.mts +0 -47
  27. package/dist/src/protocol/session/namespace.mjs +0 -62
  28. package/dist/src/protocol/types.d.mts +0 -121
  29. package/dist/src/protocol/types.mjs +0 -1
  30. package/dist/src/schemas.d.mts +0 -1552
  31. package/dist/src/semver/index.d.mts +0 -15
  32. package/dist/src/semver/index.mjs +0 -46
  33. package/dist/src/semver/satisfiesPeerRange.d.mts +0 -1
  34. package/dist/src/semver/satisfiesPeerRange.mjs +0 -19
  35. package/dist/src/state.d.mts +0 -3
  36. package/dist/src/state.mjs +0 -30
  37. package/dist/src/storage/context.d.mts +0 -3
  38. package/dist/src/storage/context.mjs +0 -11
  39. package/dist/src/storage/ops.mjs +0 -1281
  40. package/dist/src/stream.d.mts +0 -64
  41. package/dist/src/stream.mjs +0 -427
  42. package/dist/src/utils/hono.d.mts +0 -5
  43. package/dist/src/utils/hono.mjs +0 -24
  44. package/dist/src/utils/runnableConfig.d.mts +0 -3
  45. package/dist/src/utils/runnableConfig.mjs +0 -45
  46. package/dist/src/webhook.d.mts +0 -11
  47. package/dist/src/webhook.mjs +0 -30
@@ -1,143 +0,0 @@
1
- import { zValidator } from "@hono/zod-validator";
2
- import { Hono } from "hono";
3
- import { v7 as uuid7 } from "uuid";
4
- import { z } from "zod/v3";
5
- import * as schemas from "../schemas.mjs";
6
- import { stateSnapshotToThreadState } from "../state.mjs";
7
- import { threads } from "../storage/context.mjs";
8
- import { jsonExtra } from "../utils/hono.mjs";
9
- const api = new Hono();
10
- // Threads Routes
11
- api.post("/threads", zValidator("json", schemas.ThreadCreate), async (c) => {
12
- // Create Thread
13
- const payload = c.req.valid("json");
14
- const thread = await threads().put(payload.thread_id || uuid7(), { metadata: payload.metadata, if_exists: payload.if_exists ?? "raise" }, c.var.auth);
15
- if (payload.supersteps?.length) {
16
- await threads().state.bulk({ configurable: { thread_id: thread.thread_id } }, payload.supersteps, c.var.auth);
17
- }
18
- return jsonExtra(c, thread);
19
- });
20
- api.post("/threads/search", zValidator("json", schemas.ThreadSearchRequest), async (c) => {
21
- // Search Threads
22
- const payload = c.req.valid("json");
23
- const result = [];
24
- let total = 0;
25
- for await (const item of threads().search({
26
- status: payload.status,
27
- values: payload.values,
28
- metadata: payload.metadata,
29
- ids: payload.ids,
30
- limit: payload.limit ?? 10,
31
- offset: payload.offset ?? 0,
32
- sort_by: payload.sort_by ?? "created_at",
33
- sort_order: payload.sort_order ?? "desc",
34
- select: payload.select,
35
- }, c.var.auth)) {
36
- result.push(Object.fromEntries(Object.entries(item.thread).filter(([k]) => !payload.select || payload.select.includes(k))));
37
- // Only set total if it's the first item
38
- if (total === 0) {
39
- total = item.total;
40
- }
41
- }
42
- const nextOffset = (payload.offset ?? 0) + total;
43
- if (total === payload.limit) {
44
- c.res.headers.set("X-Pagination-Next", nextOffset.toString());
45
- c.res.headers.set("X-Pagination-Total", (nextOffset + 1).toString());
46
- }
47
- else {
48
- c.res.headers.set("X-Pagination-Total", nextOffset.toString());
49
- }
50
- return jsonExtra(c, result);
51
- });
52
- api.post("/threads/count", zValidator("json", schemas.ThreadCountRequest), async (c) => {
53
- const payload = c.req.valid("json");
54
- const total = await threads().count(payload, c.var.auth);
55
- return c.json(total);
56
- });
57
- api.get("/threads/:thread_id/state", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("query", z.object({ subgraphs: schemas.coercedBoolean.optional() })), async (c) => {
58
- // Get Latest Thread State
59
- const { thread_id } = c.req.valid("param");
60
- const { subgraphs } = c.req.valid("query");
61
- const state = stateSnapshotToThreadState(await threads().state.get({ configurable: { thread_id } }, { subgraphs }, c.var.auth));
62
- return jsonExtra(c, state);
63
- });
64
- api.post("/threads/:thread_id/state", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", schemas.ThreadStateUpdate), async (c) => {
65
- // Update Thread State
66
- const { thread_id } = c.req.valid("param");
67
- const payload = c.req.valid("json");
68
- const config = { configurable: { thread_id } };
69
- if (payload.checkpoint_id) {
70
- config.configurable ??= {};
71
- config.configurable.checkpoint_id = payload.checkpoint_id;
72
- }
73
- if (payload.checkpoint) {
74
- config.configurable ??= {};
75
- Object.assign(config.configurable, payload.checkpoint);
76
- }
77
- const inserted = await threads().state.post(config, payload.values, payload.as_node, c.var.auth);
78
- return jsonExtra(c, inserted);
79
- });
80
- api.get("/threads/:thread_id/state/:checkpoint_id", zValidator("param", z.object({
81
- thread_id: z.string().uuid(),
82
- checkpoint_id: z.string().uuid(),
83
- })), zValidator("query", z.object({ subgraphs: schemas.coercedBoolean.optional() })), async (c) => {
84
- // Get Thread State At Checkpoint
85
- const { thread_id, checkpoint_id } = c.req.valid("param");
86
- const { subgraphs } = c.req.valid("query");
87
- const state = stateSnapshotToThreadState(await threads().state.get({ configurable: { thread_id, checkpoint_id } }, { subgraphs }, c.var.auth));
88
- return jsonExtra(c, state);
89
- });
90
- api.post("/threads/:thread_id/state/checkpoint", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", z.object({
91
- subgraphs: schemas.coercedBoolean.optional(),
92
- checkpoint: schemas.CheckpointSchema.nullish(),
93
- })), async (c) => {
94
- // Get Thread State At Checkpoint Post
95
- const { thread_id } = c.req.valid("param");
96
- const { checkpoint, subgraphs } = c.req.valid("json");
97
- const state = stateSnapshotToThreadState(await threads().state.get({ configurable: { thread_id, ...checkpoint } }, { subgraphs }, c.var.auth));
98
- return jsonExtra(c, state);
99
- });
100
- api.get("/threads/:thread_id/history", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("query", z.object({
101
- limit: z
102
- .string()
103
- .optional()
104
- .default("10")
105
- .transform((value) => parseInt(value, 10)),
106
- before: z.string().optional(),
107
- })), async (c) => {
108
- // Get Thread History
109
- const { thread_id } = c.req.valid("param");
110
- const { limit, before } = c.req.valid("query");
111
- const states = await threads().state.list({ configurable: { thread_id, checkpoint_ns: "" } }, { limit, before }, c.var.auth);
112
- return jsonExtra(c, states.map(stateSnapshotToThreadState));
113
- });
114
- api.post("/threads/:thread_id/history", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", schemas.ThreadHistoryRequest), async (c) => {
115
- // Get Thread History Post
116
- const { thread_id } = c.req.valid("param");
117
- const { limit, before, metadata, checkpoint } = c.req.valid("json");
118
- const states = await threads().state.list({ configurable: { thread_id, checkpoint_ns: "", ...checkpoint } }, { limit, before, metadata }, c.var.auth);
119
- return jsonExtra(c, states.map(stateSnapshotToThreadState));
120
- });
121
- api.get("/threads/:thread_id", zValidator("param", z.object({ thread_id: z.string().uuid() })), async (c) => {
122
- // Get Thread
123
- const { thread_id } = c.req.valid("param");
124
- return jsonExtra(c, await threads().get(thread_id, c.var.auth));
125
- });
126
- api.delete("/threads/:thread_id", zValidator("param", z.object({ thread_id: z.string().uuid() })), async (c) => {
127
- // Delete Thread
128
- const { thread_id } = c.req.valid("param");
129
- await threads().delete(thread_id, c.var.auth);
130
- return new Response(null, { status: 204 });
131
- });
132
- api.patch("/threads/:thread_id", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", schemas.ThreadPatchRequest), async (c) => {
133
- // Patch Thread
134
- const { thread_id } = c.req.valid("param");
135
- const { metadata } = c.req.valid("json");
136
- return jsonExtra(c, await threads().patch(thread_id, { metadata }, c.var.auth));
137
- });
138
- api.post("/threads/:thread_id/copy", zValidator("param", z.object({ thread_id: z.string().uuid() })), async (c) => {
139
- // Copy Thread
140
- const { thread_id } = c.req.valid("param");
141
- return jsonExtra(c, await threads().copy(thread_id, c.var.auth));
142
- });
143
- export default api;
@@ -1,22 +0,0 @@
1
- import type { CompiledGraph } from "@langchain/langgraph";
2
- export declare const GRAPHS: Record<string, CompiledGraph<string>>;
3
- export declare const NAMESPACE_GRAPH: Uint8Array<ArrayBufferLike>;
4
- export type CompiledGraphFactory<T extends string> = (config: {
5
- configurable?: Record<string, unknown>;
6
- }) => Promise<CompiledGraph<T>>;
7
- export declare function resolveGraph(spec: string, options: {
8
- cwd: string;
9
- onlyFilePresence?: false;
10
- }): Promise<{
11
- sourceFile: string;
12
- exportSymbol: string;
13
- resolved: CompiledGraph<string> | CompiledGraphFactory<string>;
14
- }>;
15
- export declare function resolveGraph(spec: string, options: {
16
- cwd: string;
17
- onlyFilePresence: true;
18
- }): Promise<{
19
- sourceFile: string;
20
- exportSymbol: string;
21
- resolved: undefined;
22
- }>;
@@ -1,59 +0,0 @@
1
- import * as uuid from "uuid";
2
- import * as path from "node:path";
3
- import * as fs from "node:fs/promises";
4
- import { pathToFileURL } from "node:url";
5
- export const GRAPHS = {};
6
- export const NAMESPACE_GRAPH = uuid.parse("6ba7b821-9dad-11d1-80b4-00c04fd430c8");
7
- export async function resolveGraph(spec, options) {
8
- const [userFile, exportSymbol] = spec.split(":", 2);
9
- const sourceFile = path.resolve(options.cwd, userFile);
10
- // validate file exists
11
- await fs.stat(sourceFile);
12
- if (options?.onlyFilePresence) {
13
- return { sourceFile, exportSymbol, resolved: undefined };
14
- }
15
- const isGraph = (graph) => {
16
- if (typeof graph !== "object" || graph == null)
17
- return false;
18
- return "compile" in graph && typeof graph.compile === "function";
19
- };
20
- const isCompiledGraph = (graph) => {
21
- if (typeof graph !== "object" || graph == null)
22
- return false;
23
- return ("builder" in graph &&
24
- typeof graph.builder === "object" &&
25
- graph.builder != null);
26
- };
27
- const graph = await import(pathToFileURL(sourceFile).toString()).then((module) => module[exportSymbol || "default"]);
28
- // obtain the graph, and if not compiled, compile it
29
- const resolved = await (async () => {
30
- if (!graph)
31
- throw new Error("Failed to load graph: graph is nullush");
32
- const afterResolve = (graphLike) => {
33
- const graph = isGraph(graphLike) ? graphLike.compile() : graphLike;
34
- // TODO: hack, remove once LangChain 1.x createAgent is fixed.
35
- // `createAgent` returns a ReactAgent wrapper that itself looks
36
- // like a CompiledGraph (it has a `builder` — the outer
37
- // StateGraph) *and* exposes the real compiled pregel under
38
- // `.graph`. Unwrap to the inner graph whenever both are
39
- // present so downstream code (e.g. the v2 streaming path that
40
- // keys off `graph.streamTransformers`) sees the actual pregel
41
- // rather than the wrapper.
42
- const inner = graph.graph;
43
- if (inner != null &&
44
- typeof inner === "object" &&
45
- isCompiledGraph(inner)) {
46
- return inner;
47
- }
48
- return graph;
49
- };
50
- if (typeof graph === "function") {
51
- return async (config) => {
52
- const graphLike = await graph(config);
53
- return afterResolve(graphLike);
54
- };
55
- }
56
- return afterResolve(await graph);
57
- })();
58
- return { sourceFile, exportSymbol, resolved };
59
- }
@@ -1,101 +0,0 @@
1
- import type { RunsRepo, ThreadsRepo } from "../storage/types.mjs";
2
- import type { EventSinkEntry, EventSinkFilter, ProtocolCommand, ProtocolError, ProtocolEvent, ProtocolSuccess, ThreadRecord, ProtocolTransportName } from "./types.mjs";
3
- type ServiceBindings = {
4
- runs: RunsRepo;
5
- threads: ThreadsRepo;
6
- };
7
- /**
8
- * Transport-agnostic sink used to forward normalized protocol events into a
9
- * concrete delivery mechanism such as WebSocket or SSE.
10
- */
11
- type EventSink = (message: ProtocolEvent) => Promise<void> | void;
12
- /**
13
- * Thread-scoped connection registry and command dispatcher.
14
- *
15
- * In the thread-centric protocol, a `ThreadRecord` holds ephemeral
16
- * connection state for an active client interacting with a thread. The
17
- * thread itself is durable (lives in the checkpoint store); records are
18
- * created lazily on first interaction and dropped when all connections
19
- * close.
20
- */
21
- export declare class ProtocolService {
22
- private readonly bindings;
23
- private readonly threads;
24
- constructor(bindings: ServiceBindings);
25
- getThread(threadId: string): ThreadRecord | undefined;
26
- /**
27
- * Get or create the in-memory record for a thread. Records hold
28
- * ephemeral connection state (event sinks, current run session) and
29
- * are created on first use for any thread the client targets.
30
- */
31
- ensureThread(options: {
32
- threadId: string;
33
- transport: ProtocolTransportName;
34
- auth?: ThreadRecord["auth"];
35
- sendEvent?: EventSink;
36
- }): ThreadRecord;
37
- /**
38
- * Attach a live transport consumer (WebSocket) and flush any buffered
39
- * events.
40
- */
41
- attachEventSink(threadId: string, sendEvent: EventSink): Promise<ThreadRecord>;
42
- /**
43
- * Attach a filtered SSE event sink and replay buffered events that
44
- * match the filter.
45
- *
46
- * The sink is flagged `pendingReplay` while draining so that the live
47
- * `send` path skips it — preventing live events from interleaving with
48
- * the replay loop's awaits and producing out-of-order delivery.
49
- */
50
- attachFilteredEventSink(threadId: string, sink: EventSinkEntry): Promise<ThreadRecord>;
51
- /**
52
- * Remove an SSE event sink when the connection closes.
53
- */
54
- detachEventSink(threadId: string, sinkId: string): void;
55
- closeThread(threadId: string): Promise<void>;
56
- /**
57
- * Route a protocol command on a thread.
58
- *
59
- * `subscription.subscribe` can resolve to `null` on ordered
60
- * transports (WebSocket) — see
61
- * `ProtocolSession.handleSubscribeForResponse` for the rationale.
62
- * Callers must treat `null` as "response already sent on the wire"
63
- * and skip any additional send.
64
- */
65
- handleCommand(threadId: string, command: ProtocolCommand): Promise<ProtocolSuccess | ProtocolError | null>;
66
- /**
67
- * Start a new run, resume an interrupted run, or continue on the
68
- * thread depending on its current state.
69
- */
70
- private handleRunStart;
71
- private handleInputRespond;
72
- private createOrResumeRun;
73
- private hasPendingInterrupts;
74
- private hasPendingInterruptsForThread;
75
- private handleStateGet;
76
- private forwardToRunSession;
77
- /**
78
- * Drain any WebSocket subscribes that arrived before the first run
79
- * session was bound. Called from `createOrResumeRun` right after
80
- * {@link ensureRunSession} sets up `record.session`.
81
- *
82
- * Each parked command is forwarded to the freshly-bound session,
83
- * added to `activeSubscriptions` so it persists across subsequent
84
- * runs, and its deferred `handleCommand` promise is resolved so the
85
- * WebSocket handler can finally send the response.
86
- */
87
- private drainPendingSubscribes;
88
- /**
89
- * Bind the thread record to a concrete LangGraph run and forward
90
- * normalized protocol events to attached sinks.
91
- */
92
- private ensureRunSession;
93
- private requireThread;
94
- error(id: number | null, code: ProtocolError["error"], message: string): ProtocolError;
95
- }
96
- /**
97
- * Check whether a protocol event matches an SSE event sink filter.
98
- * Mirrors the subscription matching logic in {@link RunProtocolSession}.
99
- */
100
- export declare function matchesSinkFilter(filter: EventSinkFilter, event: ProtocolEvent): boolean;
101
- export {};