Spaces:
Sleeping
Sleeping
File size: 16,311 Bytes
cf8cdd9 17a40e4 cf8cdd9 17a40e4 cf8cdd9 b76b644 fa0970b ecf16e0 bd956f0 ecf16e0 bd956f0 ecf16e0 b76b644 ecf16e0 cf8cdd9 fa0970b 2ead142 ecf16e0 b9537b4 cf8cdd9 b76b644 ecf16e0 fa0970b cf8cdd9 bd956f0 fa0970b ecf16e0 fa0970b 2ead142 ecf16e0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | // Minimal typed client for the AI War Gaming FastAPI backend.
const BASE = (import.meta as any).env?.VITE_API_BASE ?? '/api';
// Trial password gate: backend may require an X-Trial-Password header.
// We cache the password in localStorage and re-prompt on a 401.
// Local dev has no gate so this is a no-op there.
const PASSWORD_KEY = 'wargame_trial_password';
function getPassword(): string | null {
try { return localStorage.getItem(PASSWORD_KEY); } catch { return null; }
}
function setPassword(value: string | null): void {
try {
if (value === null) localStorage.removeItem(PASSWORD_KEY);
else localStorage.setItem(PASSWORD_KEY, value);
} catch { /* private mode etc. — swallow */ }
}
function promptForPassword(): string | null {
if (typeof window === 'undefined' || typeof window.prompt !== 'function') return null;
const value = window.prompt('Enter trial access password');
return value && value.length > 0 ? value : null;
}
async function doFetch(path: string, init: RequestInit | undefined, password: string | null): Promise<Response> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...((init?.headers as Record<string, string> | undefined) || {}),
};
if (password) headers['X-Trial-Password'] = password;
return fetch(`${BASE}${path}`, { ...init, headers });
}
async function req<T>(path: string, init?: RequestInit): Promise<T> {
let res = await doFetch(path, init, getPassword());
if (res.status === 401) {
setPassword(null);
const next = promptForPassword();
if (next) {
setPassword(next);
res = await doFetch(path, init, next);
}
}
if (!res.ok) {
const body = await res.text().catch(() => '');
throw Object.assign(new Error(`${res.status} ${res.statusText}: ${body}`), { status: res.status });
}
return res.status === 204 ? (undefined as any) : res.json();
}
export const api = {
health: () => req<{ status: string }>('/healthz'),
listScenarios: () => req<{ scenarios: Scenario[] }>('/scenarios'),
listGames: () => req<{ games: GameSummary[] }>('/games'),
listModels: () => req<ModelsResponse>('/models'),
listAgents: (scenario_id: string) =>
req<AgentsResponse>(`/scenarios/${scenario_id}/agents`),
createGame: (
scenario_id: string,
model?: string,
role_model_overrides?: Record<string, string>,
language?: 'en' | 'de',
) => {
const body: Record<string, unknown> = { scenario_id };
if (model) body.model = model;
if (role_model_overrides && Object.keys(role_model_overrides).length > 0) {
body.role_model_overrides = role_model_overrides;
}
// ---- i18n (round 6) ----
if (language) body.language = language;
return req<{ game_id: string; turn: number; briefing: Briefing }>(`/games`, {
method: 'POST',
body: JSON.stringify(body),
});
},
getState: (id: string) => req<StateResponse>(`/games/${id}/state`),
getBriefing: (id: string) => req<BriefingResponse>(`/games/${id}/briefing`),
recon: (id: string, agent_id: string, question: string) =>
req<ReconResponseEnvelope>(`/games/${id}/recon`, {
method: 'POST', body: JSON.stringify({ agent_id, question }),
}),
submitAction: (id: string, action: ActionRequest) =>
req<ActionAcceptedResponse>(`/games/${id}/actions`, {
method: 'POST', body: JSON.stringify(action),
}),
advance: (id: string) => req<AdvanceResponse>(`/games/${id}/advance`, { method: 'POST' }),
debrief: (id: string) => req<DebriefResponse>(`/games/${id}/debrief`),
metrics: (id: string) => req<MetricsTimelineResponse>(`/games/${id}/metrics/timeline`),
setupStart: (scenario_id: string, initial_message: string) =>
req<SetupSession>(`/scenarios/setup`, {
method: 'POST', body: JSON.stringify({ scenario_id, initial_message }),
}),
setupGet: (session_id: string) => req<SetupSession>(`/scenarios/setup/${session_id}`),
setupAnswer: (session_id: string, message: string) =>
req<SetupSession>(`/scenarios/setup/${session_id}/answer`, {
method: 'POST', body: JSON.stringify({ message }),
}),
setupCommit: (session_id: string, force = false) =>
req<ScaffoldResponse>(`/scenarios/setup/${session_id}/commit`, {
method: 'POST', body: JSON.stringify({ force }),
}),
fork: (game_id: string, from_turn: number) =>
req<ForkResponse>(`/games/${game_id}/fork`, {
method: 'POST', body: JSON.stringify({ from_turn }),
}),
orchestrate: (game_id: string, opts?: { branches?: number; turns?: number }) =>
req<OrchestrateAccepted>(`/games/${game_id}/orchestrate`, {
method: 'POST',
body: JSON.stringify({ branches: opts?.branches ?? 3, turns: opts?.turns ?? 1 }),
}),
orchestrateStatus: (game_id: string) =>
req<OrchestrateStatus>(`/games/${game_id}/orchestrate/status`),
orchestrateResult: (game_id: string) =>
req<ScenarioMap>(`/games/${game_id}/orchestrate/result`),
// Action Coach — conversational action input that drafts a 3-anchor
// ActionSubmission and submits it through the same engine path.
actionCoachStart: (game_id: string, initial_prose: string) =>
req<ActionCoachSession>(`/games/${game_id}/actions/coach`, {
method: 'POST',
body: JSON.stringify({ initial_prose }),
}),
actionCoachLoad: (game_id: string, session_id: string) =>
req<ActionCoachSession>(`/games/${game_id}/actions/coach/${session_id}`),
actionCoachAnswer: (game_id: string, session_id: string, message: string) =>
req<ActionCoachSession>(`/games/${game_id}/actions/coach/${session_id}/answer`, {
method: 'POST',
body: JSON.stringify({ message }),
}),
actionCoachCommit: (game_id: string, session_id: string) =>
req<ActionAcceptedResponse>(`/games/${game_id}/actions/coach/${session_id}/commit`, {
method: 'POST',
}),
// ---- forms (5b) ----
addConstraint: (game_id: string, body: HardConstraintInput) =>
req<HardConstraintListResponse>(`/games/${game_id}/constraints`, {
method: 'POST',
body: JSON.stringify(body),
}),
checkAction: (game_id: string, action: ActionRequest) =>
req<ConstraintCheckResponse>(`/games/${game_id}/check_action`, {
method: 'POST',
body: JSON.stringify(action),
}),
deleteConstraint: (game_id: string, constraint_id: string, force = false) =>
req<HardConstraintListResponse>(
`/games/${game_id}/constraints/${encodeURIComponent(constraint_id)}${force ? '?force=true' : ''}`,
{ method: 'DELETE' },
),
deleteDocument: (session_id: string, filename: string) =>
req<void>(
`/scenarios/setup/${session_id}/documents/${encodeURIComponent(filename)}`,
{ method: 'DELETE' },
),
listConstraints: (game_id: string) =>
req<HardConstraintListResponse>(`/games/${game_id}/constraints`),
listDocuments: (session_id: string) =>
req<DocumentListResponse>(`/scenarios/setup/${session_id}/documents`),
uploadDocument: (session_id: string, file: File) => {
const fd = new FormData();
fd.append('file', file);
// NOTE: don't set Content-Type — the browser fills in the multipart
// boundary. `req()` defaults to JSON, so we call fetch directly here.
return fetch(`${BASE}/scenarios/setup/${session_id}/documents`, {
method: 'POST',
body: fd,
}).then(async (res) => {
if (!res.ok) {
const body = await res.text().catch(() => '');
throw Object.assign(
new Error(`${res.status} ${res.statusText}: ${body}`),
{ status: res.status },
);
}
return res.json() as Promise<UploadedDocument>;
});
},
// ---- live (5b) ----
pauseGame: (id: string) =>
req<StateResponse>(`/games/${id}/pause`, { method: 'POST' }),
resumeGame: (id: string) =>
req<AdvanceResponse>(`/games/${id}/resume`, { method: 'POST' }),
// EventSource can't attach custom headers, so the trial password rides in
// a `?token=` query param instead. The backend middleware accepts either.
streamUrl: (id: string) => {
const pw = getPassword();
const qs = pw ? `?token=${encodeURIComponent(pw)}` : '';
return `${BASE}/games/${id}/stream${qs}`;
},
};
export type AnchorKind = 'prior_analogue' | 'stated_capability' | 'resource_committed';
export interface Anchor { kind: AnchorKind; detail: string }
export interface ActionRequest { intent: string; justification: string; anchors: Anchor[] }
export interface ActionAcceptedResponse { game_id: string; turn: number; action: any }
export interface Scenario { scenario_id: string; company_name: string; rival_name: string; industry: string; player_role: string; agent_count: number }
export interface GameSummary { id: string; scenario_id: string; turn: number; max_turns: number; status: 'active' | 'complete'; updated_at: string; llm_model?: string | null }
export interface ModelInfo { id: string; display_name: string; provider: string }
export interface ModelsResponse { models: ModelInfo[]; default: string; roles?: string[] }
export interface AgentInfo { id: string; label: string; kind: string; posture: string }
export interface AgentsResponse { scenario_id: string; agents: AgentInfo[] }
export interface BriefingSection { heading: string; body: string; fog_of_war?: string | null }
export interface DecisionPoint { title: string; context: string; example_actions: string[] }
export interface Briefing { turn: number; headline: string; exec_summary: string; sections: BriefingSection[]; decision_points: DecisionPoint[] }
export interface BriefingResponse { game_id: string; turn: number; briefing: Briefing; recon_budget_remaining: number }
export interface ReconResponseEnvelope { game_id: string; recon_budget_remaining: number; response: { answered_by: string; question: string; answer: string; reveals_to_rival: boolean } }
export interface AdvanceResponse { game_id: string; status: string; turn_resolved: number; next_turn?: number; briefing?: Briefing }
export interface DebriefResponse { game_id: string; status: string; markdown: string }
export interface MetricsTimelineResponse { game_id: string; points: { turn: number; metrics: { key: string; label: string; unit: string; value: number; delta: number }[] }[] }
export interface StateResponse { id: string; scenario_id: string; status: string; world: any; recon_budget_remaining: number; current_phase: string; turns: any[]; language?: 'en' | 'de' }
export interface SetupMessage { role: 'user' | 'setup_agent'; content: string; at: string }
export interface SetupSession {
session_id: string;
scenario_id: string;
status: 'gathering' | 'ready' | 'committed';
last_agent_message: string;
synthesized_brief: string | null;
committed_scenario_id: string | null;
messages: SetupMessage[];
doc_filenames?: string[];
}
export interface ScaffoldResponse {
scenario_id: string;
target_dir: string;
mode: 'blank' | 'generated';
summary: Scenario | null;
}
export interface ForkResponse {
game_id: string;
forked_from: string;
forked_at_turn: number;
turn: number;
briefing: Briefing;
}
export type OrchestratorStatus = 'pending' | 'running' | 'complete' | 'failed';
export interface StrategyVector {
id: string;
label: string;
description: string;
play_style_note: string;
likely_stumbles: string[];
priority_metrics: string[];
}
export interface OrchestrateAccepted { map_id: string; status: string }
export interface OrchestrateStatus {
map_id: string;
status: OrchestratorStatus;
branches_complete: number;
branches_total: number;
error: string | null;
}
export interface ScenarioMap {
id: string;
source_game_id: string;
scenario_id: string;
created_at: string;
updated_at: string;
vectors: StrategyVector[];
branches: Array<{
vector_id: string;
branch_game_id: string;
proxy_temperature: number;
narrative_after?: string;
skipped?: boolean;
skip_reason?: string | null;
turns_played?: number;
}>;
synthesis_markdown: string;
branches_requested: number;
turns_requested: number;
status: OrchestratorStatus;
branches_complete: number;
error: string | null;
}
// Action Coach — conversational action input.
export interface ActionDraft {
intent: string;
justification: string;
anchors: Anchor[];
}
export interface CoachMessage {
role: 'user' | 'coach';
content: string;
at: string;
}
export type ActionCoachStatus = 'gathering' | 'ready' | 'committed';
export interface ActionCoachSession {
session_id: string;
game_id: string;
turn: number;
status: ActionCoachStatus;
rounds_used: number;
last_coach_message: string;
synthesized_draft: ActionDraft | null;
committed: boolean;
messages: CoachMessage[];
}
// ---- forms (5b) ----
// Hard constraints + uploaded documents + check-action shapes (Round 4 backend).
export type ConstraintSeverity = 'hard' | 'soft';
export type ConstraintSource = 'scenario' | 'document' | 'manual';
export interface HardConstraint {
id: string;
description: string;
rationale: string;
test_question: string;
severity: ConstraintSeverity;
source: ConstraintSource;
source_ref?: string | null;
}
export interface HardConstraintInput {
description: string;
rationale: string;
test_question: string;
severity?: ConstraintSeverity;
source_ref?: string | null;
}
export interface HardConstraintListResponse {
game_id: string;
constraints: HardConstraint[];
}
export interface ConstraintViolation {
constraint_id: string;
constraint_description: string;
reason: string;
}
export interface ConstraintCheckResult {
passes: boolean;
violations: ConstraintViolation[];
}
export interface ConstraintCheckResponse {
game_id: string;
result: ConstraintCheckResult;
}
export interface UploadedDocument {
filename: string;
bytes_stored: number;
}
export interface DocumentListResponse {
session_id: string;
documents: UploadedDocument[];
}
// ---- live (5b) ----
// PhaseEvent — server-sent events that fire on the engine bus during an
// advance. Discriminated by `kind`. Wire format documented in CONTRACT.md.
export type PhaseEventKind =
| 'phase_started'
| 'phase_completed'
| 'deliberation_complete'
| 'critic_complete'
| 'premortem_complete'
| 'verdict_complete'
| 'evaluator_complete'
| 'world_updated'
| 'briefing_ready'
| 'usage_tick'
| 'paused'
| 'resumed'
| 'error';
export type VerdictOutcome =
| 'effect_major'
| 'effect_minor'
| 'no_effect'
| 'backfires';
interface PhaseEventBase {
game_id: string;
turn: number;
label: string;
at: string;
payload: Record<string, unknown> & { dropped?: number };
}
export type PhaseEvent =
| (PhaseEventBase & { kind: 'phase_started'; payload: { dropped?: number } })
| (PhaseEventBase & { kind: 'phase_completed'; payload: { dropped?: number } })
| (PhaseEventBase & {
kind: 'deliberation_complete';
payload: { agent_id: string; expects: string; fears: string; dropped?: number };
})
| (PhaseEventBase & {
kind: 'critic_complete';
payload: { count: number; issue_count: number; dropped?: number };
})
| (PhaseEventBase & {
kind: 'premortem_complete';
payload: { count: number; dropped?: number };
})
| (PhaseEventBase & {
kind: 'verdict_complete';
payload: {
actor: string;
plausibility: number;
outcome: VerdictOutcome;
dropped?: number;
};
})
| (PhaseEventBase & {
kind: 'evaluator_complete';
payload: { scored: number; dropped?: number };
})
| (PhaseEventBase & {
kind: 'world_updated';
payload: { media_tone: string; public_narrative: string; dropped?: number };
})
| (PhaseEventBase & {
kind: 'briefing_ready';
payload: { turn: number; dropped?: number };
})
| (PhaseEventBase & {
kind: 'usage_tick';
payload: {
cost_usd_so_far: number;
input_tokens_so_far: number;
output_tokens_so_far: number;
dropped?: number;
};
})
| (PhaseEventBase & {
kind: 'paused';
payload: { turn: number; dropped?: number };
})
| (PhaseEventBase & {
kind: 'resumed';
payload: { dropped?: number };
})
| (PhaseEventBase & {
kind: 'error';
payload: Record<string, unknown> & { dropped?: number };
});
|