@clawtopia/werewolf-evolution 0.1.4 → 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 +32 -7
- package/dist/index.js +269 -62
- package/package.json +1 -1
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
|
}
|
|
@@ -116,6 +117,7 @@ interface MessageReceivedLike {
|
|
|
116
117
|
from: string;
|
|
117
118
|
content: string;
|
|
118
119
|
messageId?: string;
|
|
120
|
+
sessionKey?: string;
|
|
119
121
|
runId?: string;
|
|
120
122
|
}
|
|
121
123
|
interface MessageContextLike {
|
|
@@ -144,15 +146,20 @@ interface AgentRunContextLike {
|
|
|
144
146
|
}
|
|
145
147
|
declare class EvolutionContextStore {
|
|
146
148
|
private readonly inboundByRun;
|
|
149
|
+
private readonly inboundBySession;
|
|
147
150
|
private readonly boundByRun;
|
|
148
151
|
private readonly hashByDebriefId;
|
|
149
152
|
private readonly toolCalls;
|
|
150
153
|
capture(event: MessageReceivedLike, ctx: MessageContextLike, now?: number): CapturedInbound | undefined;
|
|
151
|
-
getPending(runId?: string, sessionKey?: string, now?: number): CapturedInbound | undefined;
|
|
152
|
-
|
|
154
|
+
getPending(runId?: string, sessionKey?: string, prompt?: string, now?: number): CapturedInbound | undefined;
|
|
155
|
+
private storeInbound;
|
|
156
|
+
bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, now?: number, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedInbound): BoundRun | undefined;
|
|
153
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;
|
|
154
161
|
consume(runId: string, sessionKey: string, now?: number): BoundRun;
|
|
155
|
-
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;
|
|
156
163
|
consumeToolCall(toolCallId: string, sessionKey?: string, now?: number): BoundRun;
|
|
157
164
|
cleanup(now?: number): void;
|
|
158
165
|
}
|
|
@@ -171,18 +178,34 @@ interface SuggestionDecisionInput {
|
|
|
171
178
|
}
|
|
172
179
|
interface PromptContextLike extends AgentRunContextLike {
|
|
173
180
|
}
|
|
181
|
+
interface PromptBuildEventLike {
|
|
182
|
+
prompt: string;
|
|
183
|
+
}
|
|
184
|
+
interface OrdinaryDirectMessage {
|
|
185
|
+
channelId: string;
|
|
186
|
+
accountId: string;
|
|
187
|
+
from: string;
|
|
188
|
+
sessionKey: string;
|
|
189
|
+
content: string;
|
|
190
|
+
capturedAt: number;
|
|
191
|
+
}
|
|
174
192
|
declare class WerewolfEvolutionService {
|
|
175
193
|
readonly contexts: EvolutionContextStore;
|
|
176
194
|
private readonly version;
|
|
177
195
|
private readonly ordinaryDirectMessages;
|
|
196
|
+
private readonly ordinaryDirectMessagesBySession;
|
|
178
197
|
private readonly ownerDirectRuns;
|
|
179
198
|
private readonly observedRuns;
|
|
180
199
|
constructor(version?: string);
|
|
200
|
+
private cleanupOrdinaryDirectMessages;
|
|
181
201
|
captureMessage(event: MessageReceivedLike, ctx: MessageContextLike): void;
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
202
|
+
private pendingOrdinaryDirectMessage;
|
|
203
|
+
private consumeOrdinaryDirectMessage;
|
|
204
|
+
bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedDebrief | CapturedSuggestionCommand, pendingOrdinary?: OrdinaryDirectMessage): void;
|
|
205
|
+
bindPromptRun(event: PromptBuildEventLike, ctx: AgentRunContextLike, config: unknown): void;
|
|
206
|
+
finishRun(ctx: Pick<AgentRunContextLike, "runId" | "sessionKey">): void;
|
|
207
|
+
buildPromptContext(ctx: PromptContextLike, hooks?: TransactionHooks): {
|
|
208
|
+
prependContext: string;
|
|
186
209
|
} | undefined;
|
|
187
210
|
beforeToolCall(event: {
|
|
188
211
|
toolName: string;
|
|
@@ -195,10 +218,12 @@ declare class WerewolfEvolutionService {
|
|
|
195
218
|
sessionKey?: string;
|
|
196
219
|
runId?: string;
|
|
197
220
|
toolCallId?: string;
|
|
221
|
+
agentId?: string;
|
|
198
222
|
}): {
|
|
199
223
|
block?: boolean;
|
|
200
224
|
blockReason?: string;
|
|
201
225
|
} | undefined;
|
|
226
|
+
private persistIncident;
|
|
202
227
|
commit(toolCallId: string, ctx: OpenClawPluginToolContext, input: CommitInput, hooks?: TransactionHooks): Record<string, unknown>;
|
|
203
228
|
decideSuggestion(toolCallId: string, ctx: OpenClawPluginToolContext, input: SuggestionDecisionInput, hooks?: TransactionHooks): Record<string, unknown>;
|
|
204
229
|
}
|
package/dist/index.js
CHANGED
|
@@ -324,7 +324,7 @@ function isUnknownEligibilityValue(value) {
|
|
|
324
324
|
var CAPTURE_TTL_MS = 10 * 60 * 1e3;
|
|
325
325
|
var MAX_CAPTURES = 256;
|
|
326
326
|
var SUGGESTION_COMMAND = /^\s*(采纳|忽略|拒绝)\s+(S-\d{3,6})\s*[。.!!]?\s*$/i;
|
|
327
|
-
var
|
|
327
|
+
var LEGACY_DIRECT_CONVERSATION = /^private:(?:HUMAN|human):([0-9]+)$/;
|
|
328
328
|
function isExplicitConfiguredOwner(config, channelId, senderId) {
|
|
329
329
|
if (channelId !== "clawtopia" && channelId !== "coolclaw" || !senderId) return false;
|
|
330
330
|
const owners = record(record(config)?.commands)?.ownerAllowFrom;
|
|
@@ -344,8 +344,11 @@ function sameHumanSender(left, right) {
|
|
|
344
344
|
}
|
|
345
345
|
function isHumanDirectMessage(event, ctx) {
|
|
346
346
|
if (ctx.channelId !== "clawtopia" && ctx.channelId !== "coolclaw") return false;
|
|
347
|
-
if (!ctx.conversationId
|
|
348
|
-
|
|
347
|
+
if (!ctx.conversationId) return false;
|
|
348
|
+
const legacy = LEGACY_DIRECT_CONVERSATION.exec(ctx.conversationId);
|
|
349
|
+
const canonical = new RegExp(`^${ctx.channelId}:human:([0-9]+)$`).exec(ctx.conversationId);
|
|
350
|
+
const humanId = legacy?.[1] ?? canonical?.[1];
|
|
351
|
+
return humanId !== void 0 && humanId !== "0" && event.from === `${ctx.channelId}:human:${humanId}`;
|
|
349
352
|
}
|
|
350
353
|
function normalizedAccountId(value) {
|
|
351
354
|
return value?.trim() || "default";
|
|
@@ -365,13 +368,15 @@ function resolveAgentAccountBinding(config, channelId, accountId) {
|
|
|
365
368
|
}
|
|
366
369
|
var EvolutionContextStore = class {
|
|
367
370
|
inboundByRun = /* @__PURE__ */ new Map();
|
|
371
|
+
inboundBySession = /* @__PURE__ */ new Map();
|
|
368
372
|
boundByRun = /* @__PURE__ */ new Map();
|
|
369
373
|
hashByDebriefId = /* @__PURE__ */ new Map();
|
|
370
374
|
toolCalls = /* @__PURE__ */ new Map();
|
|
371
375
|
capture(event, ctx, now = Date.now()) {
|
|
372
376
|
this.cleanup(now);
|
|
373
377
|
const runId = event.runId ?? ctx.runId;
|
|
374
|
-
|
|
378
|
+
const sessionKey = event.sessionKey ?? ctx.sessionKey;
|
|
379
|
+
if (!sessionKey) return void 0;
|
|
375
380
|
if (isTrustedDebriefOrigin(ctx.channelId, event.from)) {
|
|
376
381
|
try {
|
|
377
382
|
const { envelope, bodyHash } = parseDebriefBody(event.content);
|
|
@@ -381,7 +386,7 @@ var EvolutionContextStore = class {
|
|
|
381
386
|
channelId: ctx.channelId,
|
|
382
387
|
accountId: normalizedAccountId(ctx.accountId),
|
|
383
388
|
from: event.from,
|
|
384
|
-
sessionKey
|
|
389
|
+
sessionKey,
|
|
385
390
|
runId,
|
|
386
391
|
conversationId: ctx.conversationId,
|
|
387
392
|
messageId: event.messageId,
|
|
@@ -392,7 +397,7 @@ var EvolutionContextStore = class {
|
|
|
392
397
|
...prior && prior.hash !== bodyHash ? { conflict: true } : {}
|
|
393
398
|
};
|
|
394
399
|
this.hashByDebriefId.set(envelope.debriefId, prior ?? { hash: bodyHash, capturedAt: now });
|
|
395
|
-
this.
|
|
400
|
+
this.storeInbound(captured);
|
|
396
401
|
return captured;
|
|
397
402
|
} catch {
|
|
398
403
|
return void 0;
|
|
@@ -405,7 +410,7 @@ var EvolutionContextStore = class {
|
|
|
405
410
|
channelId: ctx.channelId,
|
|
406
411
|
accountId: normalizedAccountId(ctx.accountId),
|
|
407
412
|
from: event.from,
|
|
408
|
-
sessionKey
|
|
413
|
+
sessionKey,
|
|
409
414
|
runId,
|
|
410
415
|
conversationId: ctx.conversationId,
|
|
411
416
|
messageId: event.messageId,
|
|
@@ -414,21 +419,38 @@ var EvolutionContextStore = class {
|
|
|
414
419
|
decision: match[1] === "\u91C7\u7EB3" ? "accept" : "reject",
|
|
415
420
|
capturedAt: now
|
|
416
421
|
};
|
|
417
|
-
this.
|
|
422
|
+
this.storeInbound(command);
|
|
418
423
|
return command;
|
|
419
424
|
}
|
|
420
|
-
getPending(runId, sessionKey, now = Date.now()) {
|
|
425
|
+
getPending(runId, sessionKey, prompt, now = Date.now()) {
|
|
421
426
|
this.cleanup(now);
|
|
422
427
|
if (!runId || !sessionKey) return void 0;
|
|
423
428
|
const inbound = this.inboundByRun.get(runId);
|
|
424
|
-
|
|
429
|
+
if (inbound) {
|
|
430
|
+
return inbound.sessionKey === sessionKey && now - inbound.capturedAt <= CAPTURE_TTL_MS ? inbound : void 0;
|
|
431
|
+
}
|
|
432
|
+
if (!prompt) return void 0;
|
|
433
|
+
const pending = this.inboundBySession.get(sessionKey);
|
|
434
|
+
if (!pending) return void 0;
|
|
435
|
+
return pending.find((candidate) => prompt.includes(candidate.content));
|
|
425
436
|
}
|
|
426
|
-
|
|
437
|
+
storeInbound(inbound) {
|
|
438
|
+
if (inbound.runId) {
|
|
439
|
+
this.inboundByRun.set(inbound.runId, inbound);
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const pending = this.inboundBySession.get(inbound.sessionKey) ?? [];
|
|
443
|
+
pending.push(inbound);
|
|
444
|
+
this.inboundBySession.set(inbound.sessionKey, pending);
|
|
445
|
+
}
|
|
446
|
+
bindAgentRun(event, ctx, binding, now = Date.now(), explicitOwnerAuthorized = false, pendingInbound) {
|
|
427
447
|
this.cleanup(now);
|
|
428
448
|
if (!ctx.runId || !ctx.sessionKey || !ctx.agentId || !ctx.workspaceDir) return void 0;
|
|
429
|
-
const
|
|
449
|
+
const runInbound = this.inboundByRun.get(ctx.runId);
|
|
450
|
+
const sessionPending = this.inboundBySession.get(ctx.sessionKey);
|
|
451
|
+
const pendingIndex = pendingInbound ? sessionPending?.indexOf(pendingInbound) ?? -1 : -1;
|
|
452
|
+
const inbound = runInbound ?? (pendingIndex >= 0 ? pendingInbound : void 0);
|
|
430
453
|
if (!inbound || inbound.sessionKey !== ctx.sessionKey || now - inbound.capturedAt > CAPTURE_TTL_MS) return void 0;
|
|
431
|
-
this.inboundByRun.delete(ctx.runId);
|
|
432
454
|
const eventAccountId = normalizedAccountId(event.accountId);
|
|
433
455
|
if (event.channelId !== inbound.channelId || eventAccountId !== inbound.accountId) return void 0;
|
|
434
456
|
if (!binding || binding.channelId !== inbound.channelId || binding.accountId !== inbound.accountId) return void 0;
|
|
@@ -437,6 +459,12 @@ var EvolutionContextStore = class {
|
|
|
437
459
|
} else {
|
|
438
460
|
if (!explicitOwnerAuthorized || event.senderIsOwner !== true || !event.senderId || normalizedSender(event.senderId) !== normalizedSender(inbound.from)) return void 0;
|
|
439
461
|
}
|
|
462
|
+
if (runInbound) {
|
|
463
|
+
this.inboundByRun.delete(ctx.runId);
|
|
464
|
+
} else {
|
|
465
|
+
sessionPending.splice(pendingIndex, 1);
|
|
466
|
+
if (sessionPending.length === 0) this.inboundBySession.delete(ctx.sessionKey);
|
|
467
|
+
}
|
|
440
468
|
const bound = {
|
|
441
469
|
runId: ctx.runId,
|
|
442
470
|
sessionKey: ctx.sessionKey,
|
|
@@ -458,6 +486,34 @@ var EvolutionContextStore = class {
|
|
|
458
486
|
const bound = this.boundByRun.get(runId);
|
|
459
487
|
return bound?.sessionKey === sessionKey && bound.expiresAt >= now ? bound : void 0;
|
|
460
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
|
+
}
|
|
461
517
|
consume(runId, sessionKey, now = Date.now()) {
|
|
462
518
|
const bound = this.getBound(runId, sessionKey, now);
|
|
463
519
|
if (!bound) throw new Error("NO_BOUND_CAPABILITY");
|
|
@@ -465,14 +521,14 @@ var EvolutionContextStore = class {
|
|
|
465
521
|
bound.consumed = true;
|
|
466
522
|
return bound;
|
|
467
523
|
}
|
|
468
|
-
authorizeToolCall(runId, sessionKey, toolCallId, now = Date.now()) {
|
|
524
|
+
authorizeToolCall(runId, sessionKey, toolCallId, now = Date.now(), agentId) {
|
|
469
525
|
this.cleanup(now);
|
|
470
|
-
if (!
|
|
471
|
-
const bound = this.
|
|
526
|
+
if (!sessionKey || !toolCallId) throw new Error("TOOL_CALL_CONTEXT_MISSING");
|
|
527
|
+
const bound = this.resolveBoundForToolCall(runId, sessionKey, agentId, false, now);
|
|
472
528
|
if (!bound) throw new Error("NO_BOUND_CAPABILITY");
|
|
473
529
|
if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
|
|
474
530
|
if (this.toolCalls.has(toolCallId)) throw new Error("TOOL_CALL_ALREADY_AUTHORIZED");
|
|
475
|
-
this.toolCalls.set(toolCallId, { runId, sessionKey, expiresAt: bound.expiresAt });
|
|
531
|
+
this.toolCalls.set(toolCallId, { runId: bound.runId, sessionKey, expiresAt: bound.expiresAt });
|
|
476
532
|
return bound;
|
|
477
533
|
}
|
|
478
534
|
consumeToolCall(toolCallId, sessionKey, now = Date.now()) {
|
|
@@ -488,6 +544,11 @@ var EvolutionContextStore = class {
|
|
|
488
544
|
for (const [key, value] of this.inboundByRun) {
|
|
489
545
|
if (now - value.capturedAt > CAPTURE_TTL_MS) this.inboundByRun.delete(key);
|
|
490
546
|
}
|
|
547
|
+
for (const [key, values] of this.inboundBySession) {
|
|
548
|
+
const current = values.filter((value) => now - value.capturedAt <= CAPTURE_TTL_MS);
|
|
549
|
+
if (current.length === 0) this.inboundBySession.delete(key);
|
|
550
|
+
else if (current.length !== values.length) this.inboundBySession.set(key, current);
|
|
551
|
+
}
|
|
491
552
|
for (const [key, value] of this.boundByRun) {
|
|
492
553
|
if (value.expiresAt < now) this.boundByRun.delete(key);
|
|
493
554
|
}
|
|
@@ -498,6 +559,13 @@ var EvolutionContextStore = class {
|
|
|
498
559
|
if (now - value.capturedAt > CAPTURE_TTL_MS) this.hashByDebriefId.delete(key);
|
|
499
560
|
}
|
|
500
561
|
while (this.inboundByRun.size > MAX_CAPTURES) this.inboundByRun.delete(this.inboundByRun.keys().next().value);
|
|
562
|
+
while ([...this.inboundBySession.values()].reduce((total, values) => total + values.length, 0) > MAX_CAPTURES) {
|
|
563
|
+
const firstKey = this.inboundBySession.keys().next().value;
|
|
564
|
+
if (!firstKey) break;
|
|
565
|
+
const values = this.inboundBySession.get(firstKey);
|
|
566
|
+
values.shift();
|
|
567
|
+
if (values.length === 0) this.inboundBySession.delete(firstKey);
|
|
568
|
+
}
|
|
501
569
|
while (this.boundByRun.size > MAX_CAPTURES) this.boundByRun.delete(this.boundByRun.keys().next().value);
|
|
502
570
|
while (this.toolCalls.size > MAX_CAPTURES) this.toolCalls.delete(this.toolCalls.keys().next().value);
|
|
503
571
|
while (this.hashByDebriefId.size > MAX_CAPTURES) this.hashByDebriefId.delete(this.hashByDebriefId.keys().next().value);
|
|
@@ -2266,6 +2334,8 @@ function getWerewolfEvolutionVersion() {
|
|
|
2266
2334
|
}
|
|
2267
2335
|
|
|
2268
2336
|
// src/service.ts
|
|
2337
|
+
var DIRECT_MESSAGE_TTL_MS = 10 * 60 * 1e3;
|
|
2338
|
+
var MAX_DIRECT_MESSAGES = 256;
|
|
2269
2339
|
function clone(value) {
|
|
2270
2340
|
return structuredClone(value);
|
|
2271
2341
|
}
|
|
@@ -2369,35 +2439,83 @@ var WerewolfEvolutionService = class {
|
|
|
2369
2439
|
contexts = new EvolutionContextStore();
|
|
2370
2440
|
version;
|
|
2371
2441
|
ordinaryDirectMessages = /* @__PURE__ */ new Map();
|
|
2442
|
+
ordinaryDirectMessagesBySession = /* @__PURE__ */ new Map();
|
|
2372
2443
|
ownerDirectRuns = /* @__PURE__ */ new Map();
|
|
2373
2444
|
observedRuns = /* @__PURE__ */ new Map();
|
|
2374
2445
|
constructor(version = getWerewolfEvolutionVersion()) {
|
|
2375
2446
|
this.version = version;
|
|
2376
2447
|
}
|
|
2448
|
+
cleanupOrdinaryDirectMessages(now) {
|
|
2449
|
+
for (const [runId, inbound] of this.ordinaryDirectMessages) {
|
|
2450
|
+
if (now - inbound.capturedAt > DIRECT_MESSAGE_TTL_MS) this.ordinaryDirectMessages.delete(runId);
|
|
2451
|
+
}
|
|
2452
|
+
for (const [sessionKey, inbounds] of this.ordinaryDirectMessagesBySession) {
|
|
2453
|
+
const current = inbounds.filter((inbound) => now - inbound.capturedAt <= DIRECT_MESSAGE_TTL_MS);
|
|
2454
|
+
if (current.length === 0) this.ordinaryDirectMessagesBySession.delete(sessionKey);
|
|
2455
|
+
else if (current.length !== inbounds.length) this.ordinaryDirectMessagesBySession.set(sessionKey, current);
|
|
2456
|
+
}
|
|
2457
|
+
while (this.ordinaryDirectMessages.size > MAX_DIRECT_MESSAGES) {
|
|
2458
|
+
this.ordinaryDirectMessages.delete(this.ordinaryDirectMessages.keys().next().value);
|
|
2459
|
+
}
|
|
2460
|
+
while ([...this.ordinaryDirectMessagesBySession.values()].reduce((total, inbounds) => total + inbounds.length, 0) > MAX_DIRECT_MESSAGES) {
|
|
2461
|
+
const firstKey = this.ordinaryDirectMessagesBySession.keys().next().value;
|
|
2462
|
+
if (!firstKey) break;
|
|
2463
|
+
const inbounds = this.ordinaryDirectMessagesBySession.get(firstKey);
|
|
2464
|
+
inbounds.shift();
|
|
2465
|
+
if (inbounds.length === 0) this.ordinaryDirectMessagesBySession.delete(firstKey);
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2377
2468
|
captureMessage(event, ctx) {
|
|
2469
|
+
const now = Date.now();
|
|
2470
|
+
this.cleanupOrdinaryDirectMessages(now);
|
|
2378
2471
|
const captured = this.contexts.capture(event, ctx);
|
|
2379
2472
|
const runId = event.runId ?? ctx.runId;
|
|
2380
|
-
|
|
2381
|
-
|
|
2473
|
+
const sessionKey = event.sessionKey ?? ctx.sessionKey;
|
|
2474
|
+
if (!captured && sessionKey && isHumanDirectMessage(event, ctx)) {
|
|
2475
|
+
const direct = {
|
|
2382
2476
|
channelId: ctx.channelId,
|
|
2383
2477
|
accountId: normalizedAccountId(ctx.accountId),
|
|
2384
2478
|
from: event.from,
|
|
2385
|
-
sessionKey
|
|
2386
|
-
|
|
2387
|
-
|
|
2479
|
+
sessionKey,
|
|
2480
|
+
content: event.content,
|
|
2481
|
+
capturedAt: now
|
|
2482
|
+
};
|
|
2483
|
+
if (runId) {
|
|
2484
|
+
this.ordinaryDirectMessages.set(runId, direct);
|
|
2485
|
+
} else {
|
|
2486
|
+
const pending = this.ordinaryDirectMessagesBySession.get(sessionKey) ?? [];
|
|
2487
|
+
pending.push(direct);
|
|
2488
|
+
this.ordinaryDirectMessagesBySession.set(sessionKey, pending);
|
|
2489
|
+
}
|
|
2490
|
+
this.cleanupOrdinaryDirectMessages(now);
|
|
2388
2491
|
}
|
|
2389
2492
|
}
|
|
2390
|
-
|
|
2493
|
+
pendingOrdinaryDirectMessage(runId, sessionKey, prompt, now) {
|
|
2494
|
+
if (!runId || !sessionKey) return void 0;
|
|
2495
|
+
const byRun = this.ordinaryDirectMessages.get(runId);
|
|
2496
|
+
if (byRun) return byRun.sessionKey === sessionKey ? byRun : void 0;
|
|
2497
|
+
return this.ordinaryDirectMessagesBySession.get(sessionKey)?.find((candidate) => now - candidate.capturedAt <= DIRECT_MESSAGE_TTL_MS && prompt.includes(candidate.content));
|
|
2498
|
+
}
|
|
2499
|
+
consumeOrdinaryDirectMessage(runId, direct) {
|
|
2500
|
+
if (this.ordinaryDirectMessages.get(runId) === direct) {
|
|
2501
|
+
this.ordinaryDirectMessages.delete(runId);
|
|
2502
|
+
return;
|
|
2503
|
+
}
|
|
2504
|
+
const pending = this.ordinaryDirectMessagesBySession.get(direct.sessionKey);
|
|
2505
|
+
const index = pending?.indexOf(direct) ?? -1;
|
|
2506
|
+
if (index < 0) return;
|
|
2507
|
+
pending.splice(index, 1);
|
|
2508
|
+
if (pending.length === 0) this.ordinaryDirectMessagesBySession.delete(direct.sessionKey);
|
|
2509
|
+
}
|
|
2510
|
+
bindAgentRun(event, ctx, binding, explicitOwnerAuthorized = false, pendingInbound, pendingOrdinary) {
|
|
2391
2511
|
const now = Date.now();
|
|
2512
|
+
this.cleanupOrdinaryDirectMessages(now);
|
|
2392
2513
|
for (const [runId, observed] of this.observedRuns) {
|
|
2393
2514
|
if (observed.expiresAt < now) this.observedRuns.delete(runId);
|
|
2394
2515
|
}
|
|
2395
2516
|
for (const [runId, direct] of this.ownerDirectRuns) {
|
|
2396
2517
|
if (direct.expiresAt < now) this.ownerDirectRuns.delete(runId);
|
|
2397
2518
|
}
|
|
2398
|
-
for (const [runId, inbound] of this.ordinaryDirectMessages) {
|
|
2399
|
-
if (now - inbound.capturedAt > 10 * 60 * 1e3) this.ordinaryDirectMessages.delete(runId);
|
|
2400
|
-
}
|
|
2401
2519
|
if (ctx.runId && ctx.sessionKey && ctx.agentId && ctx.workspaceDir) {
|
|
2402
2520
|
this.observedRuns.set(ctx.runId, {
|
|
2403
2521
|
sessionKey: ctx.sessionKey,
|
|
@@ -2406,22 +2524,29 @@ var WerewolfEvolutionService = class {
|
|
|
2406
2524
|
expiresAt: now + 10 * 60 * 1e3
|
|
2407
2525
|
});
|
|
2408
2526
|
}
|
|
2409
|
-
const bound = this.contexts.bindAgentRun(
|
|
2410
|
-
|
|
2411
|
-
|
|
2527
|
+
const bound = this.contexts.bindAgentRun(
|
|
2528
|
+
event,
|
|
2529
|
+
ctx,
|
|
2530
|
+
binding,
|
|
2531
|
+
Date.now(),
|
|
2532
|
+
explicitOwnerAuthorized,
|
|
2533
|
+
pendingInbound
|
|
2534
|
+
);
|
|
2535
|
+
const ordinary = (ctx.runId ? this.ordinaryDirectMessages.get(ctx.runId) : void 0) ?? pendingOrdinary;
|
|
2412
2536
|
if (!bound && ordinary && ctx.runId && ctx.sessionKey && ctx.agentId && ctx.workspaceDir && ordinary.sessionKey === ctx.sessionKey && ordinary.channelId === event.channelId && ordinary.accountId === normalizedAccountId(event.accountId) && explicitOwnerAuthorized && event.senderIsOwner === true && event.senderId && sameHumanSender(event.senderId, ordinary.from)) {
|
|
2413
2537
|
this.ownerDirectRuns.set(ctx.runId, {
|
|
2414
2538
|
sessionKey: ctx.sessionKey,
|
|
2415
2539
|
agentId: ctx.agentId,
|
|
2416
2540
|
workspaceDir: ctx.workspaceDir,
|
|
2417
2541
|
senderId: event.senderId,
|
|
2418
|
-
expiresAt: now +
|
|
2542
|
+
expiresAt: now + DIRECT_MESSAGE_TTL_MS
|
|
2419
2543
|
});
|
|
2544
|
+
this.consumeOrdinaryDirectMessage(ctx.runId, ordinary);
|
|
2420
2545
|
}
|
|
2421
2546
|
}
|
|
2422
|
-
bindPromptRun(ctx, config) {
|
|
2423
|
-
const pending = this.contexts.getPending(ctx.runId, ctx.sessionKey);
|
|
2424
|
-
const ordinary = ctx.runId
|
|
2547
|
+
bindPromptRun(event, ctx, config) {
|
|
2548
|
+
const pending = this.contexts.getPending(ctx.runId, ctx.sessionKey, event.prompt);
|
|
2549
|
+
const ordinary = this.pendingOrdinaryDirectMessage(ctx.runId, ctx.sessionKey, event.prompt, Date.now());
|
|
2425
2550
|
const inbound = pending ?? ordinary;
|
|
2426
2551
|
const channelId = inbound?.channelId;
|
|
2427
2552
|
const accountId = inbound?.accountId;
|
|
@@ -2448,10 +2573,18 @@ var WerewolfEvolutionService = class {
|
|
|
2448
2573
|
},
|
|
2449
2574
|
ctx,
|
|
2450
2575
|
resolveAgentAccountBinding(config, channelId, accountId),
|
|
2451
|
-
workspaceAuthorized
|
|
2576
|
+
workspaceAuthorized,
|
|
2577
|
+
pending,
|
|
2578
|
+
ordinary
|
|
2452
2579
|
);
|
|
2453
2580
|
}
|
|
2454
|
-
|
|
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 = {}) {
|
|
2455
2588
|
const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
|
|
2456
2589
|
if (!bound) {
|
|
2457
2590
|
const ownerRun = ctx.runId ? this.ownerDirectRuns.get(ctx.runId) : void 0;
|
|
@@ -2463,7 +2596,7 @@ var WerewolfEvolutionService = class {
|
|
|
2463
2596
|
const reminder = claimPendingSuggestionReminder(paths, this.version);
|
|
2464
2597
|
if (!reminder) return void 0;
|
|
2465
2598
|
return {
|
|
2466
|
-
|
|
2599
|
+
prependContext: [
|
|
2467
2600
|
"[werewolf-evolution pending suggestion reminder]",
|
|
2468
2601
|
"This is a trusted ordinary direct message from the Agent owner.",
|
|
2469
2602
|
`Remind the owner once about ${reminder.id}; do not call werewolf_suggestion_decide unless the original message is an exact decision command.`,
|
|
@@ -2480,6 +2613,7 @@ var WerewolfEvolutionService = class {
|
|
|
2480
2613
|
}
|
|
2481
2614
|
}
|
|
2482
2615
|
if (bound.agentId !== ctx.agentId || bound.workspaceDir !== ctx.workspaceDir) return void 0;
|
|
2616
|
+
if (bound.promptContext !== void 0) return { prependContext: bound.promptContext };
|
|
2483
2617
|
if (bound.inbound.kind === "suggestion-command") {
|
|
2484
2618
|
try {
|
|
2485
2619
|
const paths = resolveWorkspacePaths(bound.workspaceDir);
|
|
@@ -2488,11 +2622,38 @@ var WerewolfEvolutionService = class {
|
|
|
2488
2622
|
} catch {
|
|
2489
2623
|
return void 0;
|
|
2490
2624
|
}
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
};
|
|
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 };
|
|
2494
2627
|
}
|
|
2495
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
|
+
}
|
|
2496
2657
|
let topics = [];
|
|
2497
2658
|
let stateAvailable = true;
|
|
2498
2659
|
let activeProfile;
|
|
@@ -2511,6 +2672,19 @@ var WerewolfEvolutionService = class {
|
|
|
2511
2672
|
stateAvailable = false;
|
|
2512
2673
|
stateError = error instanceof Error ? error.message : String(error);
|
|
2513
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
|
+
}
|
|
2514
2688
|
const facts = captured.envelope.facts.map((fact) => ({
|
|
2515
2689
|
factId: fact.factId,
|
|
2516
2690
|
historyIndex: fact.availableAt.historyIndex,
|
|
@@ -2520,29 +2694,33 @@ var WerewolfEvolutionService = class {
|
|
|
2520
2694
|
targetSeat: fact.targetSeat,
|
|
2521
2695
|
summary: fact.summary
|
|
2522
2696
|
}));
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
};
|
|
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 };
|
|
2541
2714
|
}
|
|
2542
2715
|
beforeToolCall(event, ctx) {
|
|
2543
2716
|
const runId = event.runId ?? ctx.runId;
|
|
2544
2717
|
const toolCallId = event.toolCallId ?? ctx.toolCallId;
|
|
2545
|
-
|
|
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
|
+
}
|
|
2546
2724
|
if (!bound) {
|
|
2547
2725
|
const observed = runId ? this.observedRuns.get(runId) : void 0;
|
|
2548
2726
|
if (!observed || observed.sessionKey !== ctx.sessionKey || observed.expiresAt < Date.now()) return void 0;
|
|
@@ -2561,18 +2739,44 @@ var WerewolfEvolutionService = class {
|
|
|
2561
2739
|
if (bound.inbound.kind !== "debrief" || event.params.debriefId !== bound.inbound.envelope.debriefId) {
|
|
2562
2740
|
throw new Error("DEBRIEF_CAPABILITY_MISMATCH");
|
|
2563
2741
|
}
|
|
2564
|
-
this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
|
|
2742
|
+
this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
|
|
2565
2743
|
} else if (event.toolName === "werewolf_suggestion_decide") {
|
|
2566
2744
|
if (bound.inbound.kind !== "suggestion-command" || event.params.suggestionId !== bound.inbound.suggestionId || event.params.decision !== bound.inbound.decision) {
|
|
2567
2745
|
throw new Error("SUGGESTION_CAPABILITY_MISMATCH");
|
|
2568
2746
|
}
|
|
2569
|
-
this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
|
|
2747
|
+
this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
|
|
2570
2748
|
}
|
|
2571
2749
|
} catch (error) {
|
|
2572
2750
|
return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
|
|
2573
2751
|
}
|
|
2574
2752
|
return void 0;
|
|
2575
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
|
+
}
|
|
2576
2780
|
commit(toolCallId, ctx, input, hooks = {}) {
|
|
2577
2781
|
const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
|
|
2578
2782
|
const workspaceDir = requireToolWorkspace(ctx, bound);
|
|
@@ -2760,11 +2964,14 @@ function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()
|
|
|
2760
2964
|
api.on("message_received", (event, ctx) => {
|
|
2761
2965
|
service.captureMessage(event, ctx);
|
|
2762
2966
|
});
|
|
2763
|
-
api.on("before_prompt_build", (
|
|
2764
|
-
service.bindPromptRun(ctx, api.config);
|
|
2967
|
+
api.on("before_prompt_build", (event, ctx) => {
|
|
2968
|
+
service.bindPromptRun(event, ctx, api.config);
|
|
2765
2969
|
return service.buildPromptContext(ctx);
|
|
2766
2970
|
});
|
|
2767
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
|
+
});
|
|
2768
2975
|
}
|
|
2769
2976
|
var entry = definePluginEntry({
|
|
2770
2977
|
id: "werewolf-evolution",
|