8000 feat: make light sources authoritative by Mnehmos · Pull Request #102 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions src/agent/provider/openrouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ import {
classifyFetchError,
classifyHttpStatus
} from './types.js';
import {
isReasoningModel,
reasoningCompletionFloor
} from './reasoning.js';
import { isReasoningModel } from './reasoning.js';

const DEFAULT_BASE = 'https://openrouter.ai/api/v1';

Expand Down Expand Up @@ -76,9 +73,7 @@ export class OpenRouterProvider implements LLMProvider {
messages: opts.messages
};
if (opts.maxTokens !== undefined) {
body[reasoningModel ? 'max_completion_tokens' : 'max_tokens'] = reasoningModel
? Math.max(opts.maxTokens, reasoningCompletionFloor(opts.reasoningEffort))
: opts.maxTokens;
body[reasoningModel ? 'max_completion_tokens' : 'max_tokens'] = opts.maxTokens;
}
if (opts.temperature !== undefined && !reasoningModel) {
body.temperature = opts.temperature;
Expand Down
28 changes: 20 additions & 8 deletions src/agent/runtime/invoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,261 +102,273 @@
return resolveCompetency(character.stats.int, agent.competencyOverride);
}

export async function invokeAgent(input: InvokeInput, deps: AgentRuntimeDeps): Promise<InvokeResult> {
// 1. Resolve agent + character
const agent = resolveAgent(deps, input);
if (!agent) return notFound('agent_not_found');

const character = deps.characterRepo.findById(agent.characterId);
const competency = resolveInvocationCompetency(agent, character);
const resolvedModel = competency?.model ?? agent.model;

// 2. Preflight gates
const pre = preflight({ agent, character });
const pre = preflight({
agent,
character,
model: resolvedModel,
reasoningEffort: competency?.reasoningEffort ?? null
});
if (pre.skipped) {
// Persist a call row so health/audit reflects the skip
const call = deps.agentRepo.recordCall({
agentId: agent.id,
requestId: input.requestId ?? null,
provider: agent.provider,
model: resolvedModel,
messagesJson: '[]',
status: pre.status,
reasoningEffort: competency?.reasoningEffort ?? null,
competencySource: competency?.source ?? null,
errorMessage: pre.reason
});
return {
...emptyResult(agent, character, pre.status, pre.reason),
callId: call.id
};
}

// 2b. Scene-scope gate — SYSTEM.md Rule 5. Out-of-scene agents skipped
// unless distance-magic (remoteContact) overrides. Skipped invokes
// persist an audit row but NEVER throw and NEVER call the provider.
const scope = checkSceneScope(
{ encounterId: input.encounterId, sceneId: input.sceneId, remoteContact: input.remoteContact },
character,
deps
);
if (scope.skip) {
const call = deps.agentRepo.recordCall({
agentId: agent.id,
requestId: input.requestId ?? null,
provider: agent.provider,
model: resolvedModel,
messagesJson: '[]',
status: 'skipped',
reasoningEffort: competency?.reasoningEffort ?? null,
competencySource: competency?.source ?? null,
errorMessage: scope.reason ?? 'out_of_scene'
});
return {
...emptyResult(agent, character, 'skipped', scope.reason ?? 'out_of_scene'),
callId: call.id
};
}

// 2c. Distance-contact honored — synthesize a prefix so the agent's
// prompt makes the channel legible. Cannot pretend to see scene directly.
const effectiveSituation = input.remoteContact
? composeRemoteContactSituation(input.remoteContact, input.situation)
: input.situation;

// 3. Provider lookup
let provider;
try {
provider = deps.providerFactory.get(agent.provider);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const call = deps.agentRepo.recordCall({
agentId: agent.id,
requestId: input.requestId ?? null,
provider: agent.provider,
model: resolvedModel,
messagesJson: '[]',
status: 'error',
reasoningEffort: competency?.reasoningEffort ?? null,
competencySource: competency?.source ?? null,
errorMessage: message
});
return {
...emptyResult(agent, character, 'error', message),
callId: call.id
};
}

// 4. Compose prompt
const composed = composePrompt(
{
agentId: agent.id,
characterId: agent.characterId,
situation: effectiveSituation,
systemOverride: input.systemOverride,
messagesOverride: input.messagesOverride
},
deps
);

// 5. Call provider with timeout
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), agent.timeoutMs);
const remainingBudget = agent.budgetTokens === null
? null
: Math.max(0, agent.budgetTokens - agent.tokensUsed);
const completionBudget = remainingBudget === null
? agent.maxTokens
: Math.min(agent.maxTokens, remainingBudget);

