@axiom-lattice/core 1.0.45 → 1.0.50

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/dist/index.mjs CHANGED
@@ -351,10 +351,43 @@ var getModelLattice = (key) => modelLatticeManager.getModelLattice(key);
351
351
  import z from "zod";
352
352
 
353
353
  // src/tool_lattice/ToolLatticeManager.ts
354
- import {
355
- tool
356
- } from "@langchain/core/tools";
357
- import { interrupt } from "@langchain/langgraph";
354
+ import { tool } from "@langchain/core/tools";
355
+
356
+ // src/util/genUIMarkdown.ts
357
+ var genUIMarkdown = (type, data) => {
358
+ return ["```" + type, JSON.stringify(data), "```"].join("\n");
359
+ };
360
+
361
+ // src/tool_lattice/createToolApproveWrapper.ts
362
+ import { END, interrupt } from "@langchain/langgraph";
363
+ function createToolApproveWrapper(tool_config, toolExecutor) {
364
+ return async (input, exe_config) => {
365
+ const messagePrefix = "Tool execution requires approval";
366
+ const description = `${messagePrefix}
367
+
368
+ Tool: ${tool_config.name}
369
+ Args: ${JSON.stringify(input, null, 2)}`;
370
+ const md = genUIMarkdown("confirm", {
371
+ message: description,
372
+ tool_call: {
373
+ tool_call_id: exe_config.id,
374
+ tool_name: tool_config.name,
375
+ tool_args: input,
376
+ tool_config
377
+ }
378
+ });
379
+ const feedback = await interrupt(md);
380
+ if (feedback.data.action === "yes") {
381
+ return await toolExecutor(input, exe_config);
382
+ } else {
383
+ return {
384
+ goto: END
385
+ };
386
+ }
387
+ };
388
+ }
389
+
390
+ // src/tool_lattice/ToolLatticeManager.ts
358
391
  var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
359
392
  /**
360
393
  * 获取ToolLatticeManager单例实例
@@ -378,26 +411,16 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
378
411
  * @param executor 工具执行函数
379
412
  */
