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
16 changes: 14 additions & 2 deletions apps/game-api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import {
AgentProviderError,
OpenRouterModelCatalog,
OpenRouterAgentProvider,
OpenRouterSwarmPlanner,
TypeSafeJevReflexProvider,
type AgentProvider,
type ReflexProvider,
type SwarmPlanner,
} from '@hexzero/agent-runtime';
import {
archiveExperimentExportRequestSchema,
Expand Down Expand Up @@ -74,6 +78,8 @@ export { healthResponseSchema };
export interface AppOptions {
service?: SimulationService;
provider?: AgentProvider;
swarmPlanner?: SwarmPlanner;
reflexProvider?: ReflexProvider;
catalog?: Pick<OpenRouterModelCatalog, 'getCatalog'>;
geocoder?: Geocoder;
archiveExperimentExport?: (
Expand Down Expand Up @@ -134,6 +140,8 @@ export function createApp(options: AppOptions = {}) {
options.service ??
new SimulationService({
provider: options.provider ?? providerFromEnvironment(),
swarmPlanner: options.swarmPlanner ?? new OpenRouterSwarmPlanner(),
reflexProvider: options.reflexProvider ?? new TypeSafeJevReflexProvider(),
});
const catalog =
options.catalog ??
Expand Down Expand Up @@ -545,10 +553,14 @@ export function createApp(options: AppOptions = {}) {
try {
const response = await mutationPromise(context, 'tick', async () => {
const records = await service.executeNextTick();
const snapshot = service.getSnapshot();
return singleTickResponseSchema.parse({
snapshot: service.getSnapshot(),
tickNumber: records[0]!.tickNumber,
snapshot,
tickNumber: snapshot.tickNumber,
records,
...(snapshot.scenario.cognitionMode === 'zero-swarm-v1'
? { swarmTick: snapshot.swarmTicks?.at(-1) }
: {}),
});
});
return context.json(response);
Expand Down
39 changes: 28 additions & 11 deletions apps/game-api/src/experiment-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
type ProviderAttemptRecord,
type ProviderAttemptRetention,
type ExperimentAttemptAccounting,
type SwarmTickRecord,
} from '@hexzero/shared';

export interface ExperimentSource {
Expand All @@ -48,6 +49,7 @@ export interface ExperimentSource {
retentionLimit: number;
totalCompletedTurns: number;
turns: readonly AgentTurnRecord[];
swarmTicks?: readonly SwarmTickRecord[];
initialAgents: readonly Agent[];
currentAgents: readonly Agent[];
configurationEvents: readonly ExperimentConfigurationEvent[];
Expand Down Expand Up @@ -745,6 +747,18 @@ export function createExperimentExport(
requestedRangeExtendsBeyondRetention,
};
const include = inclusionsFor(request);
const exportedSwarmTicks: SwarmTickRecord[] | undefined =
source.scenario.cognitionMode === 'zero-swarm-v1' &&
request.agents.mode === 'all' &&
request.turns.mode === 'entire-retained'
? [...structuredClone(source.swarmTicks ?? [])]
: undefined;
const selectedTickNumbers = new Set([
...filtered
.map(({ tickNumber }) => tickNumber)
.filter((tick): tick is number => tick !== undefined),
...(exportedSwarmTicks ?? []).map(({ tickNumber }) => tickNumber),
]);
const selectedAgents = source.currentAgents
.filter(({ id }) => selectedSet.has(id))
.map((agent) =>
Expand Down Expand Up @@ -779,22 +793,24 @@ export function createExperimentExport(
matchingTurnCount: filtered.length,
...(source.schemaVersion === 10 || source.schemaVersion === 11
? {
matchingTickCount: new Set(
filtered.map(({ tickNumber }) => tickNumber).filter(Boolean),
).size,
matchingTickCount:
exportedSwarmTicks?.length ??
new Set(
filtered.map(({ tickNumber }) => tickNumber).filter(Boolean),
).size,
}
: {}),
...(exportedSwarmTicks
? { matchingSwarmTickCount: exportedSwarmTicks.length }
: {}),
matchingCommunicationCount: communications.length,
matchingControlChangeCount: controlChanges.length,
matchingDiplomacyEventCount: allianceEvents.length,
...(source.schemaVersion === 11
? { matchingProviderAttemptCount: providerAttempts.length }
: {}),
matchingSimulatedPlayerEventCount: source.simulatedPlayerEvents.filter(
(event) =>
new Set(
filtered.map(({ tickNumber }) => tickNumber).filter(Boolean),
).has(event.originatingTick),
(event) => selectedTickNumbers.has(event.originatingTick),
).length,
firstMatchingTurn: filtered[0]?.turnNumber,
lastMatchingTurn: filtered.at(-1)?.turnNumber,
Expand Down Expand Up @@ -857,10 +873,7 @@ export function createExperimentExport(
return [structuredClone(turn.worldActionResult.event)];
}),
...source.simulatedPlayerEvents.filter((event) => {
const selectedTicks = new Set(
filtered.map(({ tickNumber }) => tickNumber).filter(Boolean),
);
return selectedTicks.has(event.originatingTick);
return selectedTickNumbers.has(event.originatingTick);
}),
],
}
Expand All @@ -873,6 +886,7 @@ export function createExperimentExport(
: {}),
allianceEvents: structuredClone(allianceEvents),
turns: filtered.map((turn) => exportTurn(turn, request)),
...(exportedSwarmTicks ? { swarmTicks: exportedSwarmTicks } : {}),
...(source.schemaVersion === 10 || source.schemaVersion === 11
? { tickSummaries: summarizeTicks(filtered) }
: {}),
Expand Down Expand Up @@ -995,6 +1009,9 @@ export function createExperimentPreview(
...(document.selection.matchingTickCount === undefined
? {}
: { matchingTickCount: document.selection.matchingTickCount }),
...(document.selection.matchingSwarmTickCount === undefined
? {}
: { matchingSwarmTickCount: document.selection.matchingSwarmTickCount }),
matchingCommunicationCount: document.selection.matchingCommunicationCount,
matchingControlChangeCount: document.selection.matchingControlChangeCount,
matchingDiplomacyEventCount: document.selection.matchingDiplomacyEventCount,
Expand Down
2 changes: 1 addition & 1 deletion apps/game-api/src/reflex-execution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ describe('zero-swarm reflex execution seam', () => {
});
expect(snapshot.scenario.cognitionMode).toBe('zero-swarm-v1');
await expect(service.executeNextTick()).rejects.toThrow(
'Zero-swarm ticks require the Agent Zero planner',
'Zero-swarm execution requires a planner and reflex provider',
);
expect(service.getSnapshot().tickNumber).toBe(0);
});
Expand Down
17 changes: 14 additions & 3 deletions apps/game-api/src/reflex-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
type WorldState,
} from '@hexzero/world-engine';
import { AttemptAccounting } from './attempt-accounting';
import { geographicDirectionBetweenCells } from './geographic-direction';

export interface ReflexLocalHistory {
previousCell?: H3Cell;
Expand Down Expand Up @@ -88,7 +89,11 @@ function actionDescription(
: nextDistance > currentDistance
? 'This moves away from the assigned target.'
: 'This maintains the current target distance.';
return `Move into adjacent ${terrain}. ${progress}`;
const direction = geographicDirectionBetweenCells(
agent.currentCell,
action.targetCell,
);
return `Move ${direction} into adjacent ${terrain}. ${progress}`;
}

/** Compile only engine-legal actions from one frozen world state. */
Expand Down Expand Up @@ -185,6 +190,8 @@ export interface ReflexSelectionOptions {
signal?: AbortSignal;
deadlineAtMs?: number;
accounting?: AttemptAccounting;
/** First HTTP dispatch consumes a permit reserved for the whole tick. */
initialPermitReserved?: boolean;
intendedTickNumber?: number;
intendedTurnNumber?: number;
now?: () => string;
Expand Down Expand Up @@ -234,7 +241,7 @@ export async function chooseReflexWorldAction(
deadlineAtMs: options.deadlineAtMs,
beginAttempt: options.accounting
? (kind) => {
const permit = options.accounting!.startAdditional({
const details = {
agentId: compiled.observation.agentId,
intendedTurnNumber: options.intendedTurnNumber ?? 1,
...(options.intendedTickNumber
Expand All @@ -244,7 +251,11 @@ export async function chooseReflexWorldAction(
startedAt: now(),
modelId: model,
reasoningProfile: 'provider-default',
});
} as const;
const permit =
kind === 'initial' && options.initialPermitReserved
? options.accounting!.startReserved(details)
: options.accounting!.startAdditional(details);
if (permit === null) return null;
startedAttempts += 1;
return (completion) =>
Expand Down
Loading
Loading