@langchain/langgraph-cli 0.0.8 → 0.0.10

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 (39) hide show
  1. package/LICENSE +21 -93
  2. package/dist/cli/build.mjs +1 -1
  3. package/dist/cli/cli.mjs +0 -0
  4. package/dist/cli/dev.mjs +3 -3
  5. package/dist/cli/dev.python.mjs +1 -1
  6. package/dist/cli/docker.mjs +1 -1
  7. package/dist/cli/up.mjs +1 -1
  8. package/dist/{logging.mjs → utils/logging.mjs} +0 -4
  9. package/package.json +16 -32
  10. package/dist/api/assistants.mjs +0 -144
  11. package/dist/api/runs.mjs +0 -239
  12. package/dist/api/store.mjs +0 -83
  13. package/dist/api/threads.mjs +0 -143
  14. package/dist/cli/dev.node.entrypoint.mjs +0 -42
  15. package/dist/cli/dev.node.mjs +0 -35
  16. package/dist/cli/utils/ipc/client.mjs +0 -47
  17. package/dist/graph/load.hooks.mjs +0 -17
  18. package/dist/graph/load.mjs +0 -72
  19. package/dist/graph/load.utils.mjs +0 -50
  20. package/dist/graph/parser/parser.mjs +0 -308
  21. package/dist/graph/parser/parser.worker.mjs +0 -7
  22. package/dist/graph/parser/schema/types.mjs +0 -1607
  23. package/dist/graph/parser/schema/types.template.mts +0 -83
  24. package/dist/preload.mjs +0 -3
  25. package/dist/queue.mjs +0 -93
  26. package/dist/schemas.mjs +0 -407
  27. package/dist/server.mjs +0 -74
  28. package/dist/state.mjs +0 -32
  29. package/dist/storage/checkpoint.mjs +0 -127
  30. package/dist/storage/ops.mjs +0 -792
  31. package/dist/storage/persist.mjs +0 -69
  32. package/dist/storage/store.mjs +0 -41
  33. package/dist/stream.mjs +0 -215
  34. package/dist/utils/abort.mjs +0 -8
  35. package/dist/utils/error.mjs +0 -1
  36. package/dist/utils/hono.mjs +0 -27
  37. package/dist/utils/importMap.mjs +0 -55
  38. package/dist/utils/runnableConfig.mjs +0 -45
  39. package/dist/utils/serde.mjs +0 -20
