Repository navigation
feat: make light sources authoritative #102
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
876d7a9
c00c608
4ad2413
1fa37a2
881f27a
22ef012
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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'; | ||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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 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 | ||
| }; | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.