380
413
  registerLattice(key, config, executor) {
381
- let toolExecutor = async (input, exe_config) => {
382
- const result = await executor(input, exe_config);
383
- return result;
384
- };
414
+ let toolExecutor;
385
415
  if (config.needUserApprove) {
416
+ toolExecutor = createToolApproveWrapper(
417
+ config,
418
+ executor
419
+ );
420
+ } else {
386
421
  toolExecutor = async (input, exe_config) => {
387
- const contents = [
388
- "```confirm",
389
- JSON.stringify({
390
- message: "try to " + config.name + ",please confirm the action"
391
- }),
392
- "```"
393
- ].join("\n");
394
- const feedback = await interrupt(contents);
395
- if (feedback.data.action === "yes") {
396
- const result = await executor(input, exe_config);
397
- return result;
398
- } else {
399
- return "user denied the action";
400
- }
422
+ const result = await executor(input, exe_config);
423
+ return result;
401
424
  };
402
425
  }
403
426
  const toolLattice = {
@@ -512,7 +535,7 @@ var validateToolInput = (key, input) => toolLatticeManager.validateToolInput(key
512
535
  registerToolLattice(
513
536
  "get_current_date_time",
514
537
  {
515
- name: "\u83B7\u53D6\u5F53\u524D\u65E5\u671F\u65F6\u95F4",
538
+ name: "get_current_date_time",
516
539
  description: "\u83B7\u53D6\u5F53\u524D\u65E5\u671F\u65F6\u95F4",
517
540
  schema: z.object({})
518
541
  },
@@ -965,11 +988,6 @@ Results are returned using cat -n format, with line numbers starting at 1
965
988
  You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
966
989
  If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;
967
990
 
968
- // src/util/genUIMarkdown.ts
969
- var genUIMarkdown = (type, data) => {
970
- return ["```" + type, JSON.stringify(data), "```"].join("\n");
971
- };
972
-
973
991
  // src/deep_agent/tools.ts
974
992
  var writeTodos = tool2(
975
993
  (input, config) => {
@@ -1150,7 +1168,8 @@ function createTaskTool(inputs) {
1150
1168
  subagents,
1151
1169
  tools = {},
1152
1170
  model = getModelLattice("default")?.client,
1153
- stateSchema
1171
+ stateSchema,
1172
+ postModelHook
1154
1173
  } = inputs;
1155
1174
  if (!model) {
1156
1175
  throw new Error("Model not found");
@@ -1178,7 +1197,9 @@ function createTaskTool(inputs) {
1178
1197
  tools: subagentTools,
1179
1198
  stateSchema,
1180
1199
  messageModifier: subagent.prompt,
1181
- checkpointer: false
1200
+ // checkpointer: false,
1201
+ checkpointer: getCheckpointSaver("default"),
1202
+ postModelHook
1182
1203
  });
1183
1204
  agentsMap.set(subagent.name, reactAgent);
1184
1205
  }
@@ -1370,7 +1391,7 @@ var DeepAgentGraphBuilder = class {
1370
1391
  // src/createPlanExecuteAgent.ts
1371
1392
  import {
1372
1393
  Annotation,
1373
- END,
1394
+ END as END2,
1374
1395
  GraphInterrupt as GraphInterrupt2,
1375
1396
  START,
1376
1397
  StateGraph,
@@ -1844,7 +1865,7 @@ Only add steps to the plan that still NEED to be done. Do not return previously
1844
1865
  return "continue";
1845
1866
  }
1846
1867
  const workflow = new StateGraph(PlanExecuteState).addNode("planner", planStep).addNode("executor", executeStep).addNode("replanner", replanStep).addEdge(START, "planner").addEdge("planner", "executor").addEdge("executor", "replanner").addConditionalEdges("replanner", shouldEnd, {
1847
- end: END,
1868
+ end: END2,
1848
1869
  continue: "executor"
1849
1870
  });
1850
1871
  const compiledGraph = workflow.compile({
@@ -2171,17 +2192,333 @@ var getAllAgentConfigs = () => agentLatticeManager.getAllAgentConfigs();
2171
2192
  var validateAgentInput = (key, input) => agentLatticeManager.validateAgentInput(key, input);
2172
2193
  var getAgentClient = (key, options) => agentLatticeManager.initializeClient(key, options);
2173
2194
 
2195
+ // src/chunk_buffer_lattice/ChunkBuffer.ts
2196
+ var ChunkBuffer = class {
2197
+ };
2198
+
2199
+ // src/chunk_buffer_lattice/types.ts
2200
+ var ThreadStatus = /* @__PURE__ */ ((ThreadStatus2) => {
2201
+ ThreadStatus2["ACTIVE"] = "active";
2202
+ ThreadStatus2["COMPLETED"] = "completed";
2203
+ ThreadStatus2["ABORTED"] = "aborted";
2204
+ return ThreadStatus2;
2205
+ })(ThreadStatus || {});
2206
+
2207
+ // src/chunk_buffer_lattice/InMemoryChunkBuffer.ts
2208
+ var InMemoryChunkBuffer = class extends ChunkBuffer {
2209
+ constructor(config) {
2210
+ super();
2211
+ this.buffers = /* @__PURE__ */ new Map();
2212
+ this.config = {
2213
+ ttl: config?.ttl ?? 60 * 60 * 1e3,
2214
+ cleanupInterval: config?.cleanupInterval ?? 0
2215
+ };
2216
+ if (this.config.cleanupInterval > 0) {
2217
+ this.startCleanupTimer();
2218
+ }
2219
+ }
2220
+ /**
2221
+ * Start automatic periodic cleanup timer
2222
+ */
2223
+ startCleanupTimer() {
2224
+ if (this.config.cleanupInterval <= 0) return;
2225
+ this.cleanupTimer = setInterval(() => {
2226
+ this.cleanupExpiredThreads().catch(console.error);
2227
+ }, this.config.cleanupInterval);
2228
+ if (this.cleanupTimer.unref) {
2229
+ this.cleanupTimer.unref();
2230
+ }
2231
+ }
2232
+ /**
2233
+ * Stop cleanup timer (for cleanup/shutdown)
2234
+ */
2235
+ stopCleanupTimer() {
2236
+ if (this.cleanupTimer) {
2237
+ clearInterval(this.cleanupTimer);
2238
+ this.cleanupTimer = void 0;
2239
+ }
2240
+ }
2241
+ /**
2242
+ * Check if a buffer is expired (lazy cleanup helper)
2243
+ */
2244
+ isExpired(buffer) {
2245
+ return buffer.expiresAt <= Date.now();
2246
+ }
2247
+ /**
2248
+ * Get buffer if valid, perform lazy cleanup if expired
2249
+ */
2250
+ getBufferIfValid(threadId) {
2251
+ const buffer = this.buffers.get(threadId);
2252
+ if (buffer && this.isExpired(buffer)) {
2253
+ this.buffers.delete(threadId);
2254
+ return void 0;
2255
+ }
2256
+ return buffer;
2257
+ }
2258
+ /**
2259
+ * Create or get thread buffer
2260
+ */
2261
+ getOrCreateBuffer(threadId) {
2262
+ let buffer = this.getBufferIfValid(threadId);
2263
+ if (!buffer) {
2264
+ const now = Date.now();
2265
+ buffer = {
2266
+ threadId,
2267
+ chunks: [],
2268
+ status: "active" /* ACTIVE */,
2269
+ createdAt: now,
2270
+ updatedAt: now,
2271
+ expiresAt: now + this.config.ttl
2272
+ };
2273
+ this.buffers.set(threadId, buffer);
2274
+ }
2275
+ return buffer;
2276
+ }
2277
+ async addChunk(threadId, content) {
2278
+ const buffer = this.getOrCreateBuffer(threadId);
2279
+ const chunk = content;
2280
+ buffer.chunks.push(chunk);
2281
+ buffer.updatedAt = Date.now();
2282
+ buffer.expiresAt = Date.now() + this.config.ttl;
2283
+ }
2284
+ async getChunks(threadId) {
2285
+ const buffer = this.getBufferIfValid(threadId);
2286
+ return buffer ? [...buffer.chunks] : [];
2287
+ }
2288
+ async getAccumulatedContent(threadId) {
2289
+ const buffer = this.getBufferIfValid(threadId);
2290
+ if (!buffer) return "";
2291
+ return buffer.chunks.map((chunk) => chunk.data?.content).join("");
2292
+ }
2293
+ async getChunksByMessageId(threadId, messageId) {
2294
+ const buffer = this.getBufferIfValid(threadId);
2295
+ if (!buffer) return [];
2296
+ return buffer.chunks.filter((chunk) => chunk.data?.id === messageId);
2297
+ }
2298
+ async completeThread(threadId) {
2299
+ const buffer = this.getBufferIfValid(threadId);
2300
+ if (buffer) {
2301
+ buffer.status = "completed" /* COMPLETED */;
2302
+ buffer.updatedAt = Date.now();
2303
+ }
2304
+ }
2305
+ async abortThread(threadId) {
2306
+ const buffer = this.getBufferIfValid(threadId);
2307
+ if (buffer) {
2308
+ buffer.status = "aborted" /* ABORTED */;
2309
+ buffer.updatedAt = Date.now();
2310
+ }
2311
+ }
2312
+ async isThreadActive(threadId) {
2313
+ const buffer = this.getBufferIfValid(threadId);
2314
+ return buffer?.status === "active" /* ACTIVE */;
2315
+ }
2316
+ async getThreadStatus(threadId) {
2317
+ return this.getBufferIfValid(threadId)?.status;
2318
+ }
2319
+ async getThreadBuffer(threadId) {
2320
+ const buffer = this.getBufferIfValid(threadId);
2321
+ if (!buffer) return void 0;
2322
+ return {
2323
+ ...buffer,
2324
+ chunks: [...buffer.chunks]
2325
+ };
2326
+ }
2327
+ async clearThread(threadId) {
2328
+ this.buffers.delete(threadId);
2329
+ }
2330
+ async getActiveThreads() {
2331
+ const activeThreads = [];
2332
+ for (const [threadId, buffer] of this.buffers.entries()) {
2333
+ if (this.isExpired(buffer)) {
2334
+ this.buffers.delete(threadId);
2335
+ continue;
2336
+ }
2337
+ if (buffer.status === "active" /* ACTIVE */) {
2338
+ activeThreads.push(threadId);
2339
+ }
2340
+ }
2341
+ return activeThreads;
2342
+ }
2343
+ async getAllThreads() {
2344
+ const validThreads = [];
2345
+ for (const [threadId, buffer] of this.buffers.entries()) {
2346
+ if (this.isExpired(buffer)) {
2347
+ this.buffers.delete(threadId);
2348
+ } else {
2349
+ validThreads.push(threadId);
2350
+ }
2351
+ }
2352
+ return validThreads;
2353
+ }
2354
+ async hasThread(threadId) {
2355
+ return this.getBufferIfValid(threadId) !== void 0;
2356
+ }
2357
+ /**
2358
+ * Cleanup expired threads based on TTL
2359
+ * Returns number of threads cleaned up
2360
+ */
2361
+ async cleanupExpiredThreads() {
2362
+ const now = Date.now();
2363
+ let cleanedCount = 0;
2364
+ for (const [threadId, buffer] of this.buffers.entries()) {
2365
+ if (buffer.expiresAt <= now) {
2366
+ this.buffers.delete(threadId);
2367
+ cleanedCount++;
2368
+ }
2369
+ }
2370
+ return cleanedCount;
2371
+ }
2372
+ /**
2373
+ * Extend thread TTL
2374
+ */
2375
+ async extendThreadTTL(threadId, additionalMs) {
2376
+ const buffer = this.getBufferIfValid(threadId);
2377
+ if (buffer) {
2378
+ const extension = additionalMs ?? this.config.ttl;
2379
+ buffer.expiresAt = Date.now() + extension;
2380
+ buffer.updatedAt = Date.now();
2381
+ }
2382
+ }
2383
+ /**
2384
+ * Get new chunks since known content
2385
+ * Used for resuming streams from a known position
2386
+ * Matches the known content and returns chunks after that position
2387
+ * Continues to yield new chunks as they are added until thread completes/aborts
2388
+ */
2389
+ async *getNewChunksSinceContent(threadId, messageId, knownContent) {
2390
+ let buffer = this.getBufferIfValid(threadId);
2391
+ if (!buffer) return;
2392
+ let lastYieldedIndex = -1;
2393
+ let accumulatedContent = "";
2394
+ for (let i = 0; i < buffer.chunks.length; i++) {
2395
+ const chunk = buffer.chunks[i];
2396
+ if (chunk.data?.id === messageId) {
2397
+ accumulatedContent += chunk.data?.content || "";
2398
+ if (accumulatedContent === knownContent) {
2399
+ lastYieldedIndex = i;
2400
+ break;
2401
+ }
2402
+ if (accumulatedContent.length > knownContent.length) {
2403
+ if (accumulatedContent.startsWith(knownContent)) {
2404
+ lastYieldedIndex = i;
2405
+ break;
2406
+ }
2407
+ }
2408
+ }
2409
+ }
2410
+ const pollingInterval = 100;
2411
+ while (true) {
2412
+ buffer = this.getBufferIfValid(threadId);
2413
+ if (!buffer) break;
2414
+ let hasNewChunks = false;
2415
+ for (let i = lastYieldedIndex + 1; i < buffer.chunks.length; i++) {
2416
+ const chunk = buffer.chunks[i];
2417
+ if (chunk.data?.id === messageId) {
2418
+ yield chunk;
2419
+ lastYieldedIndex = i;
2420
+ hasNewChunks = true;
2421
+ }
2422
+ }
2423
+ if (buffer.status === "completed" /* COMPLETED */ || buffer.status === "aborted" /* ABORTED */) {
2424
+ break;
2425
+ }
2426
+ if (!hasNewChunks) {
2427
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
2428
+ }
2429
+ }
2430
+ }
2431
+ /**
2432
+ * Get statistics about the buffer
2433
+ */
2434
+ getStats() {
2435
+ let activeCount = 0;
2436
+ let completedCount = 0;
2437
+ let abortedCount = 0;
2438
+ let totalChunks = 0;
2439
+ const validBuffers = [];
2440
+ for (const [threadId, buffer] of this.buffers.entries()) {
2441
+ if (this.isExpired(buffer)) {
2442
+ this.buffers.delete(threadId);
2443
+ } else {
2444
+ validBuffers.push(buffer);
2445
+ }
2446
+ }
2447
+ for (const buffer of validBuffers) {
2448
+ totalChunks += buffer.chunks.length;
2449
+ switch (buffer.status) {
2450
+ case "active" /* ACTIVE */:
2451
+ activeCount++;
2452
+ break;
2453
+ case "completed" /* COMPLETED */:
2454
+ completedCount++;
2455
+ break;
2456
+ case "aborted" /* ABORTED */:
2457
+ abortedCount++;
2458
+ break;
2459
+ }
2460
+ }
2461
+ return {
2462
+ totalThreads: validBuffers.length,
2463
+ activeThreads: activeCount,
2464
+ completedThreads: completedCount,
2465
+ abortedThreads: abortedCount,
2466
+ totalChunks,
2467
+ config: this.config
2468
+ };
2469
+ }
2470
+ /**
2471
+ * Cleanup method for graceful shutdown
2472
+ */
2473
+ dispose() {
2474
+ this.stopCleanupTimer();
2475
+ this.buffers.clear();
2476
+ }
2477
+ };
2478
+
2479
+ // src/chunk_buffer_lattice/ChunkBufferLatticeManager.ts
2480
+ var ChunkBufferLatticeManager = class _ChunkBufferLatticeManager extends BaseLatticeManager {
2481
+ /**
2482
+ * Private constructor for singleton pattern
2483
+ */
2484
+ constructor() {
2485
+ super();
2486
+ }
2487
+ /**
2488
+ * Get singleton instance
2489
+ */
2490
+ static getInstance() {
2491
+ if (!_ChunkBufferLatticeManager.instance) {
2492
+ _ChunkBufferLatticeManager.instance = new _ChunkBufferLatticeManager();
2493
+ }
2494
+ return _ChunkBufferLatticeManager.instance;
2495
+ }
2496
+ /**
2497
+ * Get Lattice type identifier
2498
+ */
2499
+ getLatticeType() {
2500
+ return "chunk_buffer";
2501
+ }
2502
+ };
2503
+ var getChunkBuffer = (key) => ChunkBufferLatticeManager.getInstance().get(key);
2504
+ var registerChunkBuffer = (key, buffer) => ChunkBufferLatticeManager.getInstance().register(key, buffer);
2505
+ var hasChunkBuffer = (key) => ChunkBufferLatticeManager.getInstance().has(key);
2506
+
2174
2507
  // src/index.ts
2175
2508
  import * as Protocols from "@axiom-lattice/protocols";
2176
2509
  export {
2177
2510
  AgentConfig,
2178
2511
  AgentLatticeManager,
2179
2512
  AgentType,
2513
+ ChunkBuffer,
2514
+ ChunkBufferLatticeManager,
2180
2515
  GraphBuildOptions,
2516
+ InMemoryChunkBuffer,
2181
2517
  MemoryLatticeManager,
2182
2518
  MemoryType,
2183
2519
  ModelLatticeManager,
2184
2520
  Protocols,
2521
+ ThreadStatus,
2185
2522
  ToolLatticeManager,
2186
2523
  agentLatticeManager,
2187
2524
  getAgentClient,
@@ -2190,14 +2527,17 @@ export {
2190
2527
  getAllAgentConfigs,
2191
2528
  getAllToolDefinitions,
2192
2529
  getCheckpointSaver,
2530
+ getChunkBuffer,
2193
2531
  getModelLattice,
2194
2532
  getToolClient,
2195
2533
  getToolDefinition,
2196
2534
  getToolLattice,
2535
+ hasChunkBuffer,
2197
2536
  modelLatticeManager,
2198
2537
  registerAgentLattice,
2199
2538
  registerAgentLattices,
2200
2539
  registerCheckpointSaver,
2540
+ registerChunkBuffer,
2201
2541
  registerModelLattice,
2202
2542
  registerToolLattice,
2203
2543
  toolLatticeManager,