@clawtopia/werewolf-evolution 0.1.5 → 0.1.7

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.ts CHANGED
@@ -108,6 +108,7 @@ interface BoundRun {
108
108
  senderId?: string;
109
109
  senderIsOwner: boolean;
110
110
  consumed: boolean;
111
+ promptContext?: string;
111
112
  boundAt: number;
112
113
  expiresAt: number;
113
114
  }
@@ -154,8 +155,11 @@ declare class EvolutionContextStore {
154
155
  private storeInbound;
155
156
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, now?: number, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedInbound): BoundRun | undefined;
156
157
  getBound(runId?: string, sessionKey?: string, now?: number): BoundRun | undefined;
158
+ getBoundForToolCall(runId: string | undefined, sessionKey: string | undefined, agentId: string | undefined, now?: number): BoundRun | undefined;
159
+ private resolveBoundForToolCall;
160
+ releaseRun(runId: string | undefined, sessionKey?: string): boolean;
157
161
  consume(runId: string, sessionKey: string, now?: number): BoundRun;
158
- authorizeToolCall(runId: string | undefined, sessionKey: string | undefined, toolCallId: string | undefined, now?: number): BoundRun;
162
+ authorizeToolCall(runId: string | undefined, sessionKey: string | undefined, toolCallId: string | undefined, now?: number, agentId?: string): BoundRun;
159
163
  consumeToolCall(toolCallId: string, sessionKey?: string, now?: number): BoundRun;
160
164
  cleanup(now?: number): void;
161
165
  }
@@ -185,6 +189,10 @@ interface OrdinaryDirectMessage {
185
189
  content: string;
186
190
  capturedAt: number;
187
191
  }
