@clawtopia/werewolf-evolution 0.1.5 → 0.1.6

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
  }
@@ -199,7 +203,8 @@ declare class WerewolfEvolutionService {
199
203
  private consumeOrdinaryDirectMessage;
200
204
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedDebrief | CapturedSuggestionCommand, pendingOrdinary?: OrdinaryDirectMessage): void;
201
205
  bindPromptRun(event: PromptBuildEventLike, ctx: AgentRunContextLike, config: unknown): void;
202
- buildPromptContext(ctx: PromptContextLike): {
206
+ finishRun(ctx: Pick<AgentRunContextLike, "runId" | "sessionKey">): void;
207
+ buildPromptContext(ctx: PromptContextLike, hooks?: TransactionHooks): {
203
208
  prependContext: string;
204
209
  } | undefined;
205
210
  beforeToolCall(event: {
@@ -213,10 +218,12 @@ declare class WerewolfEvolutionService {
213
218
  sessionKey?: string;
214
219
  runId?: string;
215
220
  toolCallId?: string;
221
+ agentId?: string;
216
222
  }): {
217
223
  block?: boolean;
218
224
  blockReason?: string;
219
225
  } | undefined;
226
+ private persistIncident;
220
227
  commit(toolCallId: string, ctx: OpenClawPluginToolContext, input: CommitInput, hooks?: TransactionHooks): Record<string, unknown>;
221
228
  decideSuggestion(toolCallId: string, ctx: OpenClawPluginToolContext, input: SuggestionDecisionInput, hooks?: TransactionHooks): Record<string, unknown>;
222
229
  }
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()) {
@@ -2550,7 +2578,13 @@ var WerewolfEvolutionService = class {
2550
2578
  ordinary
2551
2579
  );
2552
2580
  }