package/LICENSE CHANGED
@@ -1,93 +1,21 @@
1
- Elastic License 2.0
2
-
3
- URL: https://www.elastic.co/licensing/elastic-license
4
-
5
- ## Acceptance
6
-
7
- By using the software, you agree to all of the terms and conditions below.
8
-
9
- ## Copyright License
10
-
11
- The licensor grants you a non-exclusive, royalty-free, worldwide,
12
- non-sublicensable, non-transferable license to use, copy, distribute, make
13
- available, and prepare derivative works of the software, in each case subject to
14
- the limitations and conditions below.
15
-
16
- ## Limitations
17
-
18
- You may not provide the software to third parties as a hosted or managed
19
- service, where the service provides users with access to any substantial set of
20
- the features or functionality of the software.
21
-
22
- You may not move, change, disable, or circumvent the license key functionality
23
- in the software, and you may not remove or obscure any functionality in the
24
- software that is protected by the license key.
25
-
26
- You may not alter, remove, or obscure any licensing, copyright, or other notices
27
- of the licensor in the software. Any use of the licensor’s trademarks is subject
28
- to applicable law.
29
-
30
- ## Patents
31
-
32
- The licensor grants you a license, under any patent claims the licensor can
33
- license, or becomes able to license, to make, have made, use, sell, offer for
34
- sale, import and have imported the software, in each case subject to the
35
- limitations and conditions in this license. This license does not cover any
36
- patent claims that you cause to be infringed by modifications or additions to
37
- the software. If you or your company make any written claim that the software
38
- infringes or contributes to infringement of any patent, your patent license for
39
- the software granted under these terms ends immediately. If your company makes
40
- such a claim, your patent license ends immediately for work on behalf of your
41
- company.
42
-
43
- ## Notices
44
-
45
- You must ensure that anyone who gets a copy of any part of the software from you
46
- also gets a copy of these terms.
47
-
48
- If you modify the software, you must include in any modified copies of the
49
- software prominent notices stating that you have modified the software.
50
-
51
- ## No Other Rights
52
-
53
- These terms do not imply any licenses other than those expressly granted in
54
- these terms.
55
-
56
- ## Termination
57
-
58
- If you use the software in violation of these terms, such use is not licensed,
59
- and your licenses will automatically terminate. If the licensor provides you
60
- with a notice of your violation, and you cease all violation of this license no
61
- later than 30 days after you receive that notice, your licenses will be
62
- reinstated retroactively. However, if you violate these terms after such
63
- reinstatement, any additional violation of these terms will cause your licenses
64
- to terminate automatically and permanently.
65
-
66
- ## No Liability
67
-
68
- *As far as the law allows, the software comes as is, without any warranty or
69
- condition, and the licensor will not be liable to you for any damages arising
70
- out of these terms or the use or nature of the software, under any kind of
71
- legal claim.*
72
-
73
- ## Definitions
74
-
75
- The **licensor** is the entity offering these terms, and the **software** is the
76
- software the licensor makes available under these terms, including any portion
77
- of it.
78
-
79
- **you** refers to the individual or entity agreeing to these terms.
80
-
81
- **your company** is any legal entity, sole proprietorship, or other kind of
82
- organization that you work for, plus all organizations that have control over,
83
- are under the control of, or are under common control with that
84
- organization. **control** means ownership of substantially all the assets of an
85
- entity, or the power to direct its management and policies by vote, contract, or
86
- otherwise. Control can be direct or indirect.
87
-
88
- **your licenses** are all the licenses granted to you for the software under
89
- these terms.
90
-
91
- **use** means anything you do with the software requiring one of your licenses.
92
-
93
- **trademark** means trademarks, service marks, and similar rights.
1
+ MIT License Copyright (c) 2025 LangChain
2
+
3
+ Permission is hereby granted, free
4
+ of charge, to any person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the Software without
6
+ restriction, including without limitation the rights to use, copy, modify, merge,
7
+ publish, distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to the
9
+ following conditions:
10
+
11
+ The above copyright notice and this permission notice
12
+ (including the next paragraph) shall be included in all copies or substantial
13
+ portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
16
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
18
+ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
19
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -7,7 +7,7 @@ import { getProjectPath } from "./utils/project.mjs";
7
7
  import { $ } from "execa";
8
8
  import * as path from "node:path";
9
9
  import * as fs from "node:fs/promises";
10
- import { logger } from "../logging.mjs";
10
+ import { logger } from "../utils/logging.mjs";
11
11
  import { withAnalytics } from "./utils/analytics.mjs";
12
12
  const stream = (proc) => {
13
13
  logger.info(`Running "${proc.spawnargs.join(" ")}"`);
package/dist/cli/cli.mjs CHANGED
File without changes
package/dist/cli/dev.mjs CHANGED
@@ -8,7 +8,7 @@ import { createIpcServer } from "./utils/ipc/server.mjs";
8
8
  import { getProjectPath } from "./utils/project.mjs";
9
9
  import { getConfig } from "../utils/config.mjs";
10
10
  import { builder } from "./utils/builder.mjs";
11
- import { logError, logger } from "../logging.mjs";
11
+ import { logError, logger } from "../utils/logging.mjs";
12
12
  import { withAnalytics } from "./utils/analytics.mjs";
13
13
  builder
14
14
  .command("dev")
@@ -101,8 +101,8 @@ builder
101
101
  child = await spawnPythonServer({ ...options, rest: args }, { configPath, config, env, hostUrl }, { pid, projectCwd });
102
102
  }
103
103
  else {
104
- const { spawnNodeServer } = await import("./dev.node.mjs");
105
- child = await spawnNodeServer({ ...options, rest: args }, { configPath, config, env, hostUrl }, { pid, projectCwd });
104
+ const { spawnServer } = await import("@langchain/langgraph-api");
105
+ child = await spawnServer(options, { config, env, hostUrl }, { pid, projectCwd });
106
106
  }
