@clawtopia/werewolf-evolution 0.1.6 → 0.1.8

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
@@ -55,7 +55,7 @@ interface DebriefProposal {
55
55
  schemaVersion: 1;
56
56
  action: ProposalAction;
57
57
  source: ProposalSource;
58
- topicId?: string | null;
58
+ topicId?: string;
59
59
  profile?: string;
60
60
  decisionWindowId?: string;
61
61
  decisionType?: string;
@@ -189,6 +189,10 @@ interface OrdinaryDirectMessage {
189
189
  content: string;
190
190
  capturedAt: number;
191
191
  }
192
+ interface MessageSendingLike {
193
+ to: string;
194
+ content?: string;
195
+ }
192
196
  declare class WerewolfEvolutionService {
193
197
  readonly contexts: EvolutionContextStore;
194
198
  private readonly version;
@@ -196,9 +200,13 @@ declare class WerewolfEvolutionService {
196
200
  private readonly ordinaryDirectMessagesBySession;
197
201
  private readonly ownerDirectRuns;
198
202
  private readonly observedRuns;
203
+ private readonly systemDebriefSessions;
199
204
  constructor(version?: string);
200
205
  private cleanupOrdinaryDirectMessages;
206
+ private cleanupSystemDebriefSessions;
207
+ private matchesSystemDebriefTarget;
201
208
  captureMessage(event: MessageReceivedLike, ctx: MessageContextLike): void;
209
+ isSystemDebriefMessage(event: MessageSendingLike, ctx: Pick<MessageContextLike, "channelId" | "accountId" | "sessionKey" | "conversationId">): boolean;
202
210
  private pendingOrdinaryDirectMessage;
203
211
  private consumeOrdinaryDirectMessage;
204
212
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedDebrief | CapturedSuggestionCommand, pendingOrdinary?: OrdinaryDirectMessage): void;
package/dist/index.js CHANGED
@@ -585,7 +585,7 @@ var proposalSchema = z2.object({
585
585
  schemaVersion: z2.literal(1),
586
586
  action: z2.enum(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW"]),
587
587
  source: z2.enum(["SELF", "OBSERVED", "EXEMPLAR"]),
588
- topicId: z2.string().regex(SAFE_TOPIC).nullable().optional(),
588
+ topicId: z2.string().regex(SAFE_TOPIC).optional(),
589
589
  profile: z2.string().regex(SAFE_PROFILE2).optional(),
590
590
  decisionWindowId: z2.string().min(1).max(200).optional(),
591
591
  decisionType: z2.string().regex(SAFE_TOKEN).optional(),
@@ -2336,6 +2336,7 @@ function getWerewolfEvolutionVersion() {
2336
2336
  // src/service.ts
2337
2337
  var DIRECT_MESSAGE_TTL_MS = 10 * 60 * 1e3;
2338
2338
  var MAX_DIRECT_MESSAGES = 256;
2339
+ var SYSTEM_DEBRIEF_DELIVERY_GRACE_MS = 30 * 1e3;
2339
2340
  function clone(value) {
2340
2341
  return structuredClone(value);
2341
2342
  }
@@ -2442,6 +2443,7 @@ var WerewolfEvolutionService = class {
2442
2443
  ordinaryDirectMessagesBySession = /* @__PURE__ */ new Map();
2443
2444
  ownerDirectRuns = /* @__PURE__ */ new Map();
2444
2445
  observedRuns = /* @__PURE__ */ new Map();
2446
+ systemDebriefSessions = /* @__PURE__ */ new Map();
2445
2447
  constructor(version = getWerewolfEvolutionVersion()) {
2446
2448
  this.version = version;
2447
2449
  }
@@ -2465,12 +2467,38 @@ var WerewolfEvolutionService = class {
2465
2467
  if (inbounds.length === 0) this.ordinaryDirectMessagesBySession.delete(firstKey);
2466
2468
  }
2467
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
+ }
2468
2486
  captureMessage(event, ctx) {
2469
2487
  const now = Date.now();
2470
2488
  this.cleanupOrdinaryDirectMessages(now);
2489
+ this.cleanupSystemDebriefSessions(now);
2471
2490
  const captured = this.contexts.capture(event, ctx);
2472
- const runId = event.runId ?? ctx.runId;
2473
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;
2474
2502
  if (!captured && sessionKey && isHumanDirectMessage(event, ctx)) {
2475
2503
  const direct = {
2476
2504
  channelId: ctx.channelId,
@@ -2490,6 +2518,12 @@ var WerewolfEvolutionService = class {
2490
2518
  this.cleanupOrdinaryDirectMessages(now);
2491
2519
  }
2492
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
+ }
2493
2527
  pendingOrdinaryDirectMessage(runId, sessionKey, prompt, now) {
2494
2528
  if (!runId || !sessionKey) return void 0;
2495
2529
  const byRun = this.ordinaryDirectMessages.get(runId);
@@ -2583,6 +2617,13 @@ var WerewolfEvolutionService = class {
2583
2617
  this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2584
2618
  this.observedRuns.delete(ctx.runId);
2585
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
+ }
2586
2627
  }
2587
2628
  buildPromptContext(ctx, hooks = {}) {
2588
2629
  const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
@@ -2706,7 +2747,19 @@ var WerewolfEvolutionService = class {
2706
2747
  `stateAvailable=${stateAvailable}`,
2707
2748
  "The proposal profile must equal activeProfile. The Arena envelope is not the profile authority.",
2708
2749
  "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.",
2750
+ "Proposal action contract:",
2751
+ "- When existingTopics=[] choose only NEW or SKIP. SUPPORT/COUNTER/REFINE are invalid without an existing topic.",
2752
+ "- NEW must omit topicId entirely. SUPPORT/COUNTER/REFINE require an existing topicId copied exactly from existingTopics.",
2753
+ "- When existingTopics is not empty, prefer a matching existing topic over NEW; never invent or guess a topicId.",
2754
+ "Proposal field contract:",
2755
+ "- SKIP contains only schemaVersion, action, source, and a concrete skipReason.",
2756
+ "- Every non-SKIP proposal must provide profile, decisionWindowId, decisionType, alternativeActionType, anchorFactId, knownFactRefs, outcomeFactRefs, trigger, rule, boundary, behavior, alternativeAction, expectedLocalEffect, observedLocalEffect, falsifier, and alternatives.",
2757
+ "- Never send null for an omitted field. Omit the key instead. alternativeTargetSeat may be null only to represent an explicit DAY_VOTE abstention.",
2758
+ "Execution versus strategy contract:",
2759
+ "- executionOperation must be one of the exact template operations. To claim execution risk, copy that template's operation, decisionType, trigger, rule, boundary, and alternativeAction exactly.",
2760
+ "- Strategy proposals must omit executionOperation. CHOOSE_VOTE_TARGET and CHOOSE_ROLE_CLAIM_TIMING are decision types, never executionOperation values.",
2761
+ "Call werewolf_debrief_commit exactly once after checking the complete proposal against this contract.",
2762
+ "After the tool returns, regardless of accepted or rejected status, return exactly NO_REPLY. Never retry the tool call.",
2710
2763
  "Do not return NO_REPLY before werewolf_debrief_commit returns a result.",
2711
2764
  "Never use generic write, edit, patch, shell, or memory-write tools for debrief state."
2712
2765
  ].join("\n");
@@ -2722,6 +2775,9 @@ var WerewolfEvolutionService = class {
2722
2775
  return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
2723
2776
  }
2724
2777
  if (!bound) {
2778
+ if (event.toolName === "werewolf_debrief_commit" || event.toolName === "werewolf_suggestion_decide") {
2779
+ return { block: true, blockReason: "NO_BOUND_CAPABILITY" };
2780
+ }
2725
2781
  const observed = runId ? this.observedRuns.get(runId) : void 0;
2726
2782
  if (!observed || observed.sessionKey !== ctx.sessionKey || observed.expiresAt < Date.now()) return void 0;
2727
2783
  const paths = resolveWorkspacePaths(observed.workspaceDir, false);
@@ -2880,6 +2936,18 @@ function proposalFailure(error) {
2880
2936
  return { status: "rejected", code: "EVOLUTION_ERROR", message: error instanceof Error ? error.message : String(error) };
2881
2937
  }
2882
2938
 
2939
+ // src/runtime-service.ts
2940
+ var SHARED_SERVICE_KEY = /* @__PURE__ */ Symbol.for("@clawtopia/werewolf-evolution/runtime-service-v1");
2941
+ function getSharedWerewolfEvolutionService() {
2942
+ const runtime = globalThis;
2943
+ const version = getWerewolfEvolutionVersion();
2944
+ const existing = runtime[SHARED_SERVICE_KEY];
2945
+ if (existing?.version === version) return existing.service;
2946
+ const service = new WerewolfEvolutionService(version);
2947
+ runtime[SHARED_SERVICE_KEY] = { version, service };
2948
+ return service;
2949
+ }
2950
+
2883
2951
  // src/tools.ts
2884
2952
  import { Type } from "typebox";
2885
2953
  import {
@@ -2889,7 +2957,9 @@ var proposalParameters = Type.Object({
2889
2957
  schemaVersion: Type.Literal(1),
2890
2958
  action: Type.Union(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW"].map((value) => Type.Literal(value))),
2891
2959
  source: Type.Union(["SELF", "OBSERVED", "EXEMPLAR"].map((value) => Type.Literal(value))),
2892
- topicId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
2960
+ topicId: Type.Optional(Type.String({
2961
+ description: "Existing lesson id for SUPPORT, COUNTER, or REFINE. Omit for NEW and SKIP; never send null."
2962
+ })),
2893
2963
  profile: Type.Optional(Type.String()),
2894
2964
  decisionWindowId: Type.Optional(Type.String()),
2895
2965
  decisionType: Type.Optional(Type.String()),
@@ -2899,7 +2969,9 @@ var proposalParameters = Type.Object({
2899
2969
  Type.Literal("RETRACT_PUBLIC_JUDGMENT"),
2900
2970
  Type.Literal("AVOID_REPEATING_PRIOR_SPEAKERS"),
2901
2971
  Type.Literal("EXPLAIN_DECIDED_WOLF_TARGET")
2902
- ])),
2972
+ ], {
2973
+ description: "Exact operation from executionTemplates. Omit for strategy proposals; never invent an operation."
2974
+ })),
2903
2975
  alternativeActionType: Type.Optional(Type.String()),
2904
2976
  alternativeTargetSeat: Type.Optional(Type.Union([Type.Integer(), Type.Null()])),
2905
2977
  anchorFactId: Type.Optional(Type.String()),
@@ -2912,7 +2984,9 @@ var proposalParameters = Type.Object({
2912
2984
  alternativeAction: Type.Optional(Type.String()),
2913
2985
  expectedLocalEffect: Type.Optional(Type.String()),
2914
2986
  observedLocalEffect: Type.Optional(Type.String()),
2915
- falsifier: Type.Optional(Type.String()),
2987
+ falsifier: Type.Optional(Type.String({
2988
+ description: "Concrete later observation that would falsify the lesson. Required for every non-SKIP proposal."
2989
+ })),
2916
2990
  alternatives: Type.Optional(Type.Array(Type.String())),
2917
2991
  skipReason: Type.Optional(Type.String())
2918
2992
  }, { additionalProperties: false });
@@ -2958,7 +3032,7 @@ function createSuggestionDecideTool(service, ctx) {
2958
3032
  }
2959
3033
 
2960
3034
  // index.ts
2961
- function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()) {
3035
+ function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionService()) {
2962
3036
  api.registerTool((ctx) => createDebriefCommitTool(service, ctx), { name: "werewolf_debrief_commit" });
2963
3037
  api.registerTool((ctx) => createSuggestionDecideTool(service, ctx), { name: "werewolf_suggestion_decide" });
2964
3038
  api.on("message_received", (event, ctx) => {
@@ -2969,6 +3043,7 @@ function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()
2969
3043
  return service.buildPromptContext(ctx);
2970
3044
  });
2971
3045
  api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
3046
+ api.on("message_sending", (event, ctx) => service.isSystemDebriefMessage(event, ctx) ? { cancel: true } : void 0);
2972
3047
  api.on("agent_end", (event, ctx) => {
2973
3048
  service.finishRun({ runId: event.runId ?? ctx.runId, sessionKey: ctx.sessionKey });
2974
3049
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawtopia/werewolf-evolution",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Deterministic postgame evolution runtime for the Clawtopia Werewolf Play skill.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",