@lmzhen/dsh-evolution-review 0.39.1 → 0.40.0

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/README.md CHANGED
@@ -15,9 +15,9 @@ Subagent-origin, background-visibility, and review-child sessions are excluded.
15
15
  | Mode | Behavior | Recorded history |
16
16
  |---|---|---|
17
17
  | `aux` (default) | Runs a plugin-owned manual loop over the parent request prefix: parent Agent, no child Session, no parent append, allowlisted parent-visible tools executed without a log; a disallowed call returns a tool error instead of aborting the review. | Emits `review-scheduled` and `review-completed`; the completion event is folded into the bounded activity review list (preview + actions + usage). |
18
- | `inject` (debug) | Sends the review prompt into the parent session as an ordinary turn. `reviewWakeInject=true` uses a waking follow-up when available. | Emits `review-scheduled`; does **not** emit `plan-applied`, so plan-based activity/replay stays empty. |
18
+ | `inject` (debug) | Sends the kind-specific foreground review prompt into the parent session as an ordinary turn. `reviewWakeInject=true` uses a waking follow-up when available. | Emits `review-scheduled`; does **not** emit `plan-applied`, so plan-based activity/replay stays empty. |
19
19
 
20
- `reviewNotice=true` allows result notices for the inject path. Aux results are audit-only: `finalText` lands in the bounded activity review record and never becomes a parent message or a new parent turn.
20
+ `reviewNotice=true` allows result notices for the inject path. Aux results are audit-only: `finalText` lands in the bounded activity review record and never becomes a parent message or a new parent turn. The aux path uses the combined prompt for skill/combined reviews, so it includes the memory pass instead of silently dropping memory. It does not declare a background role: the model sees the actual tool set, and the prompt only states that unavailable tools or paths must be replaced with verified local equivalents or reported.
21
21
 
22
22
  ## Events and limits
23
23
 