try {
const result = await provider.call({
model: resolvedModel,
messages: composed.messages,
temperature: agent.temperature,
maxTokens: agent.maxTokens,
maxTokens: completionBudget,
reasoningEffort: competency?.reasoningEffort ?? null,
signal: controller.signal
});
clearTimeout(timeout);

// Account the provider's reported usage when available. A gateway that
// omits usage still consumes a conservative estimate, so a bounded
// budget cannot be bypassed by an incomplete response envelope.
const promptTokens = result.promptTokens ?? estimateTokens(composed.messages);
const completionTokens = result.completionTokens ?? estimateTokens(result.text);
const tokensSpent = promptTokens + completionTokens;
if (tokensSpent > 0) {
deps.agentRepo.incrementTokensUsed(agent.id, tokensSpent);
}
const accountedAgent = deps.agentRepo.findById(agent.id) ?? agent;
const budgetExceeded = accountedAgent.budgetTokens !== null
&& accountedAgent.tokensUsed > accountedAgent.budgetTokens;
&& accountedAgent.tokensUsed >= accountedAgent.budgetTokens;
const callStatus: AgentCallStatus = budgetExceeded ? 'budget_exhausted' : 'ok';
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const budgetMessage = budgetExceeded
? `provider response exceeded token budget (used ${accountedAgent.tokensUsed} of ${accountedAgent.budgetTokens})`
: undefined;

// 6. Success path. A response that crossed a hard budget is recorded
// as unavailable and is not surfaced as NPC action state.
const call = deps.agentRepo.recordCall({
agentId: agent.id,
requestId: input.requestId ?? null,
provider: agent.provider,
model: resolvedModel,
messagesJson: JSON.stringify(composed.messages),
rawResponse: result.raw,
promptTokens,
completionTokens,
durationMs: result.durationMs,
status: callStatus,
reasoningEffort: competency?.reasoningEffort ?? null,
competencySource: competency?.source ?? null,
errorMessage: budgetMessage ?? null
});

// The provider returned successfully even when accounting exhausted the
// budget, so clear stale circuit failures before this result exits.
if (agent.consecutiveFailures > 0 || agent.circuitState !== 'closed') {
deps.agentRepo.recordSuccess(agent.id);
}

if (budgetExceeded) {
return {
Comment on lines +269 to +270
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset provider failures before returning on budget overflow

When an agent has one or two consecutive provider failures and the next provider call succeeds but crosses the token budget, this early return bypasses recordSuccess below. After the DM resets or increases the budget, the stale failures remain, so one subsequent transient failure can open the circuit even though the intervening provider call succeeded. Clear the circuit failure state for this successful provider call before returning the budget-exhausted result.

Useful? React with 👍 / 👎.

callId: call.id,
agentId: agent.id,
characterId: agent.characterId,
characterName: character?.name ?? null,
response: '',
status: 'budget_exhausted',
reason: budgetMessage,
promptTokens: result.promptTokens ?? null,
completionTokens: result.completionTokens ?? null,
durationMs: result.durationMs,
finishReason: result.finishReason
};
}

// Close the circuit on success.
if (agent.consecutiveFailures > 0 || agent.circuitState !== 'closed') {
deps.agentRepo.recordSuccess(agent.id);
}

// Auto-append response to agent journal.
deps.agentRepo.addJournalEntry({
agentId: agent.id,
kind: 'response',
content: result.text,
encounterId: input.encounterId ?? null,
round: input.round ?? null
});

// Emit event_inbox row for frontend polling — npc_action with the response payload.
try {
deps.eventInboxRepo.push({
eventType: 'npc_action',
sourceType: 'npc',
sourceId: agent.characterId,
priority: 5,
payload: {
agentId: agent.id,
characterId: agent.characterId,
characterName: character?.name ?? null,
response: result.text,
callId: call.id,
encounterId: input.encounterId ?? null,
round: input.round ?? null,
promptTokens: result.promptTokens ?? null,
completionTokens: result.completionTokens ?? null,
durationMs: result.durationMs,
status: 'ok'
}
});
} catch {
// Event emission must never break invoke — it's a one-way notification.
}

return {
callId: call.id,
agentId: agent.id,
characterId: agent.characterId,
characterName: character?.name ?? null,
response: result.text,
status: 'ok',
promptTokens: result.promptTokens ?? null,
completionTokens: result.completionTokens ?? null,
durationMs: result.durationMs,
finishReason: result.finishReason
};
} catch (err) {
clearTimeout(timeout);

// 7. Failure path
const providerErr = err instanceof ProviderError ? err : null;
const status: AgentCallStatus = providerErr
? (providerErr.kind === 'timeout' ? 'timeout'
: providerErr.kind === 'rate_limited' ? 'rate_limited'
: 'error')
: 'error';
const message = err instanceof Error ? err.message : String(err);

const call = deps.agentRepo.recordCall({
agentId: agent.id,
requestId: input.requestId ?? null,
provider: agent.provider,
model: resolvedModel,
messagesJson: JSON.stringify(composed.messages),
rawResponse: providerErr?.raw ?? null,
durationMs: null,
status,
reasoningEffort: competency?.reasoningEffort ?? null,
competencySource: competency?.source ?? null,
errorMessage: message
});

if (shouldTripCircuit(err)) {
deps.agentRepo.recordFailure(agent.id);
}

return {
callId: call.id,
agentId: agent.id,
characterId: agent.characterId,
characterName: character?.name ?? null,
response: '',
status,
reason: message,
promptTokens: null,
completionTokens: null,
durationMs: null
};
}
}