192
+ interface MessageSendingLike {
193
+ to: string;
194
+ content?: string;
195
+ }
188
196
  declare class WerewolfEvolutionService {
189
197
  readonly contexts: EvolutionContextStore;
190
198
  private readonly version;
@@ -192,14 +200,19 @@ declare class WerewolfEvolutionService {
192
200
  private readonly ordinaryDirectMessagesBySession;
193
201
  private readonly ownerDirectRuns;
194
202
  private readonly observedRuns;
203
+ private readonly systemDebriefSessions;
195
204
  constructor(version?: string);
196
205
  private cleanupOrdinaryDirectMessages;
206
+ private cleanupSystemDebriefSessions;
207
+ private matchesSystemDebriefTarget;
197
208
  captureMessage(event: MessageReceivedLike, ctx: MessageContextLike): void;
209
+ isSystemDebriefMessage(event: MessageSendingLike, ctx: Pick<MessageContextLike, "channelId" | "accountId" | "sessionKey" | "conversationId">): boolean;
198
210
  private pendingOrdinaryDirectMessage;
199
211
  private consumeOrdinaryDirectMessage;
200
212
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedDebrief | CapturedSuggestionCommand, pendingOrdinary?: OrdinaryDirectMessage): void;
201
213
  bindPromptRun(event: PromptBuildEventLike, ctx: AgentRunContextLike, config: unknown): void;
202
- buildPromptContext(ctx: PromptContextLike): {
214
+ finishRun(ctx: Pick<AgentRunContextLike, "runId" | "sessionKey">): void;
215
+ buildPromptContext(ctx: PromptContextLike, hooks?: TransactionHooks): {
203
216
  prependContext: string;
204
217
  } | undefined;
205
218
  beforeToolCall(event: {
@@ -213,10 +226,12 @@ declare class WerewolfEvolutionService {
213
226
  sessionKey?: string;
214
227
  runId?: string;
215
228
  toolCallId?: string;
229
+ agentId?: string;
216
230
  }): {
217
231
  block?: boolean;
218
232
  blockReason?: string;
219
233
  } | undefined;
234
+ private persistIncident;
220
235
  commit(toolCallId: string, ctx: OpenClawPluginToolContext, input: CommitInput, hooks?: TransactionHooks): Record<string, unknown>;
221
236
  decideSuggestion(toolCallId: string, ctx: OpenClawPluginToolContext, input: SuggestionDecisionInput, hooks?: TransactionHooks): Record<string, unknown>;
222
237
  }
package/dist/index.js CHANGED
@@ -486,6 +486,34 @@ var EvolutionContextStore = class {
486
486
  const bound = this.boundByRun.get(runId);
487
487
  return bound?.sessionKey === sessionKey && bound.expiresAt >= now ? bound : void 0;
488
488
  }
489
+ getBoundForToolCall(runId, sessionKey, agentId, now = Date.now()) {
490
+ return this.resolveBoundForToolCall(runId, sessionKey, agentId, true, now);
491
+ }
492
+ resolveBoundForToolCall(runId, sessionKey, agentId, includeConsumed, now) {
493
+ this.cleanup(now);
494
+ if (!sessionKey) return void 0;
495
+ if (runId) {
496
+ const bound2 = this.getBound(runId, sessionKey, now);
497
+ if (bound2 && agentId && bound2.agentId !== agentId) throw new Error("BOUND_AGENT_MISMATCH");
498
+ return bound2;
499
+ }
500
+ const matches = [...this.boundByRun.values()].filter((bound2) => bound2.sessionKey === sessionKey && bound2.expiresAt >= now && (includeConsumed || !bound2.consumed));
501
+ if (matches.length === 0) return void 0;
502
+ if (matches.length > 1) throw new Error("AMBIGUOUS_BOUND_CAPABILITY");
503
+ const bound = matches[0];
504
+ if (agentId && bound.agentId !== agentId) throw new Error("BOUND_AGENT_MISMATCH");
505
+ return bound;
506
+ }
507
+ releaseRun(runId, sessionKey) {
508
+ if (!runId) return false;
509
+ const bound = this.boundByRun.get(runId);
510
+ if (!bound || sessionKey && bound.sessionKey !== sessionKey) return false;
511
+ this.boundByRun.delete(runId);
512
+ for (const [toolCallId, authorized] of this.toolCalls) {
513
+ if (authorized.runId === runId) this.toolCalls.delete(toolCallId);
514
+ }
515
+ return true;
516
+ }
489
517
  consume(runId, sessionKey, now = Date.now()) {
490
518
  const bound = this.getBound(runId, sessionKey, now);
491
519
  if (!bound) throw new Error("NO_BOUND_CAPABILITY");
@@ -493,14 +521,14 @@ var EvolutionContextStore = class {
493
521
  bound.consumed = true;
494
522
  return bound;
495
523
  }
496
- authorizeToolCall(runId, sessionKey, toolCallId, now = Date.now()) {
524
+ authorizeToolCall(runId, sessionKey, toolCallId, now = Date.now(), agentId) {
497
525
  this.cleanup(now);
498
- if (!runId || !sessionKey || !toolCallId) throw new Error("TOOL_CALL_CONTEXT_MISSING");
499
- const bound = this.getBound(runId, sessionKey, now);
526
+ if (!sessionKey || !toolCallId) throw new Error("TOOL_CALL_CONTEXT_MISSING");
527
+ const bound = this.resolveBoundForToolCall(runId, sessionKey, agentId, false, now);
500
528
  if (!bound) throw new Error("NO_BOUND_CAPABILITY");
501
529
  if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
502
530
  if (this.toolCalls.has(toolCallId)) throw new Error("TOOL_CALL_ALREADY_AUTHORIZED");
503
- this.toolCalls.set(toolCallId, { runId, sessionKey, expiresAt: bound.expiresAt });
531
+ this.toolCalls.set(toolCallId, { runId: bound.runId, sessionKey, expiresAt: bound.expiresAt });
504
532
  return bound;
505
533
  }
506
534
  consumeToolCall(toolCallId, sessionKey, now = Date.now()) {
@@ -2308,6 +2336,7 @@ function getWerewolfEvolutionVersion() {
2308
2336
  // src/service.ts
2309
2337
  var DIRECT_MESSAGE_TTL_MS = 10 * 60 * 1e3;
2310
2338
  var MAX_DIRECT_MESSAGES = 256;
2339
+ var SYSTEM_DEBRIEF_DELIVERY_GRACE_MS = 30 * 1e3;
2311
2340
  function clone(value) {
2312
2341
  return structuredClone(value);
2313
2342
  }
@@ -2414,6 +2443,7 @@ var WerewolfEvolutionService = class {
2414
2443
  ordinaryDirectMessagesBySession = /* @__PURE__ */ new Map();
2415
2444
  ownerDirectRuns = /* @__PURE__ */ new Map();
2416
2445
  observedRuns = /* @__PURE__ */ new Map();
2446
+ systemDebriefSessions = /* @__PURE__ */ new Map();
2417
2447
  constructor(version = getWerewolfEvolutionVersion()) {
2418
2448
  this.version = version;
2419
2449
  }
@@ -2437,12 +2467,38 @@ var WerewolfEvolutionService = class {
2437
2467
  if (inbounds.length === 0) this.ordinaryDirectMessagesBySession.delete(firstKey);
2438
2468
  }
2439
2469
  }
2470
+ cleanupSystemDebriefSessions(now) {
2471
+ for (const [sessionKey, session] of this.systemDebriefSessions) {
2472
+ if (session.expiresAt < now) this.systemDebriefSessions.delete(sessionKey);
2473
+ }
2474
+ while (this.systemDebriefSessions.size > MAX_DIRECT_MESSAGES) {
2475
+ this.systemDebriefSessions.delete(this.systemDebriefSessions.keys().next().value);
2476
+ }
2477
+ }
2478
+ matchesSystemDebriefTarget(session, event, ctx) {
2479
+ const expected = session.target.trim().toLowerCase();
2480
+ const values = [event.to, ctx.conversationId].filter((value) => typeof value === "string" && value.trim().length > 0).map((value) => value.trim().toLowerCase());
2481
+ if (values.includes(expected)) return true;
2482
+ const targetMatch = /^(?:clawtopia|coolclaw):human:(\d+)$/.exec(expected);
2483
+ if (!targetMatch) return false;
2484
+ return values.some((value) => value === `private:human:${targetMatch[1]}` || value === `human:${targetMatch[1]}`);
2485
+ }
2440
2486
  captureMessage(event, ctx) {
2441
2487
  const now = Date.now();
2442
2488
  this.cleanupOrdinaryDirectMessages(now);
2489
+ this.cleanupSystemDebriefSessions(now);
2443
2490
  const captured = this.contexts.capture(event, ctx);
2444
- const runId = event.runId ?? ctx.runId;
2445
2491
  const sessionKey = event.sessionKey ?? ctx.sessionKey;
2492
+ if (captured?.kind === "debrief" && sessionKey) {
2493
+ this.systemDebriefSessions.set(sessionKey, {
2494
+ channelId: captured.channelId,
2495
+ accountId: captured.accountId,
2496
+ expiresAt: now + DIRECT_MESSAGE_TTL_MS,
2497
+ sessionKey,
2498
+ target: captured.from
2499
+ });
2500
+ }
2501
+ const runId = event.runId ?? ctx.runId;
2446
2502
  if (!captured && sessionKey && isHumanDirectMessage(event, ctx)) {
2447
2503
  const direct = {
2448
2504
  channelId: ctx.channelId,
@@ -2462,6 +2518,12 @@ var WerewolfEvolutionService = class {
2462
2518
  this.cleanupOrdinaryDirectMessages(now);
2463
2519
  }
2464
2520
  }
2521
+ isSystemDebriefMessage(event, ctx) {
2522
+ const now = Date.now();
2523
+ this.cleanupSystemDebriefSessions(now);
2524
+ const sessionKey = ctx.sessionKey;
2525
+ return [...this.systemDebriefSessions.values()].some((session) => (!sessionKey || session.sessionKey === sessionKey) && session.channelId === ctx.channelId && session.accountId === normalizedAccountId(ctx.accountId) && session.expiresAt >= now && this.matchesSystemDebriefTarget(session, event, ctx));
2526
+ }
2465
2527
  pendingOrdinaryDirectMessage(runId, sessionKey, prompt, now) {
2466
2528
  if (!runId || !sessionKey) return void 0;
2467
2529
  const byRun = this.ordinaryDirectMessages.get(runId);
@@ -2550,7 +2612,20 @@ var WerewolfEvolutionService = class {
2550
2612
  ordinary
2551
2613
  );
2552
2614
  }
2553
- buildPromptContext(ctx) {
2615
+ finishRun(ctx) {
2616
+ if (!ctx.runId) return;
2617
+ this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2618
+ this.observedRuns.delete(ctx.runId);
2619
+ this.ownerDirectRuns.delete(ctx.runId);
2620
+ const systemDebrief = ctx.sessionKey ? this.systemDebriefSessions.get(ctx.sessionKey) : void 0;
2621
+ if (systemDebrief) {
2622
+ systemDebrief.expiresAt = Math.min(
2623
+ systemDebrief.expiresAt,
2624
+ Date.now() + SYSTEM_DEBRIEF_DELIVERY_GRACE_MS
2625
+ );
2626
+ }
2627
+ }
2628
+ buildPromptContext(ctx, hooks = {}) {
2554
2629
  const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
2555
2630
  if (!bound) {
2556
2631
  const ownerRun = ctx.runId ? this.ownerDirectRuns.get(ctx.runId) : void 0;
@@ -2579,6 +2654,7 @@ var WerewolfEvolutionService = class {
2579
2654
  }
2580
2655
  }
2581
2656
  if (bound.agentId !== ctx.agentId || bound.workspaceDir !== ctx.workspaceDir) return void 0;
2657
+ if (bound.promptContext !== void 0) return { prependContext: bound.promptContext };
2582
2658
  if (bound.inbound.kind === "suggestion-command") {
2583
2659
  try {
2584
2660
  const paths = resolveWorkspacePaths(bound.workspaceDir);
@@ -2587,11 +2663,38 @@ var WerewolfEvolutionService = class {
2587
2663
  } catch {
2588
2664
  return void 0;
2589
2665
  }
2590
- return {
2591
- prependContext: `[werewolf-evolution] Trusted owner direct-message command captured for ${bound.inbound.suggestionId}. Call werewolf_suggestion_decide exactly once with decision=${bound.inbound.decision}. Do not mention or process this command in a game room or group.`
2592
- };
2666
+ bound.promptContext = `[werewolf-evolution] Trusted owner direct-message command captured for ${bound.inbound.suggestionId}. Call werewolf_suggestion_decide exactly once with decision=${bound.inbound.decision}. Do not mention or process this command in a game room or group.`;
2667
+ return { prependContext: bound.promptContext };
2593
2668
  }
2594
2669
  const captured = bound.inbound;
2670
+ const incidents = incidentReasons(captured.envelope);
2671
+ if (incidents.length > 0) {
2672
+ let incidentStatus = "already-handled";
2673
+ let incidentError;
2674
+ if (!bound.consumed) {
2675
+ try {
2676
+ const result = this.persistIncident(captured, bound.workspaceDir, incidents, hooks);
2677
+ incidentStatus = String(result.status);
2678
+ } catch (error) {
2679
+ incidentStatus = "failed";
2680
+ incidentError = error instanceof Error ? error.message : String(error);
2681
+ } finally {
2682
+ if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2683
+ }
2684
+ }
2685
+ bound.promptContext = [
2686
+ "[werewolf-evolution trusted context]",
2687
+ `debriefId=${captured.envelope.debriefId}`,
2688
+ `eligibility=${JSON.stringify(captured.envelope.game)}`,
2689
+ `incidentReasons=${JSON.stringify(incidents)}`,
2690
+ `incidentStatus=${incidentStatus}`,
2691
+ `stateAvailable=${incidentStatus !== "failed"}`,
2692
+ ...incidentError ? [`incidentError=${incidentError}`] : [],
2693
+ incidentStatus === "failed" ? "The plugin failed closed while persisting the incident; it did not fall back to model-managed writes." : "The plugin deterministically handled this ineligible debrief as incident-only state.",
2694
+ "Do not call werewolf_debrief_commit or any replacement tool. Return NO_REPLY now."
2695
+ ].join("\n");
2696
+ return { prependContext: bound.promptContext };
2697
+ }
2595
2698
  let topics = [];
2596
2699
  let stateAvailable = true;
2597
2700
  let activeProfile;
@@ -2610,6 +2713,19 @@ var WerewolfEvolutionService = class {
2610
2713
  stateAvailable = false;
2611
2714
  stateError = error instanceof Error ? error.message : String(error);
2612
2715
  }
2716
+ if (!stateAvailable) {
2717
+ if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2718
+ bound.promptContext = [
2719
+ "[werewolf-evolution trusted context]",
2720
+ `debriefId=${captured.envelope.debriefId}`,
2721
+ `eligibility=${JSON.stringify(captured.envelope.game)}`,
2722
+ "stateAvailable=false",
2723
+ `stateError=${stateError ?? "UNKNOWN_STATE_ERROR"}`,
2724
+ "Workspace evolution state is unavailable. Fail closed without model-managed writes.",
2725
+ "Do not generate a proposal or call werewolf_debrief_commit. Return NO_REPLY now."
2726
+ ].join("\n");
2727
+ return { prependContext: bound.promptContext };
2728
+ }
2613
2729
  const facts = captured.envelope.facts.map((fact) => ({
2614
2730
  factId: fact.factId,
2615
2731
  historyIndex: fact.availableAt.historyIndex,
@@ -2619,30 +2735,38 @@ var WerewolfEvolutionService = class {
2619
2735
  targetSeat: fact.targetSeat,
2620
2736
  summary: fact.summary
2621
2737
  }));
2622
- return {
2623
- prependContext: [
2624
- "[werewolf-evolution trusted context]",
2625
- `debriefId=${captured.envelope.debriefId}`,
2626
- `eligibility=${JSON.stringify(captured.envelope.game)}`,
2627
- `activeProfile=${activeProfile ?? "UNKNOWN"}`,
2628
- `facts=${JSON.stringify(facts)}`,
2629
- `decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
2630
- `existingTopics=${JSON.stringify(topics)}`,
2631
- `executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
2632
- `stateAvailable=${stateAvailable}`,
2633
- ...stateError ? [`stateError=${stateError}`] : [],
2634
- ...stateAvailable ? ["The proposal profile must equal activeProfile. The Arena envelope is not the profile authority."] : ["Workspace evolution state is unavailable. Do not infer a profile or submit evolutionary evidence."],
2635
- "Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
2636
- "Prefer a matching existing topic over NEW. Call werewolf_debrief_commit exactly once.",
2637
- "Never use generic write, edit, patch, shell, or memory-write tools for debrief state."
2638
- ].join("\n")
2639
- };
2738
+ bound.promptContext = [
2739
+ "[werewolf-evolution trusted context]",
2740
+ `debriefId=${captured.envelope.debriefId}`,
2741
+ `eligibility=${JSON.stringify(captured.envelope.game)}`,
2742
+ `activeProfile=${activeProfile ?? "UNKNOWN"}`,
2743
+ `facts=${JSON.stringify(facts)}`,
2744
+ `decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
2745
+ `existingTopics=${JSON.stringify(topics)}`,
2746
+ `executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
2747
+ `stateAvailable=${stateAvailable}`,
2748
+ "The proposal profile must equal activeProfile. The Arena envelope is not the profile authority.",
2749
+ "Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
2750
+ "Prefer a matching existing topic over NEW. Call werewolf_debrief_commit exactly once.",
2751
+ "After the tool returns, regardless of accepted or rejected status, return exactly NO_REPLY. Never retry the tool call.",
2752
+ "Do not return NO_REPLY before werewolf_debrief_commit returns a result.",
2753
+ "Never use generic write, edit, patch, shell, or memory-write tools for debrief state."
2754
+ ].join("\n");
2755
+ return { prependContext: bound.promptContext };
2640
2756
  }
2641
2757
  beforeToolCall(event, ctx) {
2642
2758
  const runId = event.runId ?? ctx.runId;
2643
2759
  const toolCallId = event.toolCallId ?? ctx.toolCallId;
2644
- const bound = this.contexts.getBound(runId, ctx.sessionKey);
2760
+ let bound;
2761
+ try {
2762
+ bound = this.contexts.getBoundForToolCall(runId, ctx.sessionKey, ctx.agentId);
2763
+ } catch (error) {
2764
+ return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
2765
+ }
2645
2766
  if (!bound) {
2767
+ if (event.toolName === "werewolf_debrief_commit" || event.toolName === "werewolf_suggestion_decide") {
2768
+ return { block: true, blockReason: "NO_BOUND_CAPABILITY" };
2769
+ }
2646
2770
  const observed = runId ? this.observedRuns.get(runId) : void 0;
2647
2771
  if (!observed || observed.sessionKey !== ctx.sessionKey || observed.expiresAt < Date.now()) return void 0;
2648
2772
  const paths = resolveWorkspacePaths(observed.workspaceDir, false);
@@ -2660,18 +2784,44 @@ var WerewolfEvolutionService = class {
2660
2784
  if (bound.inbound.kind !== "debrief" || event.params.debriefId !== bound.inbound.envelope.debriefId) {
2661
2785
  throw new Error("DEBRIEF_CAPABILITY_MISMATCH");
2662
2786
  }
2663
- this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
2787
+ this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
2664
2788
  } else if (event.toolName === "werewolf_suggestion_decide") {
2665
2789
  if (bound.inbound.kind !== "suggestion-command" || event.params.suggestionId !== bound.inbound.suggestionId || event.params.decision !== bound.inbound.decision) {
2666
2790
  throw new Error("SUGGESTION_CAPABILITY_MISMATCH");
2667
2791
  }
2668
- this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
2792
+ this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
2669
2793
  }
2670
2794
  } catch (error) {
2671
2795
  return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
2672
2796
  }
2673
2797
  return void 0;
2674
2798
  }
2799
+ persistIncident(captured, workspaceDir, incidents, hooks) {
2800
+ if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2801
+ const paths = resolveWorkspacePaths(workspaceDir);
2802
+ return runWorkspaceTransaction(paths, () => {
2803
+ assertWorkspaceSetupReady(paths, this.version);
2804
+ const current = readWorkspaceState(paths);
2805
+ const prior = current.ledger.entries.find((entry2) => entry2.debriefId === captured.envelope.debriefId);
2806
+ if (prior) {
2807
+ if (prior.bodyHash !== captured.bodyHash) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2808
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate", debriefId: captured.envelope.debriefId } };
2809
+ }
2810
+ if (current.ledger.entries.some((entry2) => entry2.gameId === captured.envelope.game.gameId) || current.ledger.legacyGameIds.includes(captured.envelope.game.gameId)) {
2811
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
2812
+ }
2813
+ const next = clone(current);
2814
+ const result = applyIncident(next, captured.envelope, captured.bodyHash, incidents);
2815
+ return {
2816
+ changes: /* @__PURE__ */ new Map([
2817
+ [paths.incidents, renderIncidents(next.incidents)],
2818
+ [paths.ledger, renderLedger(next.ledger)]
2819
+ ]),
2820
+ result: { status: "committed", debriefId: captured.envelope.debriefId, ...result },
2821
+ verify: () => verifyWorkspaceDocuments(paths)
2822
+ };
2823
+ }, hooks);
2824
+ }
2675
2825
  commit(toolCallId, ctx, input, hooks = {}) {
2676
2826
  const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
2677
2827
  const workspaceDir = requireToolWorkspace(ctx, bound);
@@ -2775,6 +2925,18 @@ function proposalFailure(error) {
2775
2925
  return { status: "rejected", code: "EVOLUTION_ERROR", message: error instanceof Error ? error.message : String(error) };
2776
2926
  }
2777
2927
 
2928
+ // src/runtime-service.ts
2929
+ var SHARED_SERVICE_KEY = /* @__PURE__ */ Symbol.for("@clawtopia/werewolf-evolution/runtime-service-v1");
2930
+ function getSharedWerewolfEvolutionService() {
2931
+ const runtime = globalThis;
2932
+ const version = getWerewolfEvolutionVersion();
2933
+ const existing = runtime[SHARED_SERVICE_KEY];
2934
+ if (existing?.version === version) return existing.service;
2935
+ const service = new WerewolfEvolutionService(version);
2936
+ runtime[SHARED_SERVICE_KEY] = { version, service };
2937
+ return service;
2938
+ }
2939
+
2778
2940
  // src/tools.ts
2779
2941
  import { Type } from "typebox";
2780
2942
  import {
@@ -2853,7 +3015,7 @@ function createSuggestionDecideTool(service, ctx) {
2853
3015
  }
2854
3016
 
2855
3017
  // index.ts
2856
- function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()) {
3018
+ function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionService()) {
2857
3019
  api.registerTool((ctx) => createDebriefCommitTool(service, ctx), { name: "werewolf_debrief_commit" });
2858
3020
  api.registerTool((ctx) => createSuggestionDecideTool(service, ctx), { name: "werewolf_suggestion_decide" });
2859
3021
  api.on("message_received", (event, ctx) => {
@@ -2864,6 +3026,10 @@ function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()
2864
3026
  return service.buildPromptContext(ctx);
2865
3027
  });
2866
3028
  api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
3029
+ api.on("message_sending", (event, ctx) => service.isSystemDebriefMessage(event, ctx) ? { cancel: true } : void 0);
3030
+ api.on("agent_end", (event, ctx) => {
3031
+ service.finishRun({ runId: event.runId ?? ctx.runId, sessionKey: ctx.sessionKey });
3032
+ });
2867
3033
  }
2868
3034
  var entry = definePluginEntry({
2869
3035
  id: "werewolf-evolution",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawtopia/werewolf-evolution",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Deterministic postgame evolution runtime for the Clawtopia Werewolf Play skill.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",