-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstream.ts
More file actions
283 lines (258 loc) · 8.95 KB
/
Copy pathstream.ts
File metadata and controls
283 lines (258 loc) · 8.95 KB
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
/**
* Stream event envelope — Zod discriminated union covering every SSE
* event type emitted by `runSimulation`. Exported from `paracosm/schema`.
*
* Current 17 event types from
* [`SimEventPayloadMap`](../../runtime/orchestrator.ts) are formalized
* here using the published specialist, decision, and personality event
* names from the universal schema.
*
* `time: number` replaces the legacy `year: number` envelope field per
* F23's time-units rename. Both are optional on the envelope (some events
* fire before a turn has advanced to its final time).
*
* @module paracosm/schema/stream
*/
import { z } from 'zod';
import { ProviderErrorSchema } from './primitives.js';
// ---------------------------------------------------------------------------
// Per-event data schemas — formalize the 17 payload shapes
// ---------------------------------------------------------------------------
const TurnStartDataSchema = z.object({
summary: z.string().optional(),
title: z.string().optional(),
description: z.string().optional(),
crisis: z.string().optional(),
category: z.string().optional(),
births: z.number().optional(),
deaths: z.number().optional(),
metrics: z.record(z.string(), z.number()).optional(),
emergent: z.boolean().optional(),
turnSummary: z.string().optional(),
totalEvents: z.number().optional(),
pacing: z.unknown().optional(),
});
const EventStartDataSchema = z.object({
summary: z.string().optional(),
eventIndex: z.number().int().min(0),
totalEvents: z.number().int().min(0),
title: z.string(),
description: z.string().optional(),
category: z.string(),
emergent: z.boolean().optional(),
turnSummary: z.string().optional(),
pacing: z.unknown().optional(),
});
const SpecialistStartDataSchema = z.object({
summary: z.string().optional(),
department: z.string().min(1),
eventIndex: z.number().int().min(0),
});
const SpecialistDoneDataSchema = z.object({
summary: z.string().optional(),
department: z.string().min(1),
eventIndex: z.number().int().min(0),
citations: z.number().int().min(0),
citationList: z.array(z.object({
text: z.string(),
url: z.string(),
doi: z.string().optional(),
})),
risks: z.array(z.string()),
forgedTools: z.array(z.unknown()),
recommendedActions: z.array(z.string()).optional(),
/** Optional full detail payload — populated when scenario emits rich reports. */
deptSummary: z.string().optional(),
});
const ForgeAttemptDataSchema = z.object({
summary: z.string().optional(),
department: z.string().min(1),
name: z.string().min(1),
description: z.string().optional(),
mode: z.string().optional(),
approved: z.boolean(),
confidence: z.number().min(0).max(1),
inputFields: z.array(z.string()),
outputFields: z.array(z.string()),
errorReason: z.string().optional(),
timestamp: z.string(),
eventIndex: z.number().int().optional(),
});
const DecisionPendingDataSchema = z.object({
summary: z.string().optional(),
eventIndex: z.number().int().min(0),
});
const DecisionMadeDataSchema = z.object({
summary: z.string().optional(),
decision: z.string(),
rationale: z.string(),
reasoning: z.string(),
selectedPolicies: z.array(z.unknown()),
selectedOptionId: z.string().optional(),
eventIndex: z.number().int().min(0),
});
const OutcomeDataSchema = z.object({
summary: z.string().optional(),
outcome: z.string(),
category: z.string(),
emergent: z.boolean(),
systemDeltas: z.record(z.string(), z.number()),
eventIndex: z.number().int().min(0),
});
const PersonalityDriftDataSchema = z.object({
summary: z.string().optional(),
agents: z.record(z.string(), z.object({
name: z.string(),
hexaco: z.record(z.string(), z.number()),
})),
commander: z.unknown(),
});
const AgentReactionsDataSchema = z.object({
summary: z.string().optional(),
reactions: z.array(z.unknown()),
moodSummary: z.unknown().optional(),
});
const BulletinDataSchema = z.object({
summary: z.string().optional(),
posts: z.array(z.unknown()),
});
const TurnDoneDataSchema = z.object({
summary: z.string().optional(),
metrics: z.record(z.string(), z.number()),
/**
* Categorical statuses bag (world.statuses declarations). Emitted
* when the scenario declared any; omitted for Mars-shape scenarios
* that only have numeric metrics. Added in the 0.7.x worldSnapshot
* widening so dashboards can surface scenario-declared governance
* state, funding round, alignment, etc.
*/
statuses: z.record(z.string(), z.union([z.string(), z.boolean()])).optional(),
/**
* Environment bag (world.environment declarations): external
* conditions like market growth pct, radiation level, depth.
* Same emit rule as statuses.
*/
environment: z.record(z.string(), z.union([z.number(), z.string(), z.boolean()])).optional(),
toolsForged: z.number().int().min(0),
totalEvents: z.number().int().optional(),
deathCauses: z.record(z.string(), z.number()).optional(),
error: z.string().optional(),
});
const PromotionDataSchema = z.object({
summary: z.string().optional(),
agentId: z.string().min(1),
department: z.string().min(1),
role: z.string().min(1),
reason: z.string().optional(),
});
const SystemsSnapshotDataSchema = z.object({
summary: z.string().optional(),
agents: z.array(z.unknown()),
population: z.number(),
morale: z.number(),
foodReserve: z.number(),
births: z.number(),
deaths: z.number(),
});
const StreamProviderErrorDataSchema = ProviderErrorSchema.extend({
summary: z.string().optional(),
site: z.string().optional(),
});
const ValidationFallbackDataSchema = z.object({
summary: z.string().optional(),
site: z.string(),
schemaName: z.string().optional(),
rawTextPreview: z.string(),
error: z.string(),
});
const SimAbortedDataSchema = z.object({
summary: z.string().optional(),
reason: z.string(),
completedTurns: z.number().int().min(0),
metrics: z.record(z.string(), z.number()),
toolsForged: z.number().int().min(0),
});
// ---------------------------------------------------------------------------
// Envelope — common fields on every stream event
// ---------------------------------------------------------------------------
/**
* Build an envelope schema for a given event type + data schema.
*
* `time` replaces legacy `year` per F23. `turn` is 0-indexed turn number
* when applicable (some events fire before a turn advances). Both
* optional; some stream events fire outside a turn context
* (e.g., `provider_error` during setup).
*/
const envelope = <T extends z.ZodTypeAny>(type: string, data: T) =>
z.object({
type: z.literal(type),
leader: z.string(),
turn: z.number().int().optional(),
time: z.number().optional(),
data,
});
// ---------------------------------------------------------------------------
// StreamEvent — discriminated union of all 17 event types
// ---------------------------------------------------------------------------
/**
* Every SSE event emitted by `runSimulation` validates against this
* union. Consumers `switch` on `event.type` for full narrow-typed access
* to `event.data` fields.
*
* @example
* ```ts
* import { StreamEventSchema } from 'paracosm/schema';
*
* for await (const raw of sse) {
* const event = StreamEventSchema.parse(JSON.parse(raw));
* switch (event.type) {
* case 'outcome': console.log(event.data.systemDeltas); break;
* case 'decision_made': console.log(event.data.rationale); break;
* case 'provider_error': console.error(event.data.kind, event.data.message); break;
* }
* }
* ```
*/
export const StreamEventSchema = z.discriminatedUnion('type', [
envelope('turn_start', TurnStartDataSchema),
envelope('event_start', EventStartDataSchema),
envelope('specialist_start', SpecialistStartDataSchema),
envelope('specialist_done', SpecialistDoneDataSchema),
envelope('forge_attempt', ForgeAttemptDataSchema),
envelope('decision_pending', DecisionPendingDataSchema),
envelope('decision_made', DecisionMadeDataSchema),
envelope('outcome', OutcomeDataSchema),
envelope('personality_drift', PersonalityDriftDataSchema),
envelope('agent_reactions', AgentReactionsDataSchema),
envelope('bulletin', BulletinDataSchema),
envelope('turn_done', TurnDoneDataSchema),
envelope('promotion', PromotionDataSchema),
envelope('systems_snapshot', SystemsSnapshotDataSchema),
envelope('provider_error', StreamProviderErrorDataSchema),
envelope('validation_fallback', ValidationFallbackDataSchema),
envelope('sim_aborted', SimAbortedDataSchema),
]);
/**
* The set of valid `event.type` literals. Consumers can use this as a
* type guard against unknown event types.
*/
export const STREAM_EVENT_TYPES = [
'turn_start',
'event_start',
'specialist_start',
'specialist_done',
'forge_attempt',
'decision_pending',
'decision_made',
'outcome',
'personality_drift',
'agent_reactions',
'bulletin',
'turn_done',
'promotion',
'systems_snapshot',
'provider_error',
'validation_fallback',
'sim_aborted',
] as const;
export type StreamEventType = (typeof STREAM_EVENT_TYPES)[number];