2553
- buildPromptContext(ctx) {
2581
+ finishRun(ctx) {
2582
+ if (!ctx.runId) return;
2583
+ this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2584
+ this.observedRuns.delete(ctx.runId);
2585
+ this.ownerDirectRuns.delete(ctx.runId);
2586
+ }
2587
+ buildPromptContext(ctx, hooks = {}) {
2554
2588
  const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
2555
2589
  if (!bound) {
2556
2590
  const ownerRun = ctx.runId ? this.ownerDirectRuns.get(ctx.runId) : void 0;
@@ -2579,6 +2613,7 @@ var WerewolfEvolutionService = class {
2579
2613
  }
2580
2614
  }
2581
2615
  if (bound.agentId !== ctx.agentId || bound.workspaceDir !== ctx.workspaceDir) return void 0;
2616
+ if (bound.promptContext !== void 0) return { prependContext: bound.promptContext };
2582
2617
  if (bound.inbound.kind === "suggestion-command") {
2583
2618
  try {
2584
2619
  const paths = resolveWorkspacePaths(bound.workspaceDir);
@@ -2587,11 +2622,38 @@ var WerewolfEvolutionService = class {
2587
2622
  } catch {
2588
2623
  return void 0;
2589
2624
  }
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
- };
2625
+ 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.`;
2626
+ return { prependContext: bound.promptContext };
2593
2627
  }
2594
2628
  const captured = bound.inbound;
2629
+ const incidents = incidentReasons(captured.envelope);
2630
+ if (incidents.length > 0) {
2631
+ let incidentStatus = "already-handled";
2632
+ let incidentError;
2633
+ if (!bound.consumed) {
2634
+ try {
2635
+ const result = this.persistIncident(captured, bound.workspaceDir, incidents, hooks);
2636
+ incidentStatus = String(result.status);
2637
+ } catch (error) {
2638
+ incidentStatus = "failed";
2639
+ incidentError = error instanceof Error ? error.message : String(error);
2640
+ } finally {
2641
+ if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2642
+ }
2643
+ }
2644
+ bound.promptContext = [
2645
+ "[werewolf-evolution trusted context]",
2646
+ `debriefId=${captured.envelope.debriefId}`,
2647
+ `eligibility=${JSON.stringify(captured.envelope.game)}`,
2648
+ `incidentReasons=${JSON.stringify(incidents)}`,
2649
+ `incidentStatus=${incidentStatus}`,
2650
+ `stateAvailable=${incidentStatus !== "failed"}`,
2651
+ ...incidentError ? [`incidentError=${incidentError}`] : [],
2652
+ 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.",
2653
+ "Do not call werewolf_debrief_commit or any replacement tool. Return NO_REPLY now."
2654
+ ].join("\n");
2655
+ return { prependContext: bound.promptContext };
2656
+ }
2595
2657
  let topics = [];
2596
2658
  let stateAvailable = true;
2597
2659
  let activeProfile;
@@ -2610,6 +2672,19 @@ var WerewolfEvolutionService = class {
2610
2672
  stateAvailable = false;
2611
2673
  stateError = error instanceof Error ? error.message : String(error);
2612
2674
  }
2675
+ if (!stateAvailable) {
2676
+ if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2677
+ bound.promptContext = [
2678
+ "[werewolf-evolution trusted context]",
2679
+ `debriefId=${captured.envelope.debriefId}`,
2680
+ `eligibility=${JSON.stringify(captured.envelope.game)}`,
2681
+ "stateAvailable=false",
2682
+ `stateError=${stateError ?? "UNKNOWN_STATE_ERROR"}`,
2683
+ "Workspace evolution state is unavailable. Fail closed without model-managed writes.",
2684
+ "Do not generate a proposal or call werewolf_debrief_commit. Return NO_REPLY now."
2685
+ ].join("\n");
2686
+ return { prependContext: bound.promptContext };
2687
+ }
2613
2688
  const facts = captured.envelope.facts.map((fact) => ({
2614
2689
  factId: fact.factId,
2615
2690
  historyIndex: fact.availableAt.historyIndex,
@@ -2619,29 +2694,33 @@ var WerewolfEvolutionService = class {
2619
2694
  targetSeat: fact.targetSeat,
2620
2695
  summary: fact.summary
2621
2696
  }));
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
- };
2697
+ bound.promptContext = [
2698
+ "[werewolf-evolution trusted context]",
2699
+ `debriefId=${captured.envelope.debriefId}`,
2700
+ `eligibility=${JSON.stringify(captured.envelope.game)}`,
2701
+ `activeProfile=${activeProfile ?? "UNKNOWN"}`,
2702
+ `facts=${JSON.stringify(facts)}`,
2703
+ `decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
2704
+ `existingTopics=${JSON.stringify(topics)}`,
2705
+ `executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
2706
+ `stateAvailable=${stateAvailable}`,
2707
+ "The proposal profile must equal activeProfile. The Arena envelope is not the profile authority.",
2708
+ "Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
2709
+ "Prefer a matching existing topic over NEW. Call werewolf_debrief_commit exactly once.",
2710
+ "Do not return NO_REPLY before werewolf_debrief_commit returns a result.",
2711
+ "Never use generic write, edit, patch, shell, or memory-write tools for debrief state."
2712
+ ].join("\n");
2713
+ return { prependContext: bound.promptContext };
2640
2714
  }
2641
2715
  beforeToolCall(event, ctx) {
2642
2716
  const runId = event.runId ?? ctx.runId;
2643
2717
  const toolCallId = event.toolCallId ?? ctx.toolCallId;
2644
- const bound = this.contexts.getBound(runId, ctx.sessionKey);
2718
+ let bound;
2719
+ try {
2720
+ bound = this.contexts.getBoundForToolCall(runId, ctx.sessionKey, ctx.agentId);
2721
+ } catch (error) {
2722
+ return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
2723
+ }
2645
2724
  if (!bound) {
2646
2725
  const observed = runId ? this.observedRuns.get(runId) : void 0;
2647
2726
  if (!observed || observed.sessionKey !== ctx.sessionKey || observed.expiresAt < Date.now()) return void 0;
@@ -2660,18 +2739,44 @@ var WerewolfEvolutionService = class {
2660
2739
  if (bound.inbound.kind !== "debrief" || event.params.debriefId !== bound.inbound.envelope.debriefId) {
2661
2740
  throw new Error("DEBRIEF_CAPABILITY_MISMATCH");
2662
2741
  }
2663
- this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
2742
+ this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
2664
2743
  } else if (event.toolName === "werewolf_suggestion_decide") {
2665
2744
  if (bound.inbound.kind !== "suggestion-command" || event.params.suggestionId !== bound.inbound.suggestionId || event.params.decision !== bound.inbound.decision) {
2666
2745
  throw new Error("SUGGESTION_CAPABILITY_MISMATCH");
2667
2746
  }
2668
- this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
2747
+ this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
2669
2748
  }
2670
2749
  } catch (error) {
2671
2750
  return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
2672
2751
  }
2673
2752
  return void 0;
2674
2753
  }
2754
+ persistIncident(captured, workspaceDir, incidents, hooks) {
2755
+ if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2756
+ const paths = resolveWorkspacePaths(workspaceDir);
2757
+ return runWorkspaceTransaction(paths, () => {
2758
+ assertWorkspaceSetupReady(paths, this.version);
2759
+ const current = readWorkspaceState(paths);
2760
+ const prior = current.ledger.entries.find((entry2) => entry2.debriefId === captured.envelope.debriefId);
2761
+ if (prior) {
2762
+ if (prior.bodyHash !== captured.bodyHash) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2763
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate", debriefId: captured.envelope.debriefId } };
2764
+ }
2765
+ if (current.ledger.entries.some((entry2) => entry2.gameId === captured.envelope.game.gameId) || current.ledger.legacyGameIds.includes(captured.envelope.game.gameId)) {
2766
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
2767
+ }
2768
+ const next = clone(current);
2769
+ const result = applyIncident(next, captured.envelope, captured.bodyHash, incidents);
2770
+ return {
2771
+ changes: /* @__PURE__ */ new Map([
2772
+ [paths.incidents, renderIncidents(next.incidents)],
2773
+ [paths.ledger, renderLedger(next.ledger)]
2774
+ ]),
2775
+ result: { status: "committed", debriefId: captured.envelope.debriefId, ...result },
2776
+ verify: () => verifyWorkspaceDocuments(paths)
2777
+ };
2778
+ }, hooks);
2779
+ }
2675
2780
  commit(toolCallId, ctx, input, hooks = {}) {
2676
2781
  const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
2677
2782
  const workspaceDir = requireToolWorkspace(ctx, bound);
@@ -2864,6 +2969,9 @@ function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()
2864
2969
  return service.buildPromptContext(ctx);
2865
2970
  });
2866
2971
  api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
2972
+ api.on("agent_end", (event, ctx) => {
2973
+ service.finishRun({ runId: event.runId ?? ctx.runId, sessionKey: ctx.sessionKey });
2974
+ });
2867
2975
  }
2868
2976
  var entry = definePluginEntry({
2869
2977
  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.6",
4
4
  "description": "Deterministic postgame evolution runtime for the Clawtopia Werewolf Play skill.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",