package/lib/index.js CHANGED
@@ -1,8 +1,7 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { randomUUID } from "node:crypto";
3
- import { BlockAssembler, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
4
- import { SessionId } from "@deepseek-ai/dsh-session";
5
- import { COMPLETION_SKILL_REVIEW_PROMPT, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, MAX_TIMER_DELAY_MS, MEMORY_REVIEW_PROMPT, PROMPT_BUNDLE, advanceReview, assertSkillsRootAliasRetired, clampOnce, classifySessionEvent, clearReviewChannel, filterUnreadSkillOps, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, registerOwnerSettings, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle, withReviewContext } from "@lmzhen/dsh-evolution-core";
3
+ import { BlockAssembler, SessionId, createToolResultMessage, createUserMessage } from "@lmzhen/dsh-evolution-core/platform";
4
+ import { DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, MAX_TIMER_DELAY_MS, PROMPT_BUNDLE, advanceReview, assertSkillsRootAliasRetired, clampOnce, classifySessionEvent, clearReviewChannel, filterUnreadSkillOps, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, registerOwnerSettings, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle, withReviewContext } from "@lmzhen/dsh-evolution-core";
6
5
  //#region lib/types/review-executor.js
7
6
  /**
8
7
  * Plugin-side review execution over the parent request prefix.
@@ -13,6 +12,30 @@ import { COMPLETION_SKILL_REVIEW_PROMPT, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT
13
12
  *
14
13
  * @module @lmzhen/dsh-evolution-review/review-executor
15
14
  */
15
+ var ReviewModelError = class extends Error {
16
+ code;
17
+ constructor(message, code) {
18
+ super(message);
19
+ this.code = code;
20
+ this.name = "ReviewModelError";
21
+ }
22
+ };
23
+ async function* streamReviewModel(llm, options, signal) {
24
+ try {
25
+ yield* llm.stream(options);
26
+ } catch (error) {
27
+ const code = signal.aborted ? "cancelled" : error.name === "TimeoutError" ? "timeout" : "transport";
28
+ throw new ReviewModelError(error instanceof Error ? error.message : String(error), code);
29
+ }
30
+ }
31
+ var ReviewPartialFailure = class extends Error {
32
+ actions;
33
+ constructor(message, actions = []) {
34
+ super(message);
35
+ this.actions = actions;
36
+ this.name = "ReviewPartialFailure";
37
+ }
38
+ };
16
39
  function toolTarget(name, raw) {
17
40
  if (raw === "") return name;
18
41
  try {
@@ -62,7 +85,7 @@ async function runReview(input) {
62
85
  for (let round = 0; round < maxRounds; round += 1) {
63
86
  signal.throwIfAborted();
64
87
  const assembler = new BlockAssembler();
65
- const stream = llm.stream({
88
+ const stream = streamReviewModel(llm, {
66
89
  provider: header.config.provider,
67
90
  model: header.config.model,
68
91
  ...header.config.reasoningEffort === void 0 ? {} : { reasoningEffort: header.config.reasoningEffort },
@@ -72,7 +95,7 @@ async function runReview(input) {
72
95
  ...header.tools === void 0 ? {} : { tools: [...header.tools] },
73
96
  ...toolHistory === void 0 ? {} : { toolHistory },
74
97
  signal
75
- });
98
+ }, signal);
76
99
  requests += 1;
77
100
  for await (const chunk of stream) {
78
101
  assembler.push(chunk);
@@ -124,7 +147,7 @@ async function runReview(input) {
124
147
  type: actionType(call.name),
125
148
  action: call.name,
126
149
  target: toolTarget(call.name, call.arguments),
127
- status: item.result.isError ? "error" : "ok"
150
+ status: item.result.isError ? "error" : item.result.content.some((block) => block.type === "text" && /staged id:|已暂存|pending_id/.test(block.text)) ? "staged" : "ok"
128
151
  });
129
152
  messages.push(createToolResultMessage({
130
153
  callId: item.callId,
@@ -133,12 +156,12 @@ async function runReview(input) {
133
156
  }));
134
157
  }
135
158
  toolCalls += calls.length;
136
- if (parent.session.seq !== beforeSeq) throw new Error("review tool mutated the parent Session");
159
+ if (parent.session.seq !== beforeSeq) throw new ReviewPartialFailure("review tool mutated the parent Session", actions);
137
160
  }
138
161
  } finally {
139
162
  clearReview();
140
163
  }
141
- if (parent.session.seq !== beforeSeq) throw new Error("review mutated the parent Session");
164
+ if (parent.session.seq !== beforeSeq) throw new ReviewPartialFailure("review mutated the parent Session", actions);
142
165
  return {
143
166
  finalText,
144
167
  actions,
@@ -592,7 +615,7 @@ function apply(ctx, rawConfig = {}) {
592
615
  if (pendingKind !== void 0) {
593
616
  pendingCadenceReviews.delete(session.id);
594
617
  if (params().reviewMode === "aux") {
595
- if (!tryAuxReview(session, agent, pendingKind, signal, "cadence")) pendingCadenceReviews.set(session.id, pendingKind);
618
+ if (!await tryAuxReview(session, agent, pendingKind, signal, "cadence")) pendingCadenceReviews.set(session.id, pendingKind);
596
619
  return;
597
620
  }
598
621
  if (params().reviewMode === "inject") {
@@ -627,10 +650,10 @@ function apply(ctx, rawConfig = {}) {
627
650
  if (!shouldCompletionReview(event.data.reason, cumulative, params().skillReviewCompletionMinToolCalls)) return;
628
651
  completionInjected.add(session.id);
629
652
  if (params().reviewMode === "aux") {
630
- if (!tryAuxReview(session, agent, "skill", signal, "completion")) completionInjected.delete(session.id);
653
+ if (!await tryAuxReview(session, agent, "skill", signal, "completion")) completionInjected.delete(session.id);
631
654
  return;
632
655
  }
633
- if (!deliverMessage(agent, COMPLETION_SKILL_REVIEW_PROMPT, "completion review", true)) {
656
+ if (!deliverMessage(agent, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, "completion review", true)) {
634
657
  completionInjected.delete(session.id);
635
658
  return;
636
659
  }
@@ -753,13 +776,13 @@ function apply(ctx, rawConfig = {}) {
753
776
  return false;
754
777
  }
755
778
  };
756
- const BRANCH_MEMORY_PROMPT = MEMORY_REVIEW_PROMPT.replace("If nothing is worth saving, just say \"Nothing to save.\" and stop.", "Do not create skills here; return a short summary of what was saved.\nIf nothing is worth saving, say \"Nothing to save.\" and stop.");
757
779
  /** Tools the plugin-side review may call; every name must already be in the parent request head. */
758
780
  /**
759
781
  * Run one plugin-side review over the parent prefix. No child Agent/Session is
760
782
  * created; the parent Agent is used only for tool scope/approval, with no log.
761
783
  */
762
- function tryAuxReview(session, agent, kind, signal, reason) {
784
+ let inFlightControllers = /* @__PURE__ */ new Set();
785
+ async function tryAuxReview(session, agent, kind, signal, reason) {
763
786
  const running = auxRunning.get(session.id);
764
787
  if (running !== void 0) {
765
788
  running.rerun = kind;
@@ -776,16 +799,39 @@ function apply(ctx, rawConfig = {}) {
776
799
  ctx.logger.warn("dsh-evolution-review: aux review skipped — llm/tools service is not mounted");
777
800
  return false;
778
801
  }
802
+ const authority = ctx.get("evolutionMutationAuthority");
803
+ let leaseToken;
804
+ if (authority?.lease !== void 0) {
805
+ const lease = await authority.lease.acquire("background_review", "review:" + session.id, Math.max(config.reviewTimeoutMs + 3e4, 6e4)).catch(() => void 0);
806
+ if (lease === void 0) {
807
+ ctx.logger.warn("dsh-evolution-review: aux review skipped — lease acquire failed");
808
+ return false;
809
+ }
810
+ if (!lease.ok) {
811
+ ctx.logger.warn("dsh-evolution-review: aux review already leased (" + lease.reason + ")");
812
+ return false;
813
+ }
814
+ leaseToken = lease.token;
815
+ }
779
816
  const state = {};
780
817
  auxRunning.set(session.id, state);
781
818
  const reviewId = "aux-" + randomUUID();
782
819
  const startedAt = Date.now();
783
820
  const controller = new AbortController();
821
+ inFlightControllers.add(controller);
784
822
  let timedOut = false;
785
823
  const timer = setTimeout(() => {
786
824
  timedOut = true;
787
825
  controller.abort();
788
826
  }, config.reviewTimeoutMs);
827
+ let leaseRenewTimer;
828
+ if (leaseToken !== void 0 && authority?.lease !== void 0) leaseRenewTimer = setInterval(() => {
829
+ authority.lease.renew(leaseToken).then((record) => {
830
+ if (record === null) controller.abort();
831
+ }).catch(() => {
832
+ controller.abort();
833
+ });
834
+ }, Math.max(5e3, Math.min(3e4, Math.floor(config.reviewTimeoutMs / 2))));
789
835
  const AUX_TOOL_ALLOW = new Set([
790
836
  "skill_manage",
791
837
  "memory",
@@ -811,7 +857,7 @@ function apply(ctx, rawConfig = {}) {
811
857
  let usage;
812
858
  let error;
813
859
  try {
814
- const prompt = kind === "memory" ? BRANCH_MEMORY_PROMPT : COMPLETION_SKILL_REVIEW_PROMPT;
860
+ const prompt = reviewPrompt(kind, "aux");
815
861
  const result = await withReviewContext({
816
862
  reviewId,
817
863
  runId: reviewId
@@ -837,13 +883,16 @@ function apply(ctx, rawConfig = {}) {
837
883
  cacheReadTokens: result.usage.cacheReadTokens ?? 0,
838
884
  cacheWriteTokens: 0
839
885
  };
840
- status = "completed";
886
+ status = toolAllow.size === 0 ? "failed" : "completed";
887
+ if (toolAllow.size === 0) error = "aux review has no allowed tools for this parent (PTC-only header); refusing to report completed";
841
888
  } catch (caught) {
842
889
  error = caught instanceof Error ? caught.message : String(caught);
890
+ if (caught instanceof ReviewPartialFailure && caught.actions.length > 0) actions = caught.actions;
843
891
  status = timedOut ? "timeout" : controller.signal.aborted ? "aborted" : "failed";
844
892
  ctx.logger.warn("dsh-evolution-review: aux review failed: " + error);
845
893
  } finally {
846
894
  clearTimeout(timer);
895
+ if (leaseRenewTimer !== void 0) clearInterval(leaseRenewTimer);
847
896
  const finishedAt = Date.now();
848
897
  try {
849
898
  ctx.emit("evolution/review-completed", {
@@ -879,19 +928,24 @@ function apply(ctx, rawConfig = {}) {
879
928
  planId: reviewId,
880
929
  memoryApplied: actions.filter((action) => action.type === "memory" && ok(action)).length,
881
930
  skillApplied: actions.filter((action) => action.type === "skill" && ok(action)).length,
882
- rejectedOps: actions.filter((action) => !ok(action)).length,
931
+ rejectedOps: actions.filter((action) => action.status === "error").length,
932
+ stagedOps: actions.filter((action) => action.status === "staged").length,
883
933
  ...error === void 0 ? {} : { executionError: error }
884
934
  });
885
935
  } catch (emitError) {
886
936
  ctx.logger.warn("dsh-evolution-review: aux plan-applied emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
887
937
  }
888
938
  auxRunning.delete(session.id);
939
+ inFlightControllers.delete(controller);
940
+ if (leaseToken !== void 0 && authority?.lease !== void 0) await authority.lease.release(leaseToken).catch(() => {});
889
941
  if (state.rerun !== void 0) tryAuxReview(session, agent, state.rerun, signal, reason);
890
942
  }
891
943
  })();
892
944
  return true;
893
945
  }
894
946
  ctx.effect(() => () => {
947
+ for (const controller of inFlightControllers) controller.abort();
948
+ inFlightControllers = /* @__PURE__ */ new Set();
895
949
  sessionState.dispose();
896
950
  }, "dsh-evolution-review.cleanup");
897
951
  }
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import type { Context, Volatile } from '@deepseek-ai/cordis';
6
6
  import z from '@deepseek-ai/schemastery';
7
- import type { ContextFormed } from '@deepseek-ai/dsh-llm';
7
+ import type { ContextFormed } from '@lmzhen/dsh-evolution-core/platform';
8
8
  declare module '@deepseek-ai/dsh-llm' {
9
9
  interface MessageSourceMap {
10
10
  'evolution-review': {
@@ -1,5 +1,5 @@
1
- import type { ContentBlock, ContextFormed, GenerateOptions, Message, StreamChunk, ToolCallBlock, ToolCallId, ToolHistory } from '@deepseek-ai/dsh-llm';
2
- import type { EpochHeader, SessionId } from '@deepseek-ai/dsh-session';
1
+ import type { ContentBlock, ContextFormed, GenerateOptions, Message, StreamChunk, ToolCallBlock, ToolCallId, ToolHistory } from '@lmzhen/dsh-evolution-core/platform';
2
+ import type { EpochHeader, SessionId } from '@lmzhen/dsh-evolution-core/platform';
3
3
  declare module '@deepseek-ai/dsh-llm' {
4
4
  interface MessageSourceMap {
5
5
  'evolution-review': {
@@ -41,11 +41,19 @@ export interface ReviewToolPort {
41
41
  export interface ReviewLlmPort {
42
42
  stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
43
43
  }
44
+ export declare class ReviewModelError extends Error {
45
+ readonly code: 'timeout' | 'cancelled' | 'transport';
46
+ constructor(message: string, code: 'timeout' | 'cancelled' | 'transport');
47
+ }
48
+ export declare class ReviewPartialFailure extends Error {
49
+ readonly actions: readonly ReviewAction[];
50
+ constructor(message: string, actions?: readonly ReviewAction[]);
51
+ }
44
52
  export interface ReviewAction {
45
53
  readonly type: 'tool' | 'skill' | 'memory';
46
54
  readonly action: string;
47
55
  readonly target: string;
48
- readonly status: 'ok' | 'error';
56
+ readonly status: 'ok' | 'staged' | 'error';
49
57
  }
50
58
  export interface ReviewUsage {
51
59
  readonly inputTokens?: number;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-evolution-review",
3
3
  "description": "Background review orchestration (community build)",
4
- "version": "0.39.1",
4
+ "version": "0.40.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -27,22 +27,22 @@
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
29
  "@deepseek-ai/schemastery": "^3.18.5",
30
- "@lmzhen/dsh-evolution-core": "^0.39.1"
30
+ "@lmzhen/dsh-evolution-core": "^0.40.0"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@deepseek-ai/cordis": "^4.0.5",
34
34
  "@deepseek-ai/dsh-agent": "^0.2.2-rc.0",
35
35
  "@deepseek-ai/dsh-llm": "^0.2.2-rc.0",
36
36
  "@deepseek-ai/dsh-session": "^0.2.2-rc.0",
37
- "@lmzhen/dsh-evolution-policy": "^0.39.1",
38
- "@lmzhen/dsh-evolution-state": "^0.39.1"
37
+ "@lmzhen/dsh-evolution-policy": "^0.40.0",
38
+ "@lmzhen/dsh-evolution-state": "^0.40.0"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@deepseek-ai/dsh-agent": "^0.2.2-rc.0",
42
42
  "@deepseek-ai/dsh-llm": "^0.2.2-rc.0",
43
43
  "@deepseek-ai/dsh-session": "^0.2.2-rc.0",
44
- "@lmzhen/dsh-evolution-core": "^0.39.1",
45
- "@lmzhen/dsh-evolution-state": "^0.39.1"
44
+ "@lmzhen/dsh-evolution-core": "^0.40.0",
45
+ "@lmzhen/dsh-evolution-state": "^0.40.0"
46
46
  },
47
47
  "engines": {
48
48
  "dsh": ">=0.2.2-rc.0 <0.2.3-0"