@listdoing/core 0.1.1 → 0.1.3

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;
@@ -692,6 +704,7 @@ declare const ACPErrorCodes: {
692
704
  readonly CONTEXT_COMPRESS_FAILED: -32121;
693
705
  readonly CONTEXT_SYNC_FAILED: -32122;
694
706
  readonly LLM_CALL_FAILED: -32130;
707
+ readonly LLM_EMPTY_RESPONSE: -32135;
695
708
  readonly LLM_TOKEN_LIMIT: -32131;
696
709
  readonly LLM_RATE_LIMIT: -32132;
697
710
  readonly LLM_PROVIDER_UNAVAILABLE: -32133;
@@ -704,6 +717,7 @@ declare const ACPErrorCodes: {
704
717
  readonly GRAPH_EXECUTION_ABORTED: -32173;
705
718
  readonly SUBAGENT_DEPTH_EXCEEDED: -32174;
706
719
  readonly SUBAGENT_TIMEOUT: -32175;
720
+ readonly SESSION_BUSY: -32176;
707
721
  readonly CODE_EXEC_DISABLED: -32180;
708
722
  readonly CODE_EXEC_TIMEOUT: -32181;
709
723
  readonly CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182;
@@ -1031,6 +1045,7 @@ declare class Ldoing {
1031
1045
  protected persistence: IPersistence;
1032
1046
  private currentSessionId;
1033
1047
  private abortControllers;
1048
+ private runningSessions;
1034
1049
  private approvalResolvers;
1035
1050
  private eventHandlers;
1036
1051
  private tokenCalibrationRatio;
@@ -1052,6 +1067,23 @@ declare class Ldoing {
1052
1067
  chat(message: string | ContentBlock[], options?: ChatOptions): Promise<ChatResult>;
1053
1068
  chatStream(message: string | ContentBlock[], options?: ChatOptions): AsyncGenerator<StreamEvent>;
1054
1069
  abort(sessionId?: string): Promise<void>;
1070
+ /**
1071
+ * 在启动新的 agent loop 前获取会话锁。
1072
+ * 根据并发策略处理正在运行的旧请求:
1073
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
1074
+ * - 'reject': 若已有运行请求,抛错
1075
+ * - 'queue': 预留,当前回退到 'abort'
1076
+ *
1077
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
1078
+ */
1079
+ private acquireSessionLock;
1080
+ /**
1081
+ * 清理被 abort 打断的半截消息:
1082
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
1083
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
1084
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
1085
+ */
1086
+ private cleanupInterruptedMessages;
1055
1087
  approveTool(callId: string, approved: boolean, _reason?: string): void;
1056
1088
  private waitForApproval;
1057
1089
  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;
@@ -692,6 +704,7 @@ declare const ACPErrorCodes: {
692
704
  readonly CONTEXT_COMPRESS_FAILED: -32121;
693
705
  readonly CONTEXT_SYNC_FAILED: -32122;
694
706
  readonly LLM_CALL_FAILED: -32130;
707
+ readonly LLM_EMPTY_RESPONSE: -32135;
695
708
  readonly LLM_TOKEN_LIMIT: -32131;
696
709
  readonly LLM_RATE_LIMIT: -32132;
697
710
  readonly LLM_PROVIDER_UNAVAILABLE: -32133;
@@ -704,6 +717,7 @@ declare const ACPErrorCodes: {
704
717
  readonly GRAPH_EXECUTION_ABORTED: -32173;
705
718
  readonly SUBAGENT_DEPTH_EXCEEDED: -32174;
706
719
  readonly SUBAGENT_TIMEOUT: -32175;
720
+ readonly SESSION_BUSY: -32176;
707
721
  readonly CODE_EXEC_DISABLED: -32180;
708
722
  readonly CODE_EXEC_TIMEOUT: -32181;
709
723
  readonly CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182;
@@ -1031,6 +1045,7 @@ declare class Ldoing {
1031
1045
  protected persistence: IPersistence;
1032
1046
  private currentSessionId;
1033
1047
  private abortControllers;
1048
+ private runningSessions;
1034
1049
  private approvalResolvers;
1035
1050
  private eventHandlers;
1036
1051
  private tokenCalibrationRatio;
@@ -1052,6 +1067,23 @@ declare class Ldoing {
1052
1067
  chat(message: string | ContentBlock[], options?: ChatOptions): Promise<ChatResult>;
1053
1068
  chatStream(message: string | ContentBlock[], options?: ChatOptions): AsyncGenerator<StreamEvent>;
1054
1069
  abort(sessionId?: string): Promise<void>;
1070
+ /**
1071
+ * 在启动新的 agent loop 前获取会话锁。
1072
+ * 根据并发策略处理正在运行的旧请求:
1073
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
1074
+ * - 'reject': 若已有运行请求,抛错
1075
+ * - 'queue': 预留,当前回退到 'abort'
1076
+ *
1077
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
1078
+ */
1079
+ private acquireSessionLock;
1080
+ /**
1081
+ * 清理被 abort 打断的半截消息:
1082
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
1083
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
1084
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
1085
+ */
1086
+ private cleanupInterruptedMessages;
1055
1087
  approveTool(callId: string, approved: boolean, _reason?: string): void;
1056
1088
  private waitForApproval;
1057
1089
  registerSkill(skill: SkillDefinition): void;
package/dist/index.js CHANGED
@@ -123,6 +123,7 @@ var ACPErrorCodes = {
123
123
  CONTEXT_COMPRESS_FAILED: -32121,
124
124
  CONTEXT_SYNC_FAILED: -32122,
125
125
  LLM_CALL_FAILED: -32130,
126
+ LLM_EMPTY_RESPONSE: -32135,
126
127
  LLM_TOKEN_LIMIT: -32131,
127
128
  LLM_RATE_LIMIT: -32132,
128
129
  LLM_PROVIDER_UNAVAILABLE: -32133,
@@ -135,6 +136,7 @@ var ACPErrorCodes = {
135
136
  GRAPH_EXECUTION_ABORTED: -32173,
136
137
  SUBAGENT_DEPTH_EXCEEDED: -32174,
137
138
  SUBAGENT_TIMEOUT: -32175,
139
+ SESSION_BUSY: -32176,
138
140
  CODE_EXEC_DISABLED: -32180,
139
141
  CODE_EXEC_TIMEOUT: -32181,
140
142
  CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182,
@@ -460,6 +462,12 @@ var OpenAIAdapter = class {
460
462
  });
461
463
  }
462
464
  }
465
+ if (!content && !toolCalls.length) {
466
+ throw new ACPError(
467
+ ACPErrorCodes.LLM_EMPTY_RESPONSE,
468
+ "LLM returned empty response with no tool calls"
469
+ );
470
+ }
463
471
  return {
464
472
  content,
465
473
  reasoning,
@@ -575,7 +583,7 @@ var SkillExecutor = class {
575
583
  const controller = new AbortController();
576
584
  const onParentAbort = () => controller.abort();
577
585
  context.signal.addEventListener("abort", onParentAbort);
578
- const timeoutId = setTimeout(() => controller.abort(), timeout);
586
+ const timeoutId = timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null;
579
587
  const execContext = {
580
588
  ...context,
581
589
  signal: controller.signal
@@ -598,7 +606,7 @@ var SkillExecutor = class {
598
606
  { name, error: err.message }
599
607
  );
600
608
  } finally {
601
- clearTimeout(timeoutId);
609
+ if (timeoutId) clearTimeout(timeoutId);
602
610
  context.signal.removeEventListener("abort", onParentAbort);
603
611
  }
604
612
  }
@@ -1176,7 +1184,13 @@ var ContextManager = class {
1176
1184
  if (systemPrompt) {
1177
1185
  result.push({ role: "system", content: systemPrompt });
1178
1186
  }
1179
- const reversed = [...messages].reverse();
1187
+ const sanitized = messages.map((m) => {
1188
+ if (m.role === "assistant" && !m.content && !m.toolCalls?.length) {
1189
+ return { ...m, content: "." };
1190
+ }
1191
+ return m;
1192
+ });
1193
+ const reversed = [...sanitized].reverse();
1180
1194
  const selected = [];
1181
1195
  let usedByMessages = 0;
1182
1196
  for (const msg of reversed) {
@@ -2417,6 +2431,9 @@ var Ldoing = class {
2417
2431
  this.startTime = 0;
2418
2432
  this.currentSessionId = null;
2419
2433
  this.abortControllers = /* @__PURE__ */ new Map();
2434
+ // Session-level concurrency control (方案 B: abort 旧请求 + 等待退出)
2435
+ // runningSessions 跟踪正在执行 agent loop 的会话,donePromise 在 agent loop 结束时 resolve
2436
+ this.runningSessions = /* @__PURE__ */ new Map();
2420
2437
  // Approval pending promises
2421
2438
  this.approvalResolvers = /* @__PURE__ */ new Map();
2422
2439
  // Event listeners
@@ -2535,23 +2552,24 @@ var Ldoing = class {
2535
2552
  // ---- Chat ----
2536
2553
  async chat(message, options) {
2537
2554
  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
2555
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2545
2556
  this.currentSessionId = sessionId;
2546
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2547
- const requireApproval = new Set(options?.requireApproval ?? []);
2557
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2548
2558
  const controller = new AbortController();
2549
2559
  this.abortControllers.set(sessionId, controller);
2550
- const startTime = Date.now();
2551
- let totalInputTokens = 0;
2552
- let totalOutputTokens = 0;
2553
- const executionTrace = [];
2554
2560
  try {
2561
+ if (options?.taskMode === "plan") {
2562
+ return await this.chatWithPlan(message, options);
2563
+ }
2564
+ if (options?.taskMode === "graph") {
2565
+ return await this.chatWithGraph(message, options);
2566
+ }
2567
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2568
+ const requireApproval = new Set(options?.requireApproval ?? []);
2569
+ const startTime = Date.now();
2570
+ let totalInputTokens = 0;
2571
+ let totalOutputTokens = 0;
2572
+ const executionTrace = [];
2555
2573
  const userContent = this.buildUserContent(message, options?.attachments);
2556
2574
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2557
2575
  let turn = 0;
@@ -2593,8 +2611,27 @@ var Ldoing = class {
2593
2611
  turn--;
2594
2612
  continue;
2595
2613
  }
2614
+ if (err.code === ACPErrorCodes.LLM_EMPTY_RESPONSE && !retried) {
2615
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2616
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2617
+ retried = true;
2618
+ turn--;
2619
+ continue;
2620
+ }
2596
2621
  throw new ACPError(ACPErrorCodes.LLM_CALL_FAILED, `LLM call failed: ${err.message}`, { turn });
2597
2622
  }
2623
+ if (!llmResponse.content && !llmResponse.toolCalls?.length) {
2624
+ if (!retried) {
2625
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2626
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2627
+ retried = true;
2628
+ turn--;
2629
+ continue;
2630
+ }
2631
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2632
+ continueLoop = false;
2633
+ break;
2634
+ }
2598
2635
  if (llmResponse.usage) {
2599
2636
  totalInputTokens += llmResponse.usage.input;
2600
2637
  totalOutputTokens += llmResponse.usage.output;
@@ -2636,29 +2673,31 @@ var Ldoing = class {
2636
2673
  return chatResult;
2637
2674
  } finally {
2638
2675
  this.abortControllers.delete(sessionId);
2676
+ if (releaseLock) releaseLock();
2639
2677
  }
2640
2678
  }
2641
2679
  async *chatStream(message, options) {
2642
2680
  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
2681
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2652
2682
  this.currentSessionId = sessionId;
2653
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2654
- const requireApproval = new Set(options?.requireApproval ?? []);
2683
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2655
2684
  const controller = new AbortController();
2656
2685
  this.abortControllers.set(sessionId, controller);
2657
- const startTime = Date.now();
2658
- let totalInputTokens = 0;
2659
- let totalOutputTokens = 0;
2660
- let retried = false;
2661
2686
  try {
2687
+ if (options?.taskMode === "plan") {
2688
+ yield* this.chatStreamWithPlan(message, options);
2689
+ return;
2690
+ }
2691
+ if (options?.taskMode === "graph") {
2692
+ yield* this.chatStreamWithGraph(message, options);
2693
+ return;
2694
+ }
2695
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2696
+ const requireApproval = new Set(options?.requireApproval ?? []);
2697
+ const startTime = Date.now();
2698
+ let totalInputTokens = 0;
2699
+ let totalOutputTokens = 0;
2700
+ let retried = false;
2662
2701
  const userContent = this.buildUserContent(message, options?.attachments);
2663
2702
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2664
2703
  let turn = 0;
@@ -2699,9 +2738,27 @@ var Ldoing = class {
2699
2738
  turn--;
2700
2739
  continue;
2701
2740
  }
2741
+ if (err.code === ACPErrorCodes.LLM_EMPTY_RESPONSE && !retried) {
2742
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2743
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2744
+ retried = true;
2745
+ turn--;
2746
+ continue;
2747
+ }
2702
2748
  yield { type: "error", code: ACPErrorCodes.LLM_CALL_FAILED, message: err.message };
2703
2749
  return;
2704
2750
  }
2751
+ if (!llmResponse.content && !llmResponse.toolCalls?.length) {
2752
+ if (!retried) {
2753
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2754
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2755
+ retried = true;
2756
+ turn--;
2757
+ continue;
2758
+ }
2759
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2760
+ break;
2761
+ }
2705
2762
  if (llmResponse.usage) {
2706
2763
  totalInputTokens += llmResponse.usage.input;
2707
2764
  totalOutputTokens += llmResponse.usage.output;
@@ -2733,6 +2790,7 @@ var Ldoing = class {
2733
2790
  });
2734
2791
  } finally {
2735
2792
  this.abortControllers.delete(sessionId);
2793
+ if (releaseLock) releaseLock();
2736
2794
  }
2737
2795
  }
2738
2796
  async abort(sessionId) {
@@ -2745,6 +2803,60 @@ var Ldoing = class {
2745
2803
  }
2746
2804
  }
2747
2805
  }
2806
+ // ---- Session-level Concurrency Control (方案 B) ----
2807
+ /**
2808
+ * 在启动新的 agent loop 前获取会话锁。
2809
+ * 根据并发策略处理正在运行的旧请求:
2810
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
2811
+ * - 'reject': 若已有运行请求,抛错
2812
+ * - 'queue': 预留,当前回退到 'abort'
2813
+ *
2814
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
2815
+ */
2816
+ async acquireSessionLock(sessionId) {
2817
+ const policy = this.config.concurrentPolicy ?? "abort";
2818
+ const running = this.runningSessions.get(sessionId);
2819
+ if (running) {
2820
+ if (policy === "reject") {
2821
+ throw new ACPError(
2822
+ ACPErrorCodes.SESSION_BUSY,
2823
+ `Session ${sessionId} is already running a chat`
2824
+ );
2825
+ }
2826
+ await this.abort(sessionId);
2827
+ await running.donePromise;
2828
+ this.cleanupInterruptedMessages(sessionId);
2829
+ }
2830
+ let resolveDone;
2831
+ const donePromise = new Promise((resolve) => {
2832
+ resolveDone = resolve;
2833
+ });
2834
+ this.runningSessions.set(sessionId, { donePromise, resolveDone });
2835
+ return () => {
2836
+ this.runningSessions.delete(sessionId);
2837
+ resolveDone();
2838
+ };
2839
+ }
2840
+ /**
2841
+ * 清理被 abort 打断的半截消息:
2842
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
2843
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
2844
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
2845
+ */
2846
+ cleanupInterruptedMessages(sessionId) {
2847
+ try {
2848
+ const session = this.sessionManager.get(sessionId);
2849
+ if (!session?.messages?.length) return;
2850
+ const msgs = session.messages;
2851
+ const last = msgs[msgs.length - 1];
2852
+ if (last.role === "assistant" && last.toolCalls?.length) {
2853
+ msgs.pop();
2854
+ console.log(`[concurrency] cleaned up interrupted assistant(tool_calls) from session ${sessionId}`);
2855
+ }
2856
+ } catch (err) {
2857
+ console.warn("[concurrency] failed to cleanup interrupted messages:", err);
2858
+ }
2859
+ }
2748
2860
  // ---- Tool Approval ----
2749
2861
  approveTool(callId, approved, _reason) {
2750
2862
  const resolver = this.approvalResolvers.get(callId);
@@ -2835,7 +2947,7 @@ ${JSON.stringify(params, null, 2)}`;
2835
2947
  async chatInner(prompt, sessionId, options) {
2836
2948
  const session = this.sessionManager.getOrThrow(sessionId);
2837
2949
  const messageCountBefore = session.messages.length;
2838
- const result = await this.chat(prompt, options);
2950
+ const result = await this.chat(prompt, { ...options, _skipLock: true });
2839
2951
  const sessionAfter = this.sessionManager.getOrThrow(sessionId);
2840
2952
  if (sessionAfter.messages.length > messageCountBefore + 2) {
2841
2953
  const innerMessages = sessionAfter.messages.splice(messageCountBefore);
package/dist/index.mjs CHANGED
@@ -63,6 +63,7 @@ var ACPErrorCodes = {
63
63
  CONTEXT_COMPRESS_FAILED: -32121,
64
64
  CONTEXT_SYNC_FAILED: -32122,
65
65
  LLM_CALL_FAILED: -32130,
66
+ LLM_EMPTY_RESPONSE: -32135,
66
67
  LLM_TOKEN_LIMIT: -32131,
67
68
  LLM_RATE_LIMIT: -32132,
68
69
  LLM_PROVIDER_UNAVAILABLE: -32133,
@@ -75,6 +76,7 @@ var ACPErrorCodes = {
75
76
  GRAPH_EXECUTION_ABORTED: -32173,
76
77
  SUBAGENT_DEPTH_EXCEEDED: -32174,
77
78
  SUBAGENT_TIMEOUT: -32175,
79
+ SESSION_BUSY: -32176,
78
80
  CODE_EXEC_DISABLED: -32180,
79
81
  CODE_EXEC_TIMEOUT: -32181,
80
82
  CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182,
@@ -400,6 +402,12 @@ var OpenAIAdapter = class {
400
402
  });
401
403
  }
402
404
  }
405
+ if (!content && !toolCalls.length) {
406
+ throw new ACPError(
407
+ ACPErrorCodes.LLM_EMPTY_RESPONSE,
408
+ "LLM returned empty response with no tool calls"
409
+ );
410
+ }
403
411
  return {
404
412
  content,
405
413
  reasoning,
@@ -515,7 +523,7 @@ var SkillExecutor = class {
515
523
  const controller = new AbortController();
516
524
  const onParentAbort = () => controller.abort();
517
525
  context.signal.addEventListener("abort", onParentAbort);
518
- const timeoutId = setTimeout(() => controller.abort(), timeout);
526
+ const timeoutId = timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null;
519
527
  const execContext = {
520
528
  ...context,
521
529
  signal: controller.signal
@@ -538,7 +546,7 @@ var SkillExecutor = class {
538
546
  { name, error: err.message }
539
547
  );
540
548
  } finally {
541
- clearTimeout(timeoutId);
549
+ if (timeoutId) clearTimeout(timeoutId);
542
550
  context.signal.removeEventListener("abort", onParentAbort);
543
551
  }
544
552
  }
@@ -1116,7 +1124,13 @@ var ContextManager = class {
1116
1124
  if (systemPrompt) {
1117
1125
  result.push({ role: "system", content: systemPrompt });
1118
1126
  }
1119
- const reversed = [...messages].reverse();
1127
+ const sanitized = messages.map((m) => {
1128
+ if (m.role === "assistant" && !m.content && !m.toolCalls?.length) {
1129
+ return { ...m, content: "." };
1130
+ }
1131
+ return m;
1132
+ });
1133
+ const reversed = [...sanitized].reverse();
1120
1134
  const selected = [];
1121
1135
  let usedByMessages = 0;
1122
1136
  for (const msg of reversed) {
@@ -2357,6 +2371,9 @@ var Ldoing = class {
2357
2371
  this.startTime = 0;
2358
2372
  this.currentSessionId = null;
2359
2373
  this.abortControllers = /* @__PURE__ */ new Map();
2374
+ // Session-level concurrency control (方案 B: abort 旧请求 + 等待退出)
2375
+ // runningSessions 跟踪正在执行 agent loop 的会话,donePromise 在 agent loop 结束时 resolve
2376
+ this.runningSessions = /* @__PURE__ */ new Map();
2360
2377
  // Approval pending promises
2361
2378
  this.approvalResolvers = /* @__PURE__ */ new Map();
2362
2379
  // Event listeners
@@ -2475,23 +2492,24 @@ var Ldoing = class {
2475
2492
  // ---- Chat ----
2476
2493
  async chat(message, options) {
2477
2494
  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
2495
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2485
2496
  this.currentSessionId = sessionId;
2486
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2487
- const requireApproval = new Set(options?.requireApproval ?? []);
2497
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2488
2498
  const controller = new AbortController();
2489
2499
  this.abortControllers.set(sessionId, controller);
2490
- const startTime = Date.now();
2491
- let totalInputTokens = 0;
2492
- let totalOutputTokens = 0;
2493
- const executionTrace = [];
2494
2500
  try {
2501
+ if (options?.taskMode === "plan") {
2502
+ return await this.chatWithPlan(message, options);
2503
+ }
2504
+ if (options?.taskMode === "graph") {
2505
+ return await this.chatWithGraph(message, options);
2506
+ }
2507
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2508
+ const requireApproval = new Set(options?.requireApproval ?? []);
2509
+ const startTime = Date.now();
2510
+ let totalInputTokens = 0;
2511
+ let totalOutputTokens = 0;
2512
+ const executionTrace = [];
2495
2513
  const userContent = this.buildUserContent(message, options?.attachments);
2496
2514
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2497
2515
  let turn = 0;
@@ -2533,8 +2551,27 @@ var Ldoing = class {
2533
2551
  turn--;
2534
2552
  continue;
2535
2553
  }
2554
+ if (err.code === ACPErrorCodes.LLM_EMPTY_RESPONSE && !retried) {
2555
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2556
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2557
+ retried = true;
2558
+ turn--;
2559
+ continue;
2560
+ }
2536
2561
  throw new ACPError(ACPErrorCodes.LLM_CALL_FAILED, `LLM call failed: ${err.message}`, { turn });
2537
2562
  }
2563
+ if (!llmResponse.content && !llmResponse.toolCalls?.length) {
2564
+ if (!retried) {
2565
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2566
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2567
+ retried = true;
2568
+ turn--;
2569
+ continue;
2570
+ }
2571
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2572
+ continueLoop = false;
2573
+ break;
2574
+ }
2538
2575
  if (llmResponse.usage) {
2539
2576
  totalInputTokens += llmResponse.usage.input;
2540
2577
  totalOutputTokens += llmResponse.usage.output;
@@ -2576,29 +2613,31 @@ var Ldoing = class {
2576
2613
  return chatResult;
2577
2614
  } finally {
2578
2615
  this.abortControllers.delete(sessionId);
2616
+ if (releaseLock) releaseLock();
2579
2617
  }
2580
2618
  }
2581
2619
  async *chatStream(message, options) {
2582
2620
  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
2621
  const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
2592
2622
  this.currentSessionId = sessionId;
2593
- const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2594
- const requireApproval = new Set(options?.requireApproval ?? []);
2623
+ const releaseLock = options?._skipLock ? null : await this.acquireSessionLock(sessionId);
2595
2624
  const controller = new AbortController();
2596
2625
  this.abortControllers.set(sessionId, controller);
2597
- const startTime = Date.now();
2598
- let totalInputTokens = 0;
2599
- let totalOutputTokens = 0;
2600
- let retried = false;
2601
2626
  try {
2627
+ if (options?.taskMode === "plan") {
2628
+ yield* this.chatStreamWithPlan(message, options);
2629
+ return;
2630
+ }
2631
+ if (options?.taskMode === "graph") {
2632
+ yield* this.chatStreamWithGraph(message, options);
2633
+ return;
2634
+ }
2635
+ const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
2636
+ const requireApproval = new Set(options?.requireApproval ?? []);
2637
+ const startTime = Date.now();
2638
+ let totalInputTokens = 0;
2639
+ let totalOutputTokens = 0;
2640
+ let retried = false;
2602
2641
  const userContent = this.buildUserContent(message, options?.attachments);
2603
2642
  this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
2604
2643
  let turn = 0;
@@ -2639,9 +2678,27 @@ var Ldoing = class {
2639
2678
  turn--;
2640
2679
  continue;
2641
2680
  }
2681
+ if (err.code === ACPErrorCodes.LLM_EMPTY_RESPONSE && !retried) {
2682
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2683
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2684
+ retried = true;
2685
+ turn--;
2686
+ continue;
2687
+ }
2642
2688
  yield { type: "error", code: ACPErrorCodes.LLM_CALL_FAILED, message: err.message };
2643
2689
  return;
2644
2690
  }
2691
+ if (!llmResponse.content && !llmResponse.toolCalls?.length) {
2692
+ if (!retried) {
2693
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2694
+ this.sessionManager.addMessage(sessionId, { role: "user", content: "System: \u521A\u521A\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u751F\u6210\u6709\u6548\u56DE\u590D\u3002" });
2695
+ retried = true;
2696
+ turn--;
2697
+ continue;
2698
+ }
2699
+ this.sessionManager.addMessage(sessionId, { role: "assistant", content: "." });
2700
+ break;
2701
+ }
2645
2702
  if (llmResponse.usage) {
2646
2703
  totalInputTokens += llmResponse.usage.input;
2647
2704
  totalOutputTokens += llmResponse.usage.output;
@@ -2673,6 +2730,7 @@ var Ldoing = class {
2673
2730
  });
2674
2731
  } finally {
2675
2732
  this.abortControllers.delete(sessionId);
2733
+ if (releaseLock) releaseLock();
2676
2734
  }
2677
2735
  }
2678
2736
  async abort(sessionId) {
@@ -2685,6 +2743,60 @@ var Ldoing = class {
2685
2743
  }
2686
2744
  }
2687
2745
  }
2746
+ // ---- Session-level Concurrency Control (方案 B) ----
2747
+ /**
2748
+ * 在启动新的 agent loop 前获取会话锁。
2749
+ * 根据并发策略处理正在运行的旧请求:
2750
+ * - 'abort' (默认): 中止旧请求,等待其真正退出,清理半截消息,然后返回
2751
+ * - 'reject': 若已有运行请求,抛错
2752
+ * - 'queue': 预留,当前回退到 'abort'
2753
+ *
2754
+ * 返回一个 release 函数,agent loop 结束时必须调用以释放锁。
2755
+ */
2756
+ async acquireSessionLock(sessionId) {
2757
+ const policy = this.config.concurrentPolicy ?? "abort";
2758
+ const running = this.runningSessions.get(sessionId);
2759
+ if (running) {
2760
+ if (policy === "reject") {
2761
+ throw new ACPError(
2762
+ ACPErrorCodes.SESSION_BUSY,
2763
+ `Session ${sessionId} is already running a chat`
2764
+ );
2765
+ }
2766
+ await this.abort(sessionId);
2767
+ await running.donePromise;
2768
+ this.cleanupInterruptedMessages(sessionId);
2769
+ }
2770
+ let resolveDone;
2771
+ const donePromise = new Promise((resolve) => {
2772
+ resolveDone = resolve;
2773
+ });
2774
+ this.runningSessions.set(sessionId, { donePromise, resolveDone });
2775
+ return () => {
2776
+ this.runningSessions.delete(sessionId);
2777
+ resolveDone();
2778
+ };
2779
+ }
2780
+ /**
2781
+ * 清理被 abort 打断的半截消息:
2782
+ * 如果 session.messages 最后一条是 assistant 且带 tool_calls,
2783
+ * 但后面没有对应的 tool 消息,则删除这条 assistant。
2784
+ * 避免下次 LLM 调用因 tool_calls 未配对而报错。
2785
+ */
2786
+ cleanupInterruptedMessages(sessionId) {
2787
+ try {
2788
+ const session = this.sessionManager.get(sessionId);
2789
+ if (!session?.messages?.length) return;
2790
+ const msgs = session.messages;
2791
+ const last = msgs[msgs.length - 1];
2792
+ if (last.role === "assistant" && last.toolCalls?.length) {
2793
+ msgs.pop();
2794
+ console.log(`[concurrency] cleaned up interrupted assistant(tool_calls) from session ${sessionId}`);
2795
+ }
2796
+ } catch (err) {
2797
+ console.warn("[concurrency] failed to cleanup interrupted messages:", err);
2798
+ }
2799
+ }
2688
2800
  // ---- Tool Approval ----
2689
2801
  approveTool(callId, approved, _reason) {
2690
2802
  const resolver = this.approvalResolvers.get(callId);
@@ -2775,7 +2887,7 @@ ${JSON.stringify(params, null, 2)}`;
2775
2887
  async chatInner(prompt, sessionId, options) {
2776
2888
  const session = this.sessionManager.getOrThrow(sessionId);
2777
2889
  const messageCountBefore = session.messages.length;
2778
- const result = await this.chat(prompt, options);
2890
+ const result = await this.chat(prompt, { ...options, _skipLock: true });
2779
2891
  const sessionAfter = this.sessionManager.getOrThrow(sessionId);
2780
2892
  if (sessionAfter.messages.length > messageCountBefore + 2) {
2781
2893
  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.1",
3
+ "version": "0.1.3",
4
4
  "description": "ListDoing Core — cross-platform shared logic",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",