@listdoing/core 0.1.0 → 0.1.2

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.d.mts CHANGED
@@ -352,6 +352,8 @@ interface ChatOptions {
352
352
  };
353
353
  /** Attached files/images to include with the message */
354
354
  attachments?: FileInput[];
355
+ /** Internal: skip session lock acquisition (used by chatInner to avoid re-entrant deadlock) */
356
+ _skipLock?: boolean;
355
357
  }
356
358
  interface ChatResult {
357
359
  reply: string;
@@ -524,6 +526,16 @@ interface LdoingConfig {
524
526
  permissionMode?: PermissionMode;
525
527
  /** Per-permission policy overrides (key = sub-permission, value = policy) */
526
528
  permissionOverrides?: Record<string, PermissionPolicy>;
529
+ /**
530
+ * Concurrent chat policy when a new chat is initiated while another is still running
531
+ * on the same session.
532
+ * - 'abort' (default): abort the running chat, wait for it to exit, then start the new one.
533
+ * Half-finished messages (assistant with tool_calls but no matching tool result) are cleaned up.
534
+ * - 'reject': throw an error immediately if a chat is already running.
535
+ * - 'queue': (reserved) queue the new chat and execute after the running one completes.
536
+ * Not yet implemented; falls back to 'abort'.
537
+ */
538
+ concurrentPolicy?: 'abort' | 'reject' | 'queue';
527
539
  }
528
540
  interface ContextConfig {
529
541
  maxTokens?: number;
@@ -704,6 +716,7 @@ declare const ACPErrorCodes: {
704
716
  readonly GRAPH_EXECUTION_ABORTED: -32173;
705
717
  readonly SUBAGENT_DEPTH_EXCEEDED: -32174;
706
718
  readonly SUBAGENT_TIMEOUT: -32175;
719
+ readonly SESSION_BUSY: -32176;
707
720
  readonly CODE_EXEC_DISABLED: -32180;
708
721
  readonly CODE_EXEC_TIMEOUT: -32181;
709
722
  readonly CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182;
@@ -1031,6 +1044,7 @@ declare class Ldoing {
1031
1044
  protected persistence: IPersistence;
1032
1045
  private currentSessionId;
1033
1046
  private abortControllers;
1047
+ private runningSessions;
1034
1048
  private approvalResolvers;
1035
1049
  private eventHandlers;
1036
1050
  private tokenCalibrationRatio;
@@ -1052,6 +1066,23 @@ declare class Ldoing {
1052
1066
  chat(message: string | ContentBlock[], options?: ChatOptions): Promise<ChatResult>;
1053
1067
  chatStream(message: string | ContentBlock[], options?: ChatOptions): AsyncGenerator<StreamEvent>;
1054
1068
  abort(sessionId?: string): Promise<void>;
1069
+ /**
1070
+ * 在启动新的 agent loop 前获取会话锁。
1071
+ * 根据并发策略处理正在运行的旧请求:
1072
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
1073
+ * - 'reject': 若已有运行请求,抛错
1074
+ * - 'queue': 预留,当前回退到 'abort'
1075
+ *
1076
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
1077
+ */
1078
+ private acquireSessionLock;
1079
+ /**
1080
+ * 清理被 abort 打断的半截消息:
1081
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
1082
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
1083
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
1084
+ */
1085
+ private cleanupInterruptedMessages;
1055
1086
  approveTool(callId: string, approved: boolean, _reason?: string): void;
1056
1087
  private waitForApproval;
1057
1088
  registerSkill(skill: SkillDefinition): void;
package/dist/index.d.ts CHANGED
@@ -352,6 +352,8 @@ interface ChatOptions {
352
352
  };
353
353
  /** Attached files/images to include with the message */
354
354
  attachments?: FileInput[];
355
+ /** Internal: skip session lock acquisition (used by chatInner to avoid re-entrant deadlock) */
356
+ _skipLock?: boolean;
355
357
  }
356
358
  interface ChatResult {
357
359
  reply: string;
@@ -524,6 +526,16 @@ interface LdoingConfig {
524
526
  permissionMode?: PermissionMode;
525
527
  /** Per-permission policy overrides (key = sub-permission, value = policy) */
526
528
  permissionOverrides?: Record<string, PermissionPolicy>;
529
+ /**
530
+ * Concurrent chat policy when a new chat is initiated while another is still running
531
+ * on the same session.
532
+ * - 'abort' (default): abort the running chat, wait for it to exit, then start the new one.
533
+ * Half-finished messages (assistant with tool_calls but no matching tool result) are cleaned up.
534
+ * - 'reject': throw an error immediately if a chat is already running.
535
+ * - 'queue': (reserved) queue the new chat and execute after the running one completes.
536
+ * Not yet implemented; falls back to 'abort'.
537
+ */
538
+ concurrentPolicy?: 'abort' | 'reject' | 'queue';
527
539
  }
528
540
  interface ContextConfig {
529
541
  maxTokens?: number;
@@ -704,6 +716,7 @@ declare const ACPErrorCodes: {
704
716
  readonly GRAPH_EXECUTION_ABORTED: -32173;
705
717
  readonly SUBAGENT_DEPTH_EXCEEDED: -32174;
706
718
  readonly SUBAGENT_TIMEOUT: -32175;
719
+ readonly SESSION_BUSY: -32176;
707
720
  readonly CODE_EXEC_DISABLED: -32180;
708
721
  readonly CODE_EXEC_TIMEOUT: -32181;
709
722
  readonly CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182;
@@ -1031,6 +1044,7 @@ declare class Ldoing {
1031
1044
  protected persistence: IPersistence;
1032
1045
  private currentSessionId;
1033
1046
  private abortControllers;
1047
+ private runningSessions;
1034
1048
  private approvalResolvers;
1035
1049
  private eventHandlers;
1036
1050
  private tokenCalibrationRatio;
@@ -1052,6 +1066,23 @@ declare class Ldoing {
1052
1066
  chat(message: string | ContentBlock[], options?: ChatOptions): Promise<ChatResult>;
1053
1067
  chatStream(message: string | ContentBlock[], options?: ChatOptions): AsyncGenerator<StreamEvent>;
1054
1068
  abort(sessionId?: string): Promise<void>;
1069
+ /**
1070
+ * 在启动新的 agent loop 前获取会话锁。
1071
+ * 根据并发策略处理正在运行的旧请求:
1072
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
1073
+ * - 'reject': 若已有运行请求,抛错
1074
+ * - 'queue': 预留,当前回退到 'abort'
1075
+ *
1076
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
1077
+ */
1078
+ private acquireSessionLock;
1079
+ /**
1080
+ * 清理被 abort 打断的半截消息:
1081
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
1082
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
1083
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
1084
+ */
1085
+ private cleanupInterruptedMessages;
1055
1086
  approveTool(callId: string, approved: boolean, _reason?: string): void;
1056
1087
  private waitForApproval;
1057
1088
  registerSkill(skill: SkillDefinition): void;
package/dist/index.js CHANGED
@@ -135,6 +135,7 @@ var ACPErrorCodes = {
135
135
  GRAPH_EXECUTION_ABORTED: -32173,
136
136
  SUBAGENT_DEPTH_EXCEEDED: -32174,
137
137
  SUBAGENT_TIMEOUT: -32175,
138
+ SESSION_BUSY: -32176,
138
139
  CODE_EXEC_DISABLED: -32180,
139
140
  CODE_EXEC_TIMEOUT: -32181,
140
141
  CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182,
@@ -575,7 +576,7 @@ var SkillExecutor = class {
575
576
  const controller = new AbortController();
576
577
  const onParentAbort = () => controller.abort();
577
578
  context.signal.addEventListener("abort", onParentAbort);
578
- const timeoutId = setTimeout(() => controller.abort(), timeout);
579
+ const timeoutId = timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null;
579
580
  const execContext = {
580
581
  ...context,
581
582
  signal: controller.signal
@@ -598,7 +599,7 @@ var SkillExecutor = class {
598
599
  { name, error: err.message }
599
600
  );
600
601
  } finally {
601
- clearTimeout(timeoutId);
602
+ if (timeoutId) clearTimeout(timeoutId);
602
603
  context.signal.removeEventListener("abort", onParentAbort);
603
604
  }
604
605
  }
@@ -2417,6 +2418,9 @@ var Ldoing = class {
2417
2418
  this.startTime = 0;
2418
2419
  this.currentSessionId = null;
2419
2420
  this.abortControllers = /* @__PURE__ */ new Map();
2421
+ // Session-level concurrency control (方案 B: abort 旧请求 + 等待退出)
2422
+ // runningSessions 跟踪正在执行 agent loop 的会话,donePromise 在 agent loop 结束时 resolve
2423
+ this.runningSessions = /* @__PURE__ */ new Map();
2420
2424
  // Approval pending promises
2421
2425
  this.approvalResolvers = /* @__PURE__ */ new Map();
2422
2426
  // Event listeners
@@ -2535,23 +2539,24 @@ var Ldoing = class {
2535
2539
  // ---- Chat ----
2536
2540
  async chat(message, options) {
2537
2541
  this.ensureInitialized();
2538
- if (options?.taskMode === "plan") {
2539
- return this.chatWithPlan(message, options);
2540
- }
2541
- if (options?.taskMode === "graph") {
2542
- return this.chatWithGraph(message, options);
2543
- }
2544
2542
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2545
2543
  this.currentSessionId = sessionId;
2546
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2547
- const requireApproval = new Set(options?.requireApproval ?? []);
2544
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2548
2545
  const controller = new AbortController();
2549
2546
  this.abortControllers.set(sessionId, controller);
2550
- const startTime = Date.now();
2551
- let totalInputTokens = 0;
2552
- let totalOutputTokens = 0;
2553
- const executionTrace = [];
2554
2547
  try {
2548
+ if (options?.taskMode === "plan") {
2549
+ return await this.chatWithPlan(message, options);
2550
+ }
2551
+ if (options?.taskMode === "graph") {
2552
+ return await this.chatWithGraph(message, options);
2553
+ }
2554
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2555
+ const requireApproval = new Set(options?.requireApproval ?? []);
2556
+ const startTime = Date.now();
2557
+ let totalInputTokens = 0;
2558
+ let totalOutputTokens = 0;
2559
+ const executionTrace = [];
2555
2560
  const userContent = this.buildUserContent(message, options?.attachments);
2556
2561
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2557
2562
  let turn = 0;
@@ -2636,29 +2641,31 @@ var Ldoing = class {
2636
2641
  return chatResult;
2637
2642
  } finally {
2638
2643
  this.abortControllers.delete(sessionId);
2644
+ if (releaseLock) releaseLock();
2639
2645
  }
2640
2646
  }
2641
2647
  async *chatStream(message, options) {
2642
2648
  this.ensureInitialized();
2643
- if (options?.taskMode === "plan") {
2644
- yield* this.chatStreamWithPlan(message, options);
2645
- return;
2646
- }
2647
- if (options?.taskMode === "graph") {
2648
- yield* this.chatStreamWithGraph(message, options);
2649
- return;
2650
- }
2651
2649
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2652
2650
  this.currentSessionId = sessionId;
2653
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2654
- const requireApproval = new Set(options?.requireApproval ?? []);
2651
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2655
2652
  const controller = new AbortController();
2656
2653
  this.abortControllers.set(sessionId, controller);
2657
- const startTime = Date.now();
2658
- let totalInputTokens = 0;
2659
- let totalOutputTokens = 0;
2660
- let retried = false;
2661
2654
  try {
2655
+ if (options?.taskMode === "plan") {
2656
+ yield* this.chatStreamWithPlan(message, options);
2657
+ return;
2658
+ }
2659
+ if (options?.taskMode === "graph") {
2660
+ yield* this.chatStreamWithGraph(message, options);
2661
+ return;
2662
+ }
2663
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2664
+ const requireApproval = new Set(options?.requireApproval ?? []);
2665
+ const startTime = Date.now();
2666
+ let totalInputTokens = 0;
2667
+ let totalOutputTokens = 0;
2668
+ let retried = false;
2662
2669
  const userContent = this.buildUserContent(message, options?.attachments);
2663
2670
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2664
2671
  let turn = 0;
@@ -2733,6 +2740,7 @@ var Ldoing = class {
2733
2740
  });
2734
2741
  } finally {
2735
2742
  this.abortControllers.delete(sessionId);
2743
+ if (releaseLock) releaseLock();
2736
2744
  }
2737
2745
  }
2738
2746
  async abort(sessionId) {
@@ -2745,6 +2753,60 @@ var Ldoing = class {
2745
2753
  }
2746
2754
  }
2747
2755
  }
2756
+ // ---- Session-level Concurrency Control (方案 B) ----
2757
+ /**
2758
+ * 在启动新的 agent loop 前获取会话锁。
2759
+ * 根据并发策略处理正在运行的旧请求:
2760
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
2761
+ * - 'reject': 若已有运行请求,抛错
2762
+ * - 'queue': 预留,当前回退到 'abort'
2763
+ *
2764
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
2765
+ */
2766
+ async acquireSessionLock(sessionId) {
2767
+ const policy = this.config.concurrentPolicy ?? "abort";
2768
+ const running = this.runningSessions.get(sessionId);
2769
+ if (running) {
2770
+ if (policy === "reject") {
2771
+ throw new ACPError(
2772
+ ACPErrorCodes.SESSION_BUSY,
2773
+ `Session ${sessionId} is already running a chat`
2774
+ );
2775
+ }
2776
+ await this.abort(sessionId);
2777
+ await running.donePromise;
2778
+ this.cleanupInterruptedMessages(sessionId);
2779
+ }
2780
+ let resolveDone;
2781
+ const donePromise = new Promise((resolve) => {
2782
+ resolveDone = resolve;
2783
+ });
2784
+ this.runningSessions.set(sessionId, { donePromise, resolveDone });
2785
+ return () => {
2786
+ this.runningSessions.delete(sessionId);
2787
+ resolveDone();
2788
+ };
2789
+ }
2790
+ /**
2791
+ * 清理被 abort 打断的半截消息:
2792
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
2793
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
2794
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
2795
+ */
2796
+ cleanupInterruptedMessages(sessionId) {
2797
+ try {
2798
+ const session = this.sessionManager.get(sessionId);
2799
+ if (!session?.messages?.length) return;
2800
+ const msgs = session.messages;
2801
+ const last = msgs[msgs.length - 1];
2802
+ if (last.role === "assistant" && last.toolCalls?.length) {
2803
+ msgs.pop();
2804
+ console.log(`[concurrency] cleaned up interrupted assistant(tool_calls) from session ${sessionId}`);
2805
+ }
2806
+ } catch (err) {
2807
+ console.warn("[concurrency] failed to cleanup interrupted messages:", err);
2808
+ }
2809
+ }
2748
2810
  // ---- Tool Approval ----
2749
2811
  approveTool(callId, approved, _reason) {
2750
2812
  const resolver = this.approvalResolvers.get(callId);
@@ -2835,7 +2897,7 @@ ${JSON.stringify(params, null, 2)}`;
2835
2897
  async chatInner(prompt, sessionId, options) {
2836
2898
  const session = this.sessionManager.getOrThrow(sessionId);
2837
2899
  const messageCountBefore = session.messages.length;
2838
- const result = await this.chat(prompt, options);
2900
+ const result = await this.chat(prompt, { ...options, _skipLock: true });
2839
2901
  const sessionAfter = this.sessionManager.getOrThrow(sessionId);
2840
2902
  if (sessionAfter.messages.length > messageCountBefore + 2) {
2841
2903
  const innerMessages = sessionAfter.messages.splice(messageCountBefore);
package/dist/index.mjs CHANGED
@@ -75,6 +75,7 @@ var ACPErrorCodes = {
75
75
  GRAPH_EXECUTION_ABORTED: -32173,
76
76
  SUBAGENT_DEPTH_EXCEEDED: -32174,
77
77
  SUBAGENT_TIMEOUT: -32175,
78
+ SESSION_BUSY: -32176,
78
79
  CODE_EXEC_DISABLED: -32180,
79
80
  CODE_EXEC_TIMEOUT: -32181,
80
81
  CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182,
@@ -515,7 +516,7 @@ var SkillExecutor = class {
515
516
  const controller = new AbortController();
516
517
  const onParentAbort = () => controller.abort();
517
518
  context.signal.addEventListener("abort", onParentAbort);
518
- const timeoutId = setTimeout(() => controller.abort(), timeout);
519
+ const timeoutId = timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null;
519
520
  const execContext = {
520
521
  ...context,
521
522
  signal: controller.signal
@@ -538,7 +539,7 @@ var SkillExecutor = class {
538
539
  { name, error: err.message }
539
540
  );
540
541
  } finally {
541
- clearTimeout(timeoutId);
542
+ if (timeoutId) clearTimeout(timeoutId);
542
543
  context.signal.removeEventListener("abort", onParentAbort);
543
544
  }
544
545
  }
@@ -2357,6 +2358,9 @@ var Ldoing = class {
2357
2358
  this.startTime = 0;
2358
2359
  this.currentSessionId = null;
2359
2360
  this.abortControllers = /* @__PURE__ */ new Map();
2361
+ // Session-level concurrency control (方案 B: abort 旧请求 + 等待退出)
2362
+ // runningSessions 跟踪正在执行 agent loop 的会话,donePromise 在 agent loop 结束时 resolve
2363
+ this.runningSessions = /* @__PURE__ */ new Map();
2360
2364
  // Approval pending promises
2361
2365
  this.approvalResolvers = /* @__PURE__ */ new Map();
2362
2366
  // Event listeners
@@ -2475,23 +2479,24 @@ var Ldoing = class {
2475
2479
  // ---- Chat ----
2476
2480
  async chat(message, options) {
2477
2481
  this.ensureInitialized();
2478
- if (options?.taskMode === "plan") {
2479
- return this.chatWithPlan(message, options);
2480
- }
2481
- if (options?.taskMode === "graph") {
2482
- return this.chatWithGraph(message, options);
2483
- }
2484
2482
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2485
2483
  this.currentSessionId = sessionId;
2486
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2487
- const requireApproval = new Set(options?.requireApproval ?? []);
2484
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2488
2485
  const controller = new AbortController();
2489
2486
  this.abortControllers.set(sessionId, controller);
2490
- const startTime = Date.now();
2491
- let totalInputTokens = 0;
2492
- let totalOutputTokens = 0;
2493
- const executionTrace = [];
2494
2487
  try {
2488
+ if (options?.taskMode === "plan") {
2489
+ return await this.chatWithPlan(message, options);
2490
+ }
2491
+ if (options?.taskMode === "graph") {
2492
+ return await this.chatWithGraph(message, options);
2493
+ }
2494
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2495
+ const requireApproval = new Set(options?.requireApproval ?? []);
2496
+ const startTime = Date.now();
2497
+ let totalInputTokens = 0;
2498
+ let totalOutputTokens = 0;
2499
+ const executionTrace = [];
2495
2500
  const userContent = this.buildUserContent(message, options?.attachments);
2496
2501
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2497
2502
  let turn = 0;
@@ -2576,29 +2581,31 @@ var Ldoing = class {
2576
2581
  return chatResult;
2577
2582
  } finally {
2578
2583
  this.abortControllers.delete(sessionId);
2584
+ if (releaseLock) releaseLock();
2579
2585
  }
2580
2586
  }
2581
2587
  async *chatStream(message, options) {
2582
2588
  this.ensureInitialized();
2583
- if (options?.taskMode === "plan") {
2584
- yield* this.chatStreamWithPlan(message, options);
2585
- return;
2586
- }
2587
- if (options?.taskMode === "graph") {
2588
- yield* this.chatStreamWithGraph(message, options);
2589
- return;
2590
- }
2591
2589
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2592
2590
  this.currentSessionId = sessionId;
2593
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2594
- const requireApproval = new Set(options?.requireApproval ?? []);
2591
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2595
2592
  const controller = new AbortController();
2596
2593
  this.abortControllers.set(sessionId, controller);
2597
- const startTime = Date.now();
2598
- let totalInputTokens = 0;
2599
- let totalOutputTokens = 0;
2600
- let retried = false;
2601
2594
  try {
2595
+ if (options?.taskMode === "plan") {
2596
+ yield* this.chatStreamWithPlan(message, options);
2597
+ return;
2598
+ }
2599
+ if (options?.taskMode === "graph") {
2600
+ yield* this.chatStreamWithGraph(message, options);
2601
+ return;
2602
+ }
2603
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2604
+ const requireApproval = new Set(options?.requireApproval ?? []);
2605
+ const startTime = Date.now();
2606
+ let totalInputTokens = 0;
2607
+ let totalOutputTokens = 0;
2608
+ let retried = false;
2602
2609
  const userContent = this.buildUserContent(message, options?.attachments);
2603
2610
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2604
2611
  let turn = 0;
@@ -2673,6 +2680,7 @@ var Ldoing = class {
2673
2680
  });
2674
2681
  } finally {
2675
2682
  this.abortControllers.delete(sessionId);
2683
+ if (releaseLock) releaseLock();
2676
2684
  }
2677
2685
  }
2678
2686
  async abort(sessionId) {
@@ -2685,6 +2693,60 @@ var Ldoing = class {
2685
2693
  }
2686
2694
  }
2687
2695
  }
2696
+ // ---- Session-level Concurrency Control (方案 B) ----
2697
+ /**
2698
+ * 在启动新的 agent loop 前获取会话锁。
2699
+ * 根据并发策略处理正在运行的旧请求:
2700
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
2701
+ * - 'reject': 若已有运行请求,抛错
2702
+ * - 'queue': 预留,当前回退到 'abort'
2703
+ *
2704
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
2705
+ */
2706
+ async acquireSessionLock(sessionId) {
2707
+ const policy = this.config.concurrentPolicy ?? "abort";
2708
+ const running = this.runningSessions.get(sessionId);
2709
+ if (running) {
2710
+ if (policy === "reject") {
2711
+ throw new ACPError(
2712
+ ACPErrorCodes.SESSION_BUSY,
2713
+ `Session ${sessionId} is already running a chat`
2714
+ );
2715
+ }
2716
+ await this.abort(sessionId);
2717
+ await running.donePromise;
2718
+ this.cleanupInterruptedMessages(sessionId);
2719
+ }
2720
+ let resolveDone;
2721
+ const donePromise = new Promise((resolve) => {
2722
+ resolveDone = resolve;
2723
+ });
2724
+ this.runningSessions.set(sessionId, { donePromise, resolveDone });
2725
+ return () => {
2726
+ this.runningSessions.delete(sessionId);
2727
+ resolveDone();
2728
+ };
2729
+ }
2730
+ /**
2731
+ * 清理被 abort 打断的半截消息:
2732
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
2733
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
2734
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
2735
+ */
2736
+ cleanupInterruptedMessages(sessionId) {
2737
+ try {
2738
+ const session = this.sessionManager.get(sessionId);
2739
+ if (!session?.messages?.length) return;
2740
+ const msgs = session.messages;
2741
+ const last = msgs[msgs.length - 1];
2742
+ if (last.role === "assistant" && last.toolCalls?.length) {
2743
+ msgs.pop();
2744
+ console.log(`[concurrency] cleaned up interrupted assistant(tool_calls) from session ${sessionId}`);
2745
+ }
2746
+ } catch (err) {
2747
+ console.warn("[concurrency] failed to cleanup interrupted messages:", err);
2748
+ }
2749
+ }
2688
2750
  // ---- Tool Approval ----
2689
2751
  approveTool(callId, approved, _reason) {
2690
2752
  const resolver = this.approvalResolvers.get(callId);
@@ -2775,7 +2837,7 @@ ${JSON.stringify(params, null, 2)}`;
2775
2837
  async chatInner(prompt, sessionId, options) {
2776
2838
  const session = this.sessionManager.getOrThrow(sessionId);
2777
2839
  const messageCountBefore = session.messages.length;
2778
- const result = await this.chat(prompt, options);
2840
+ const result = await this.chat(prompt, { ...options, _skipLock: true });
2779
2841
  const sessionAfter = this.sessionManager.getOrThrow(sessionId);
2780
2842
  if (sessionAfter.messages.length > messageCountBefore + 2) {
2781
2843
  const innerMessages = sessionAfter.messages.splice(messageCountBefore);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@listdoing/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "ListDoing Core — cross-platform shared logic",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -12,7 +12,9 @@
12
12
  "require": "./dist/index.js"
13
13
  }
14
14
  },
15
- "files": ["dist"],
15
+ "files": [
16
+ "dist"
17
+ ],
16
18
  "scripts": {
17
19
  "build": "tsup src/index.ts --format cjs,esm --dts --clean"
18
20
  },