107
107
  };
108
108
  watcher.on("all", async (_name, path) => {
@@ -6,7 +6,7 @@ import path from "node:path";
6
6
  import os from "node:os";
7
7
  import { extract as tarExtract } from "tar";
8
8
  import zipExtract from "extract-zip";
9
- import { logger } from "../logging.mjs";
9
+ import { logger } from "../utils/logging.mjs";
10
10
  import { assembleLocalDeps } from "../docker/docker.mjs";
11
11
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
12
  const UV_VERSION = "0.5.20";
@@ -6,7 +6,7 @@ import { builder } from "./utils/builder.mjs";
6
6
  import * as fs from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import dedent from "dedent";
9
- import { logger } from "../logging.mjs";
9
+ import { logger } from "../utils/logging.mjs";
10
10
  import { withAnalytics } from "./utils/analytics.mjs";
11
11
  const fileExists = async (path) => {
12
12
  try {
package/dist/cli/up.mjs CHANGED
@@ -3,7 +3,7 @@ import * as fs from "node:fs/promises";
3
3
  import * as path from "node:path";
4
4
  import { getConfig } from "../utils/config.mjs";
5
5
  import { getProjectPath } from "./utils/project.mjs";
6
- import { logger } from "../logging.mjs";
6
+ import { logger } from "../utils/logging.mjs";
7
7
  import { createCompose, getDockerCapabilities } from "../docker/compose.mjs";
8
8
  import { configToCompose, getBaseImage } from "../docker/docker.mjs";
9
9
  import { getExecaOptions } from "../docker/shell.mjs";
@@ -1,5 +1,4 @@
1
1
  import { createLogger, format, transports } from "winston";
2
- import { logger as honoLogger } from "hono/logger";
3
2
  import { consoleFormat } from "winston-console-format";
4
3
  import { parse as stacktraceParser } from "stacktrace-parser";
5
4
  import { readFileSync } from "fs";
@@ -95,6 +94,3 @@ export const logError = (error, options) => {
95
94
  };
96
95
  process.on("uncaughtException", (error) => logError(error));
97
96
  process.on("unhandledRejection", (error) => logError(error));
98
- export const requestLogger = () => honoLogger((message, ...rest) => {
99
- logger.info(message, ...rest);
100
- });
package/package.json CHANGED
@@ -1,34 +1,21 @@
1
1
  {
2
2
  "name": "@langchain/langgraph-cli",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=18"
7
7
  },
8
- "license": "Elastic-2.0",
8
+ "license": "MIT",
9
9
  "main": "./dist/server.mjs",
10
+ "types": "./dist/server.d.mts",
10
11
  "bin": {
11
12
  "langgraphjs": "dist/cli/cli.mjs"
12
13
  },
13
14
  "files": [
14
15
  "dist/"
15
16
  ],
16
- "scripts": {
17
- "build": "node scripts/spawn.mjs build",
18
- "prepack": "pnpm run build",
19
- "typecheck": "tsc --noEmit",
20
- "cli": "tsx src/cli/cli.mts",
21
- "cli:watch": "tsx watch src/cli/cli.mts",
22
- "test:cli": "pnpm run cli dev --no-browser --config ./tests/graphs/langgraph.json",
23
- "test": "vitest",
24
- "test:ci": "node scripts/spawn.mjs test"
25
- },
26
17
  "dependencies": {
27
18
  "@commander-js/extra-typings": "^13.0.0",
28
- "@hono/node-server": "^1.12.0",
29
- "@hono/zod-validator": "^0.2.2",
30
- "@types/json-schema": "^7.0.15",
31
- "@typescript/vfs": "^1.6.0",
32
19
  "chokidar": "^4.0.3",
33
20
  "commander": "^13.0.0",
34
21
  "dedent": "^1.5.3",
@@ -36,33 +23,30 @@
36
23
  "execa": "^9.5.2",
37
24
  "exit-hook": "^4.0.0",
38
25
  "extract-zip": "^2.0.1",
39
- "hono": "^4.5.4",
40
26
  "langsmith": "^0.2.15",
41
27
  "open": "^10.1.0",
42
28
  "stacktrace-parser": "^0.1.10",
43
- "superjson": "^2.2.2",
44
29
  "tar": "^7.4.3",
45
- "tsx": "^4.19.2",
46
- "uuid": "^10.0.0",
47
30
  "winston": "^3.17.0",
48
31
  "winston-console-format": "^1.0.8",
49
32
  "yaml": "^2.7.0",
50
33
  "zod": "^3.23.8",
51
- "@babel/code-frame": "^7.26.2"
52
- },
53
- "peerDependencies": {
54
- "@langchain/core": "^0.3.36",
55
- "@langchain/langgraph": "^0.2.43",
56
- "@langchain/langgraph-checkpoint": "^0.0.14",
57
- "typescript": "^5.5.4"
34
+ "@babel/code-frame": "^7.26.2",
35
+ "@langchain/langgraph-api": "0.0.10"
58
36
  },
59
37
  "devDependencies": {
60
- "@langchain/langgraph-sdk": "^0.0.33",
38
+ "tsx": "^4.19.2",
61
39
  "@types/babel__code-frame": "^7.0.6",
62
40
  "@types/node": "^22.2.0",
63
- "@types/uuid": "^10.0.0",
64
- "postgres": "^3.4.5",
65
41
  "prettier": "^3.3.3",
66
- "vitest": "^2.1.8"
42
+ "vitest": "^3.0.5",
43
+ "typescript": "^5.5.4"
44
+ },
45
+ "scripts": {
46
+ "build": "npx -y bun scripts/build.mjs",
47
+ "typecheck": "tsc --noEmit",
48
+ "cli": "tsx src/cli/cli.mts",
49
+ "cli:watch": "tsx watch src/cli/cli.mts",
50
+ "test": "vitest"
67
51
  }
68
- }
52
+ }
@@ -1,144 +0,0 @@
1
- import { Hono } from "hono";
2
- import { zValidator } from "@hono/zod-validator";
3
- import { v4 as uuid } from "uuid";
4
- import { z } from "zod";
5
- import { getAssistantId, getGraph, getGraphSchema } from "../graph/load.mjs";
6
- import { Assistants } from "../storage/ops.mjs";
7
- import * as schemas from "../schemas.mjs";
8
- import { HTTPException } from "hono/http-exception";
9
- const api = new Hono();
10
- api.post("/assistants", zValidator("json", schemas.AssistantCreate), async (c) => {
11
- // Create Assistant
12
- const payload = c.req.valid("json");
13
- const assistant = await Assistants.put(payload.assistant_id ?? uuid(), {
14
- config: payload.config ?? {},
15
- graph_id: payload.graph_id,
16
- metadata: payload.metadata ?? {},
17
- if_exists: payload.if_exists ?? "raise",
18
- name: payload.name ?? "Untitled",
19
- });
20
- return c.json(assistant);
21
- });
22
- api.post("/assistants/search", zValidator("json", schemas.AssistantSearchRequest), async (c) => {
23
- // Search Assistants
24
- const payload = c.req.valid("json");
25
- const result = [];
26
- for await (const item of Assistants.search({
27
- graph_id: payload.graph_id,
28
- metadata: payload.metadata,
29
- limit: payload.limit ?? 10,
30
- offset: payload.offset ?? 0,
31
- })) {
32
- result.push(item);
33
- }
34
- return c.json(result);
35
- });
36
- api.get("/assistants/:assistant_id", async (c) => {
37
- // Get Assistant
38
- const assistantId = getAssistantId(c.req.param("assistant_id"));
39
- return c.json(await Assistants.get(assistantId));
40
- });
41
- api.delete("/assistants/:assistant_id", async (c) => {
42
- // Delete Assistant
43
- const assistantId = getAssistantId(c.req.param("assistant_id"));
44
- return c.json(await Assistants.delete(assistantId));
45
- });
46
- api.patch("/assistants/:assistant_id", zValidator("json", schemas.AssistantPatch), async (c) => {
47
- // Patch Assistant
48
- const assistantId = getAssistantId(c.req.param("assistant_id"));
49
- const payload = c.req.valid("json");
50
- return c.json(await Assistants.patch(assistantId, payload));
51
- });
52
- const RunnableConfigSchema = z.object({
53
- tags: z.array(z.string()).optional(),
54
- metadata: z.record(z.unknown()).optional(),
55
- run_name: z.string().optional(),
56
- max_concurrency: z.number().optional(),
57
- recursion_limit: z.number().optional(),
58
- configurable: z.record(z.unknown()).optional(),
59
- run_id: z.string().uuid().optional(),
60
- });
61
- const getRunnableConfig = (userConfig) => {
62
- if (!userConfig)
63
- return {};
64
- return {
65
- configurable: userConfig.configurable,
66
- tags: userConfig.tags,
67
- metadata: userConfig.metadata,
68
- runName: userConfig.run_name,
69
- maxConcurrency: userConfig.max_concurrency,
70
- recursionLimit: userConfig.recursion_limit,
71
- runId: userConfig.run_id,
72
- };
73
- };
74
- api.get("/assistants/:assistant_id/graph", zValidator("query", z.object({ xray: schemas.coercedBoolean.optional() })), async (c) => {
75
- // Get Assistant Graph
76
- const assistantId = getAssistantId(c.req.param("assistant_id"));
77
- const assistant = await Assistants.get(assistantId);
78
- const { xray } = c.req.valid("query");
79
- const graph = getGraph(assistant.graph_id);
80
- return c.json(graph.getGraph({ ...getRunnableConfig(assistant.config), xray }).toJSON());
81
- });
82
- api.get("/assistants/:assistant_id/schemas", async (c) => {
83
- // Get Assistant Schemas
84
- const assistantId = getAssistantId(c.req.param("assistant_id"));
85
- const assistant = await Assistants.get(assistantId);
86
- const graphSchema = await getGraphSchema(assistant.graph_id);
87
- const rootGraphId = Object.keys(graphSchema).find((i) => !i.includes("|"));
88
- if (!rootGraphId)
89
- throw new Error("Failed to find root graph");
90
- const rootGraphSchema = graphSchema[rootGraphId];
91
- return c.json({
92
- graph_id: assistant.graph_id,
93
- input_schema: rootGraphSchema.input,
94
- output_schema: rootGraphSchema.output,
95
- state_schema: rootGraphSchema.state,
96
- config_schema: rootGraphSchema.config,
97
- });
98
- });
99
- api.get("/assistants/:assistant_id/subgraphs/:namespace?", zValidator("param", z.object({ assistant_id: z.string(), namespace: z.string().optional() })), zValidator("query", z.object({ recurse: schemas.coercedBoolean.optional() })), async (c) => {
100
- // Get Assistant Subgraphs
101
- const { assistant_id, namespace } = c.req.valid("param");
102
- const { recurse } = c.req.valid("query");
103
- const assistantId = getAssistantId(assistant_id);
104
- const assistant = await Assistants.get(assistantId);
105
- const graph = getGraph(assistant.graph_id);
106
- const graphSchema = await getGraphSchema(assistant.graph_id);
107
- const rootGraphId = Object.keys(graphSchema).find((i) => !i.includes("|"));
108
- if (!rootGraphId) {
109
- throw new HTTPException(404, { message: "Failed to find root graph" });
110
- }
111
- const result = [];
112
- const subgraphsGenerator = "getSubgraphsAsync" in graph
113
- ? graph.getSubgraphsAsync.bind(graph)
114
- : // @ts-expect-error older versions of langgraph don't have getSubgraphsAsync
115
- graph.getSubgraphs.bind(graph);
116
- for await (const [ns] of subgraphsGenerator(namespace, recurse)) {
117
- result.push([
118
- ns,
119
- graphSchema[`${rootGraphId}|${ns}`] || graphSchema[rootGraphId],
120
- ]);
121
- }
122
- return c.json(Object.fromEntries(result));
123
- });
124
- api.post("/assistants/:assistant_id/latest", zValidator("json", schemas.AssistantLatestVersion), async (c) => {
125
- // Set Latest Assistant Version
126
- const assistantId = getAssistantId(c.req.param("assistant_id"));
127
- const { version } = c.req.valid("json");
128
- return c.json(await Assistants.setLatest(assistantId, version));
129
- });
130
- api.post("/assistants/:assistant_id/versions", zValidator("json", z.object({
131
- limit: z.number().min(1).max(1000).optional().default(10),
132
- offset: z.number().min(0).optional().default(0),
133
- metadata: z.record(z.unknown()).optional(),
134
- })), async (c) => {
135
- // Get Assistant Versions
136
- const assistantId = getAssistantId(c.req.param("assistant_id"));
137
- const { limit, offset, metadata } = c.req.valid("json");
138
- return c.json(await Assistants.getVersions(assistantId, {
139
- limit,
140
- offset,
141
- metadata,
142
- }));
143
- });
144
- export default api;
package/dist/api/runs.mjs DELETED
@@ -1,239 +0,0 @@
1
- import { Hono } from "hono";
2
- import { HTTPException } from "hono/http-exception";
3
- import { streamSSE } from "hono/streaming";
4
- import { getAssistantId } from "../graph/load.mjs";
5
- import { zValidator } from "@hono/zod-validator";
6
- import * as schemas from "../schemas.mjs";
7
- import { z } from "zod";
8
- import { Runs, Threads } from "../storage/ops.mjs";
9
- import { serialiseAsDict } from "../utils/serde.mjs";
10
- import { getDisconnectAbortSignal, jsonExtra, waitKeepAlive, } from "../utils/hono.mjs";
11
- import { logError, logger } from "../logging.mjs";
12
- import { v4 as uuid4 } from "uuid";
13
- const api = new Hono();
14
- const createValidRun = async (threadId, payload) => {
15
- const { assistant_id: assistantId, ...run } = payload;
16
- const runId = uuid4();
17
- const streamMode = Array.isArray(payload.stream_mode)
18
- ? payload.stream_mode
19
- : payload.stream_mode != null
20
- ? [payload.stream_mode]
21
- : [];
22
- if (streamMode.length === 0)
23
- streamMode.push("values");
24
- const multitaskStrategy = payload.multitask_strategy ?? "reject";
25
- const preventInsertInInflight = multitaskStrategy === "reject";
26
- const config = { ...run.config };
27
- if (run.checkpoint_id) {
28
- config.configurable ??= {};
29
- config.configurable.checkpoint_id = run.checkpoint_id;
30
- }
31
- if (run.checkpoint) {
32
- config.configurable ??= {};
33
- Object.assign(config.configurable, run.checkpoint);
34
- }
35
- let feedbackKeys = run.feedback_keys != null
36
- ? Array.isArray(run.feedback_keys)
37
- ? run.feedback_keys
38
- : [run.feedback_keys]
39
- : undefined;
40
- if (!feedbackKeys?.length)
41
- feedbackKeys = undefined;
42
- const [first, ...inflight] = await Runs.put(runId, getAssistantId(assistantId), {
43
- input: run.input,
44
- command: run.command,
45
- config,
46
- stream_mode: streamMode,
47
- interrupt_before: run.interrupt_before,
48
- interrupt_after: run.interrupt_after,
49
- webhook: run.webhook,
50
- feedback_keys: feedbackKeys,
51
- temporary: threadId == null && (run.on_completion ?? "delete") === "delete",
52
- subgraphs: run.stream_subgraphs ?? false,
53
- }, {
54
- threadId,
55
- metadata: run.metadata,
56
- status: "pending",
57
- multitaskStrategy,
58
- preventInsertInInflight,
59
- afterSeconds: payload.after_seconds,
60
- ifNotExists: payload.if_not_exists,
61
- });
62
- if (first?.run_id === runId) {
63
- logger.info("Created run", { run_id: runId, thread_id: threadId });
64
- if ((multitaskStrategy === "interrupt" || multitaskStrategy === "rollback") &&
65
- inflight.length > 0) {
66
- try {
67
- await Runs.cancel(threadId, inflight.map((run) => run.run_id), { action: multitaskStrategy });
68
- }
69
- catch (error) {
70
- logger.warn("Failed to cancel inflight runs, might be already cancelled", {
71
- error,
72
- run_ids: inflight.map((run) => run.run_id),
73
- thread_id: threadId,
74
- });
75
- }
76
- }
77
- return first;
78
- }
79
- else if (multitaskStrategy === "reject") {
80
- throw new HTTPException(422, {
81
- message: "Thread is already running a task. Wait for it to finish or choose a different multitask strategy.",
82
- });
83
- }
84
- throw new HTTPException(500, {
85
- message: "Unreachable state when creating run",
86
- });
87
- };
88
- api.post("/runs/crons", zValidator("json", schemas.CronCreate), async () => {
89
- // Create Thread Cron
90
- throw new HTTPException(500, { message: "Not implemented" });
91
- });
92
- api.post("/runs/crons/search", zValidator("json", schemas.CronSearch), async () => {
93
- // Search Crons
94
- throw new HTTPException(500, { message: "Not implemented" });
95
- });
96
- api.delete("/runs/crons/:cron_id", zValidator("param", z.object({ cron_id: z.string().uuid() })), async () => {
97
- // Delete Cron
98
- throw new HTTPException(500, { message: "Not implemented" });
99
- });
100
- api.post("/threads/:thread_id/runs/crons", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", schemas.CronCreate), async () => {
101
- // Create Thread Cron
102
- throw new HTTPException(500, { message: "Not implemented" });
103
- });
104
- api.post("/runs/stream", zValidator("json", schemas.RunCreate), async (c) => {
105
- // Stream Stateless Run
106
- const payload = c.req.valid("json");
107
- const run = await createValidRun(undefined, payload);
108
- return streamSSE(c, async (stream) => {
109
- const cancelOnDisconnect = payload.on_disconnect === "cancel"
110
- ? getDisconnectAbortSignal(c, stream)
111
- : undefined;
112
- try {
113
- for await (const { event, data } of Runs.Stream.join(run.run_id, undefined, { cancelOnDisconnect, ignore404: true })) {
114
- await stream.writeSSE({ data: serialiseAsDict(data), event });
115
- }
116
- }
117
- catch (error) {
118
- logError(error, { prefix: "Error streaming run" });
119
- }
120
- });
121
- });
122
- api.post("/runs/wait", zValidator("json", schemas.RunCreate), async (c) => {
123
- // Wait Stateless Run
124
- const payload = c.req.valid("json");
125
- const run = await createValidRun(undefined, payload);
126
- return waitKeepAlive(c, Runs.wait(run.run_id, undefined));
127
- });
128
- api.post("/runs", zValidator("json", schemas.RunCreate), async (c) => {
129
- // Create Stateless Run
130
- const payload = c.req.valid("json");
131
- const run = await createValidRun(undefined, payload);
132
- return jsonExtra(c, run);
133
- });
134
- api.post("/runs/batch", zValidator("json", schemas.RunBatchCreate), async (c) => {
135
- // Batch Runs
136
- const payload = c.req.valid("json");
137
- const runs = await Promise.all(payload.map((run) => createValidRun(undefined, run)));
138
- return jsonExtra(c, runs);
139
- });
140
- api.get("/threads/:thread_id/runs", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("query", z.object({
141
- limit: z.coerce.number().nullish(),
142
- offset: z.coerce.number().nullish(),
143
- status: z.string().nullish(),
144
- metadata: z.record(z.string(), z.unknown()).nullish(),
145
- })), async (c) => {
146
- // List runs
147
- const { thread_id } = c.req.valid("param");
148
- const { limit, offset, status, metadata } = c.req.valid("query");
149
- const [runs] = await Promise.all([
150
- Runs.search(thread_id, {
151
- limit,
152
- offset,
153
- status,
154
- metadata,
155
- }),
156
- Threads.get(thread_id),
157
- ]);
158
- return jsonExtra(c, runs);
159
- });
160
- api.post("/threads/:thread_id/runs", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", schemas.RunCreate), async (c) => {
161
- // Create Run
162
- const { thread_id } = c.req.valid("param");
163
- const payload = c.req.valid("json");
164
- const run = await createValidRun(thread_id, payload);
165
- return jsonExtra(c, run);
166
- });
167
- api.post("/threads/:thread_id/runs/stream", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", schemas.RunCreate), async (c) => {
168
- // Stream Run
169
- const { thread_id } = c.req.valid("param");
170
- const payload = c.req.valid("json");
171
- const run = await createValidRun(thread_id, payload);
172
- return streamSSE(c, async (stream) => {
173
- const cancelOnDisconnect = payload.on_disconnect === "cancel"
174
- ? getDisconnectAbortSignal(c, stream)
175
- : undefined;
176
- try {
177
- for await (const { event, data } of Runs.Stream.join(run.run_id, thread_id, { cancelOnDisconnect })) {
178
- await stream.writeSSE({ data: serialiseAsDict(data), event });
179
- }
180
- }
181
- catch (error) {
182
- logError(error, { prefix: "Error streaming run" });
183
- }
184
- });
185
- });
186
- api.post("/threads/:thread_id/runs/wait", zValidator("param", z.object({ thread_id: z.string().uuid() })), zValidator("json", schemas.RunCreate), async (c) => {
187
- // Wait Run
188
- const { thread_id } = c.req.valid("param");
189
- const payload = c.req.valid("json");
190
- const run = await createValidRun(thread_id, payload);
191
- return waitKeepAlive(c, Runs.join(run.run_id, thread_id));
192
- });
193
- api.get("/threads/:thread_id/runs/:run_id", zValidator("param", z.object({ thread_id: z.string().uuid(), run_id: z.string().uuid() })), async (c) => {
194
- const { thread_id, run_id } = c.req.valid("param");
195
- const [run] = await Promise.all([
196
- Runs.get(run_id, thread_id),
197
- Threads.get(thread_id),
198
- ]);
199
- return jsonExtra(c, run);
200
- });
201
- api.delete("/threads/:thread_id/runs/:run_id", zValidator("param", z.object({ thread_id: z.string().uuid(), run_id: z.string().uuid() })), async (c) => {
202
- // Delete Run
203
- const { thread_id, run_id } = c.req.valid("param");
204
- await Runs.delete(run_id, thread_id);
205
- return c.body(null, 204);
206
- });
207
- api.get("/threads/:thread_id/runs/:run_id/join", zValidator("param", z.object({ thread_id: z.string().uuid(), run_id: z.string().uuid() })), async (c) => {
208
- // Join Run Http
209
- const { thread_id, run_id } = c.req.valid("param");
210
- return jsonExtra(c, await Runs.join(run_id, thread_id));
211
- });
212
- api.get("/threads/:thread_id/runs/:run_id/stream", zValidator("param", z.object({ thread_id: z.string().uuid(), run_id: z.string().uuid() })), zValidator("query", z.object({ cancel_on_disconnect: schemas.coercedBoolean.optional() })), async (c) => {
213
- // Stream Run Http
214
- const { thread_id, run_id } = c.req.valid("param");
215
- const { cancel_on_disconnect } = c.req.valid("query");
216
- return streamSSE(c, async (stream) => {
217
- const signal = cancel_on_disconnect
218
- ? getDisconnectAbortSignal(c, stream)
219
- : undefined;
220
- for await (const { event, data } of Runs.Stream.join(run_id, thread_id, {
221
- cancelOnDisconnect: signal,
222
- })) {
223
- await stream.writeSSE({ data: serialiseAsDict(data), event });
224
- }
225
- });
226
- });
227
- api.post("/threads/:thread_id/runs/:run_id/cancel", zValidator("param", z.object({ thread_id: z.string().uuid(), run_id: z.string().uuid() })), zValidator("query", z.object({
228
- wait: z.coerce.boolean().optional().default(false),
229
- action: z.enum(["interrupt", "rollback"]).optional().default("interrupt"),
230
- })), async (c) => {
231
- // Cancel Run Http
232
- const { thread_id, run_id } = c.req.valid("param");
233
- const { wait, action } = c.req.valid("query");
234
- await Runs.cancel(thread_id, [run_id], { action });
235
- if (wait)
236
- await Runs.join(run_id, thread_id);
237
- return c.body(null, wait ? 204 : 202);
238
- });
239
- export default api;