Check warning on line 374 in src/agent/runtime/invoke.ts

View check run for this annotation

Repowise Bot / Repowise / code health

Introduced: brain method

Brain Method: invokeAgent is 229 lines, CCN 24, in a file imported by 6 others
17 changes: 17 additions & 0 deletions src/agent/runtime/preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import { Agent } from '../../schema/agent.js';
import { Character, NPC } from '../../schema/character.js';
import { AgentCallStatus } from '../../schema/agent.js';
import { ReasoningEffort } from '../../schema/agent.js';
import { isReasoningModel, reasoningCompletionFloor } from '../provider/reasoning.js';

/** Conditions that should prevent the agent from acting. */
const INCAPACITATING_CONDITIONS = new Set([
Expand All @@ -34,9 +36,11 @@
*
* Order matters: cheapest checks first.
*/
export function preflight(input: {

Check warning on line 39 in src/agent/runtime/preflight.ts

View check run for this annotation

Repowise Bot / Repowise / code health

Signature changed: preflight

1 caller outside this PR call `preflight`: `tests/agent/runtime/preflight.test.ts::__module__`. They are not part of this change, so nothing in this diff proves they still compile or still pass the right arguments.
agent: Agent;
character: Character | NPC | null;
model?: string;
reasoningEffort?: ReasoningEffort | null;
}): PreflightResult {
const { agent, character } = input;

Expand All @@ -62,6 +66,19 @@
};
}

if (
agent.budgetTokens !== null
&& input.model
&& isReasoningModel(input.model)
&& agent.budgetTokens - agent.tokensUsed < reasoningCompletionFloor(input.reasoningEffort)
) {
return {
skipped: true,
status: 'budget_exhausted',
reason: `budget_exhausted (remaining ${agent.budgetTokens - agent.tokensUsed} tokens cannot fund the reasoning completion floor)`
};
}

// 4. Character is incapacitated — no point burning tokens.
if (!character) {
return { skipped: true, status: 'incapable', reason: 'character_not_found' };
Expand Down
87 changes: 80 additions & 7 deletions src/server/consolidated/inventory-manage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import { z } from 'zod';
import { createActionRouter, ActionDefinition, McpResponse } from '../../utils/action-router.js';
import type { InventoryRepository } from '../../storage/repos/inventory.repo.js';
import { CustomEffectsRepository } from '../../storage/repos/custom-effects.repo.js';
import { INVENTORY_LIMITS } from '../../schema/inventory.js';
import { getDomainServices } from '../domain-services.js';
import { SessionContext } from '../types.js';
import { RichFormatter } from '../utils/formatter.js';
import { getLightSourceProfile } from '../../services/light-source.service.js';

// ═══════════════════════════════════════════════════════════════════════════
// CONSTANTS
Expand All @@ -25,9 +27,11 @@
function ensureDb() {
const services = getDomainServices();
return {
db: services.db,
itemRepo: services.item,
inventoryRepo: services.inventory,
charRepo: services.character
charRepo: services.character,
effectsRepo: new CustomEffectsRepository(services.db),
};
}

Expand Down Expand Up @@ -313,67 +317,126 @@

use: {
schema: UseSchema,
handler: async (params: z.infer<typeof UseSchema>) => {
const { inventoryRepo, itemRepo, charRepo } = ensureDb();
const { db, inventoryRepo, itemRepo, charRepo, effectsRepo } = ensureDb();

const item = itemRepo.findById(params.itemId);
if (!item) {
throw new Error(`Item not found: ${params.itemId}`);
}

if ( 10BC8 item.type !== 'consumable') {
throw new Error(`Item "${item.name}" is not a consumable (type: ${item.type})`);
const lightSource = getLightSourceProfile(item);
if (item.type !== 'consumable' && !lightSource) {
throw new Error(`Item "${item.name}" is not a consumable or recognized light source (type: ${item.type})`);
}

const inventory = inventoryRepo.getInventory(params.characterId);
const hasItem = inventory.items.some((i: { itemId: string; quantity: number }) =>
i.itemId === params.itemId && i.quantity > 0
);
if (!hasItem) {
throw new Error(`Character does not have item "${item.name}"`);
}

if (lightSource) {
const properties = item.properties ?? {};
const open5e = properties.open5e && typeof properties.open5e === 'object'
? properties.open5e as Record<string, unknown>
: undefined;
const lightResult = db.transaction(() => {
if (lightSource.consumesItem && !inventoryRepo.removeItem(params.characterId, params.itemId, 1)) {
throw new Error(`Failed to use light source`);
}

const effect = effectsRepo.apply({
target_id: params.characterId,
target_type: 'character',
name: `Light source: ${item.name}`,
description: `${item.name} is lit and provides ${lightSource.brightRadiusFeet} ft bright light plus ${lightSource.dimRadiusFeet} ft dim light${lightSource.shape === 'cone' ? ' in a cone' : ''}.`,
source: {
type: 'natural',
entity_id: item.id,
entity_name: item.name,
},
category: 'neutral',
power_level: 1,
mechanics: [{
type: 'sense_granted',
value: `${lightSource.shape}:${lightSource.brightRadiusFeet}ft bright/${lightSource.dimRadiusFeet}ft dim`,
}],
duration: { type: 'minutes', value: lightSource.durationMinutes },
triggers: [],
removal_conditions: [{ type: 'duration_expires' }],
stackable: false,
max_stacks: 1,
});

return { effect, consumed: lightSource.consumesItem };
})();

return {
success: true,
actionType: 'use',
itemName: item.name,
characterId: params.characterId,
effect: 'Light source lit',
lightSource: {
...lightSource,
active: true,
effectId: lightResult.effect.id,
expiresAt: lightResult.effect.expires_at,
consumed: lightResult.consumed,
provenance: {
itemId: item.id,
itemName: item.name,
open5e: open5e ?? null,
},
},
message: `${lightResult.consumed ? 'Consumed and lit' : 'Lit'} ${item.name}; the light is authoritative for ${lightSource.durationMinutes} minutes`,
};
}

const properties = item.properties ?? {};
let healingValue: unknown = properties.healing ?? properties.healingDice ?? properties.heal;
const effect = properties.effect || properties.effects || 'No defined effect';
if (healingValue === undefined && typeof effect === 'string' && /heal|restore|regain/i.test(effect)) {
healingValue = effect;
}
const healing = rollHealing(healingValue);
const targetId = params.targetId || params.characterId;
const target = healing ? charRepo.findById(targetId) : null;
if (healing && !target) {
throw new Error(`Healing target not found: ${targetId}`);
}

const removed = inventoryRepo.removeItem(params.characterId, params.itemId, 1);
if (!removed) {
throw new Error(`Failed to consume item`);
}

const hpBefore = target?.hp;
const hpAfter = target && healing
? Math.min(target.maxHp, target.hp + healing.amount)
: undefined;
if (target && hpAfter !== hpBefore) {
charRepo.update(target.id, { hp: hpAfter } as any);
}

return {
success: true,
actionType: 'use',
itemName: item.name,
characterId: params.characterId,
targetId,
effect,
healing: healing?.amount,
healingNotation: healing?.notation,
healingRolls: healing?.rolls,
hpBefore,
hpAfter,
message: `Used ${item.name}`
};
},

Check warning on line 439 in src/server/consolidated/inventory-manage.ts

View check run for this annotation

Repowise Bot / Repowise / code health

Introduced: brain method

Brain Method: <anonymous@320> is 109 lines, CCN 27, in a file imported by 4 others
aliases: ['consume', 'apply', 'activate']
},

Expand Down Expand Up @@ -534,10 +597,12 @@
3. equip - Slot weapons/armor (updates AC automatically)

🔄 COMMON ACTIONS:
- transfer: Move items between characters
- use: Consume potions/scrolls (removes item, shows effect)
- transfer: Move items between characters atomically (use this for a player-to-NPC handoff)
- use: Consume potions/scrolls or light a torch/lantern (persists duration and provenance)
- get_detailed: Show weight, capacity, and item details

IMPORTANT: give is a world/DM grant to one character and does not remove an item from another character. For a handoff, always use transfer with fromCharacterId and toCharacterId.

⚔️ EQUIPMENT SLOTS:
mainhand, offhand, armor, head, feet, accessory

Expand All @@ -560,96 +625,104 @@
// HANDLER
// ═══════════════════════════════════════════════════════════════════════════

export async function handleInventoryManage(args: unknown, _ctx: SessionContext): Promise<McpResponse> {
const response = await router(args as Record<string, unknown>);

// Wrap response with ASCII formatting
try {
const parsed = JSON.parse(response.content[0].text);
let output = '';

if (parsed.error) {
output = RichFormatter.header('Inventory Error', '❌');
output += RichFormatter.alert(parsed.message || 'Unknown error', 'error');
if (parsed.suggestions) {
output += RichFormatter.section('Did you mean?');
parsed.suggestions.forEach((s: { value: string; similarity: number }) => {
output += ` • ${s.value} (${s.similarity}% match)\n`;
});
}
if (parsed.validActions) {
output += RichFormatter.section('Valid Actions');
output += RichFormatter.list(parsed.validActions);
}
} else if (parsed.actionType === 'give' || parsed.actionType === 'remove') {
output = RichFormatter.header(parsed.actionType === 'give' ? 'Item Added' : 'Item Removed', parsed.actionType === 'give' ? '➕' : '➖');
output += RichFormatter.keyValue({
'Item': parsed.itemName,
'Quantity': parsed.quantity,
'Character': parsed.characterId,
});
output += RichFormatter.success(parsed.message);
} else if (parsed.actionType === 'transfer') {
output = RichFormatter.header('Item Transferred', '🔀');
output += RichFormatter.keyValue({
'Item': parsed.itemName,
'Quantity': parsed.quantity,
'From': parsed.fromCharacterId,
'To': parsed.toCharacterId,
});
output += RichFormatter.success(parsed.message);
} else if (parsed.actionType === 'use') {
output = RichFormatter.header('Item Used', '✨');
output = RichFormatter.header(parsed.lightSource ? 'Light Source Lit' : 'Item Used', parsed.lightSource ? '🔥' : '✨');
output += RichFormatter.keyValue({
'Item': parsed.itemName,
'Target': parsed.targetId,
});
output += RichFormatter.section('Effect');
output += `${parsed.effect}\n`;
if (parsed.lightSource) {
output += RichFormatter.keyValue({
'Bright': `${parsed.lightSource.brightRadiusFeet} ft`,
'Dim': `${parsed.lightSource.dimRadiusFeet} ft`,
'Duration': `${parsed.lightSource.durationMinutes} minutes`,
'Effect ID': parsed.lightSource.effectId,
});
}
output += RichFormatter.success(parsed.message);
} else if (parsed.actionType === 'equip' || parsed.actionType === 'unequip') {
output = RichFormatter.header(parsed.actionType === 'equip' ? 'Item Equipped' : 'Item Unequipped', parsed.actionType === 'equip' ? '⚔️' : '📦');
output += RichFormatter.keyValue({
'Item': parsed.itemName,
'Character': parsed.characterId,
...(parsed.slot && { 'Slot': parsed.slot }),
});
if (parsed.acChange) {
output += RichFormatter.alert(parsed.acChange, 'info');
}
output += RichFormatter.success(parsed.message);
} else if (parsed.actionType === 'get' || parsed.actionType === 'get_detailed') {
output = RichFormatter.header('Inventory', '🎒');
output += RichFormatter.keyValue({
'Character': parsed.characterId,
...(parsed.totalWeight !== undefined && {
'Weight': `${parsed.totalWeight}/${parsed.capacity} lbs`
}),
...(parsed.gold !== undefined && { 'Gold': parsed.gold }),
'Items': parsed.itemCount || 0
});
if (parsed.inventory?.length) {
output += RichFormatter.inventory(parsed.inventory.map((i: { item?: { name: string }; itemId: string; quantity: number; equipped: boolean; slot?: string }) => ({
name: i.item?.name || i.itemId,
quantity: i.quantity,
equipped: i.equipped,
slot: i.slot,
})));
} else {
output += '*Inventory is empty*\n';
}
} else {
// Fallback
output = RichFormatter.header('Inventory Operation', '🎒');
output += JSON.stringify(parsed, null, 2) + '\n';
}

// Embed JSON for programmatic access
output += RichFormatter.embedJson(parsed, 'INVENTORY_MANAGE');

return { content: [{ type: 'text', text: output }] };
} catch {
// If JSON parsing fails, return original response
return response;
}
}

Check warning on line 728 in src/server/consolidated/inventory-manage.ts

View check run for this annotation

Repowise Bot / Repowise / code health

Introduced: brain method

Brain Method: handleInventoryManage is 93 lines, CCN 28, in a file imported by 4 others
17 changes: 17 additions & 0 deletions src/server/consolidated/quest-manage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,18 @@ async function handleCreate(args: z.infer<typeof CreateSchema>): Promise<object>
questId: quest.id,
name: quest.name,
objectiveCount: objectives.length,
// Return the generated IDs with the create receipt. Subsequent
// update/complete calls require the exact objective UUID; callers
// must never derive one from the quest ID or array position.
objectives: objectives.map(objective => ({
id: objective.id,
description: objective.description,
type: objective.type,
target: objective.target,
current: objective.current,
required: objective.required,
completed: objective.completed,
})),
message: `Created quest "${quest.name}" with ${objectives.length} objectives`
};
}
Expand Down Expand Up @@ -521,6 +533,11 @@ Aliases: new→create, accept→assign, progress→update_objective, finish→co
5. complete - Turn in quest for rewards
6. get_log - View character's quest journal

IMPORTANT: create returns the exact questId and objective IDs. Use those IDs
for update_objective and complete_objective; never derive an objective ID from
the quest ID, objective name, or array position. If an ID is unavailable, use
get or get_log first.

🎯 OBJECTIVE TYPES (for create):
Each objective requires a "type" field. Valid values:
- kill: defeat enemies
Expand Down
Loading
Loading
0