返回 CodeWhale
pet-engine.ts
根目录 / pet / src / core / pet-engine.ts
1 import { PET_MAX_SECONDS } from './pet-sim.js';
2 import type { Category, WhaleEvent } from './model.js';
3 import { compilePetTelemetry, PET_BIN_MS, type PetBucket } from './pet-telemetry.js';
4
5 // Engine emits a liveness pulse every 10 seconds for a running operation.
6 // Keep a small scheduling margin so one delayed pulse does not erase a valid
7 // long operation from the owner projection; after that, it becomes generic.
8 // The physics tape keeps its own, shorter coverage rule (see `pulse`).
9 export const ENGINE_OWNER_STALE_MS = 12_000;
10 export type OwnerActivityKind = 'reading' | 'editing' | 'searching' | 'testing' | 'executing'
11 | 'browsing' | 'computer' | 'memory' | 'tool' | 'thinking' | 'responding' | 'delegating';
12 export type OwnerPresence = 'unknown' | 'working' | 'needs_you' | 'done' | 'idle';
13 export type OwnerFreshness = 'missing' | 'fresh' | 'stale';
14 export type OwnerTurnOutcome = 'completed' | 'interrupted' | 'failed';
15 export type OwnerOperationOutcome = 'succeeded' | 'failed' | 'cancelled' | 'denied';
16
17 export interface EngineOwnerProjection {
18 schemaVersion: 1;
19 /** Added by the existing owner after selecting its session source. */
20 sessionId: string | null;
21 /** Added by the existing owner; monotonic for this session source. */
22 cursor: number;
23 observed: boolean;
24 freshness: OwnerFreshness;
25 authoritativePresence: OwnerPresence;
26 activityKind: OwnerActivityKind | null;
27 actionId?: string;
28 observedAtMs: number | null;
29 parallelAgentCount: number;
30 activeSpans: { activityKind: OwnerActivityKind; actionId?: string; startedAtMs: number }[];
31 turnId: string | null;
32 turnOutcome: OwnerTurnOutcome | null;
33 doneEffectId: string | null;
34 failedToolAge: { activityKind: OwnerActivityKind; actionId?: string; ageMs: number } | null;
35 }
36
37 type SpanGroup = 'operation' | 'agent' | 'thinking' | 'responding';
38 interface ActiveSpan {
39 key: string;
40 activityKind: OwnerActivityKind;
41 actionId?: string;
42 startedAtMs: number;
43 event: WhaleEvent;
44 group: SpanGroup;
45 }
46 interface FailedTool {
47 activityKind: OwnerActivityKind;
48 actionId?: string;
49 failedAtMs: number;
50 }
51
52 const ACTIVITY_KINDS: readonly OwnerActivityKind[] = [
53 'reading', 'editing', 'searching', 'testing', 'executing', 'browsing', 'computer',
54 'memory', 'tool', 'thinking', 'responding', 'delegating',
55 ];
56 const TURN_OUTCOMES: readonly OwnerTurnOutcome[] = ['completed', 'interrupted', 'failed'];
57 const OPERATION_OUTCOMES: readonly OwnerOperationOutcome[] = ['succeeded', 'failed', 'cancelled', 'denied'];
58 const APPROVAL_OUTCOMES = ['approved', 'denied', 'cancelled'] as const;
59
60 function categoryFor(kind: OwnerActivityKind): Category {
61 switch (kind) {
62 case 'reading': case 'editing': case 'searching': return 'filesystem';
63 case 'testing': case 'executing': return 'code';
64 case 'browsing': return 'browser';
65 case 'computer': case 'tool': return 'tool';
66 case 'memory': return 'memory';
67 case 'thinking': return 'reasoning';
68 case 'responding': return 'communication';
69 case 'delegating': return 'agent';
70 }
71 }
72
73 /** Read-only reducer for the Engine owner's typed metadata. It keeps using the
74 * existing pet telemetry tape and physics owner; it neither recognizes tool
75 * names from content nor accepts transcript text, arguments, commands, or results. */
76 export class PetEngineTelemetry {
77 private events: WhaleEvent[] = [];
78 private active = new Map<string, ActiveSpan>();
79 private waiting: WhaleEvent | undefined;
80 private sequence = 0;
81 private lastTime = 0;
82 private lastObservedAt: number | undefined;
83 private turnId: string | undefined;
84 private turnOutcome: OwnerTurnOutcome | undefined;
85 private terminalAt: number | undefined;
86 private lastFailedTool: FailedTool | undefined;
87 private completedSpans = new Set<string>();
88 private completedTurns = new Set<string>();
89
90 /** Ephemeral safe read projection. Span ids are retained only in this
91 * reducer to correlate trusted lifecycle events and never leave the owner. */
92 activity(at: number): EngineOwnerProjection {
93 const observed = this.lastObservedAt !== undefined;
94 const freshness: OwnerFreshness = !observed ? 'missing'
95 : at - this.lastObservedAt! <= ENGINE_OWNER_STALE_MS ? 'fresh' : 'stale';
96 const fresh = freshness === 'fresh';
97 const active = fresh
98 ? [...this.active.values()]
99 .filter(span => at >= span.startedAtMs && at - span.event.endTime <= ENGINE_OWNER_STALE_MS)
100 // The parent's own work leads; delegated agents are counted in
101 // `parallelAgentCount` and only lead when nothing else is active.
102 .sort((a, b) => Number(a.group === 'agent') - Number(b.group === 'agent')
103 || b.startedAtMs - a.startedAtMs || a.key.localeCompare(b.key))
104 : [];
105 const agents = active.filter(span => span.group === 'agent').length;
106 const terminalFresh = fresh && this.terminalAt !== undefined
107 && at >= this.terminalAt && at - this.terminalAt <= ENGINE_OWNER_STALE_MS;
108 let authoritativePresence: OwnerPresence = 'unknown';
109 if (fresh) {
110 if (this.waiting) authoritativePresence = 'needs_you';
111 else if (terminalFresh && this.turnOutcome === 'completed' && this.turnId) authoritativePresence = 'done';
112 else if (terminalFresh) authoritativePresence = 'idle';
113 else if (active.length > 0 || this.turnId) authoritativePresence = 'working';
114 }
115 const activityKind = fresh && authoritativePresence !== 'needs_you'
116 && authoritativePresence !== 'done' && authoritativePresence !== 'idle'
117 ? active[0]?.activityKind
118 ?? (this.lastFailedTool && at >= this.lastFailedTool.failedAtMs
119 && at - this.lastFailedTool.failedAtMs <= ENGINE_OWNER_STALE_MS
120 ? this.lastFailedTool.activityKind : null)
121 : null;
122 const failedAge = fresh && this.lastFailedTool
123 && at >= this.lastFailedTool.failedAtMs
124 && at - this.lastFailedTool.failedAtMs <= ENGINE_OWNER_STALE_MS
125 ? { activityKind: this.lastFailedTool.activityKind,
126 ...(this.lastFailedTool.actionId ? { actionId: this.lastFailedTool.actionId } : {}),
127 ageMs: at - this.lastFailedTool.failedAtMs }
128 : null;
129 const actionId = activityKind ? (active.length ? active[0].actionId : failedAge?.actionId) : undefined;
130 const doneEffectId = authoritativePresence === 'done' && terminalFresh
131 && this.turnOutcome === 'completed' && this.turnId ? this.turnId : null;
132
133 return {
134 schemaVersion: 1,
135 sessionId: null,
136 cursor: 0,
137 observed,
138 freshness,
139 authoritativePresence,
140 activityKind: activityKind ?? null,
141 ...(actionId ? { actionId } : {}),
142 observedAtMs: this.lastObservedAt ?? null,
143 parallelAgentCount: fresh ? agents : 0,
144 activeSpans: active.slice(0, 4).map(span => ({
145 activityKind: span.activityKind,
146 ...(span.actionId ? { actionId: span.actionId } : {}),
147 startedAtMs: span.startedAtMs,
148 })),
149 turnId: this.turnId ?? null,
150 turnOutcome: this.turnOutcome ?? null,
151 doneEffectId,
152 failedToolAge: failedAge,
153 };
154 }
155
156 private add(name: string, category: Category, at: number, agentId = 'parent', continuation = false): WhaleEvent {
157 if (this.events.length >= 8192) throw new Error('Pet Engine observation window is full.');
158 const event: WhaleEvent = {
159 schemaVersion: 1,
160 id: `engine:${this.sequence++}`,
161 traceId: 'foreground',
162 startTime: at,
163 endTime: at,
164 name,
165 category,
166 agentId,
167 status: 'running',
168 attributes: continuation ? { 'whalesong.continuation': true } : {},
169 };
170 this.events.push(event);
171 return event;
172 }
173
174 private start(key: string, kind: OwnerActivityKind, group: SpanGroup, at: number, agentId = 'parent', actionId?: string): void {
175 if (this.active.has(key)) return;
176 if (this.active.size >= 256) throw new Error('Too many active Engine pet spans.');
177 const event = this.add(group === 'agent' ? 'agent' : group === 'thinking' ? 'thinking'
178 : group === 'responding' ? 'assistant_message' : 'operation', categoryFor(kind), at, agentId);
179 this.active.set(key, { key, activityKind: kind, actionId, startedAtMs: at, event, group });
180 }
181
182 private pulse(key: string, at: number): void {
183 const span = this.active.get(key);
184 if (!span) return;
185 // A resumed stream does not assert tape coverage across its silent
186 // interval; the span itself (and its start) stays active.
187 if (at - span.event.endTime > PET_BIN_MS * 2) {
188 const event = this.add(span.event.name, span.event.category, at, span.event.agentId, true);
189 this.active.set(key, { ...span, event });
190 } else {
191 span.event.endTime = at;
192 }
193 }
194
195 private finish(key: string, at: number, status: 'success' | 'unknown' = 'success'): ActiveSpan | undefined {
196 if (!this.active.has(key)) return undefined;
197 this.pulse(key, at);
198 const span = this.active.get(key);
199 if (!span) return undefined;
200 span.event.endTime = at;
201 span.event.status = status;
202 this.active.delete(key);
203 return span;
204 }
205
206 private addOnce(set: Set<string>, id: string, maximum: number): boolean {
207 if (set.has(id)) return false;
208 set.add(id);
209 while (set.size > maximum) set.delete(set.values().next().value as string);
210 return true;
211 }
212
213 /** Transactional batch copy; validation errors cannot accept half a batch. */
214 clone(): PetEngineTelemetry {
215 const next = new PetEngineTelemetry();
216 const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
217 next.events = copy(this.events);
218 const spans = new Map(next.events.map(event => [event.id, event]));
219 next.active = new Map(Array.from(this.active, ([key, span]) => [key, {
220 ...span,
221 event: spans.get(span.event.id) ?? copy(span.event),
222 }]));
223 next.waiting = this.waiting ? spans.get(this.waiting.id) ?? copy(this.waiting) : undefined;
224 next.sequence = this.sequence;
225 next.lastTime = this.lastTime;
226 next.lastObservedAt = this.lastObservedAt;
227 next.turnId = this.turnId;
228 next.turnOutcome = this.turnOutcome;
229 next.terminalAt = this.terminalAt;
230 next.lastFailedTool = this.lastFailedTool ? { ...this.lastFailedTool } : undefined;
231 next.completedSpans = new Set(this.completedSpans);
232 next.completedTurns = new Set(this.completedTurns);
233 return next;
234 }
235
236 /** Mutates in place: clock, freshness and the event window change before
237 * type-specific fields are checked. Callers that continue after a throw must
238 * observe on a clone() and swap it in on success, as the dot whale does. */
239 observe(value: unknown, at: number): void {
240 if (!Number.isFinite(at) || at < this.lastTime || at > PET_MAX_SECONDS * 1000)
241 throw new Error('Invalid Engine pet clock.');
242 if (!value || typeof value !== 'object' || Array.isArray(value))
243 throw new Error('Invalid Engine pet metadata.');
244 const event = value as Record<string, unknown>;
245 const allowed = ['event', 'index', 'channel', 'span_id', 'activity_kind', 'action_id', 'outcome', 'id', 'worker_status', 'turn_id', 'turn_outcome'];
246 const stringFields = ['action_id', 'event', 'span_id', 'id', 'worker_status', 'turn_id', 'turn_outcome'];
247 if (Object.keys(event).some(key => !allowed.includes(key)) || typeof event.event !== 'string'
248 || Object.values(event).some(v => typeof v === 'string' && v.length > 256)
249 || stringFields.some(key => event[key] !== undefined && typeof event[key] !== 'string')
250 || event.action_id !== undefined && (typeof event.action_id !== 'string' || !event.action_id
251 || /[\u0000-\u001f\u007f-\u009f]/.test(event.action_id)
252 || [...event.action_id].reduce((bytes, char) => {
253 const cp = char.codePointAt(0)!;
254 return bytes + (cp <= 0x7f ? 1 : cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4);
255 }, 0) > 256)
256 || event.channel !== undefined && !['text', 'reasoning'].includes(event.channel as string)
257 || event.activity_kind !== undefined && !ACTIVITY_KINDS.includes(event.activity_kind as OwnerActivityKind)
258 || event.outcome !== undefined && (typeof event.outcome !== 'string'
259 || (event.event === 'approval_resolved'
260 ? !APPROVAL_OUTCOMES.includes(event.outcome as typeof APPROVAL_OUTCOMES[number])
261 : event.event === 'operation_activity_completed'
262 ? !OPERATION_OUTCOMES.includes(event.outcome as OwnerOperationOutcome)
263 : true))
264 || event.turn_outcome !== undefined && !TURN_OUTCOMES.includes(event.turn_outcome as OwnerTurnOutcome)
265 || event.index !== undefined && (!Number.isSafeInteger(event.index) || (event.index as number) < 0))
266 throw new Error('Invalid Engine pet metadata fields.');
267
268 this.lastTime = at;
269 this.lastObservedAt = at;
270 this.events = this.events.filter(item => item.endTime >= at - 12_800);
271 const required = (key: string): string => {
272 const value = event[key];
273 if (typeof value !== 'string' || !value) throw new Error(`Missing Engine ${key}.`);
274 return value;
275 };
276 const index = (): string => {
277 if (!Number.isSafeInteger(event.index)) throw new Error('Missing Engine index.');
278 return String(event.index);
279 };
280 const activityKind = (): OwnerActivityKind => {
281 if (!ACTIVITY_KINDS.includes(event.activity_kind as OwnerActivityKind))
282 throw new Error('Missing Engine activity kind.');
283 return event.activity_kind as OwnerActivityKind;
284 };
285 const startMessage = (key: string, kind: OwnerActivityKind, group: SpanGroup): void => {
286 this.start(key, kind, group, at);
287 this.waiting = undefined;
288 };
289
290 switch (event.event) {
291 case 'turn_started': {
292 const id = required('turn_id');
293 if (this.turnId !== id) {
294 this.active.clear();
295 this.waiting = undefined;
296 this.lastFailedTool = undefined;
297 this.turnId = id;
298 this.turnOutcome = undefined;
299 this.terminalAt = undefined;
300 }
301 break;
302 }
303 case 'message_started': startMessage(`message:${index()}`, 'responding', 'responding'); break;
304 case 'thinking_started': startMessage(`thinking:${index()}`, 'thinking', 'thinking'); break;
305 case 'response_delta': {
306 const reasoning = event.channel === 'reasoning';
307 const key = `${reasoning ? 'thinking' : 'message'}:${index()}`;
308 if (!this.active.has(key)) this.start(key, reasoning ? 'thinking' : 'responding', reasoning ? 'thinking' : 'responding', at);
309 else this.pulse(key, at);
310 this.waiting = undefined;
311 break;
312 }
313 case 'message_complete': this.finish(`message:${index()}`, at); break;
314 case 'thinking_complete': this.finish(`thinking:${index()}`, at); break;
315 case 'operation_activity_started': {
316 const spanId = required('span_id');
317 const kind = activityKind();
318 if (!this.completedSpans.has(spanId)) this.start(`operation:${spanId}`, kind, 'operation', at, 'parent', event.action_id as string | undefined);
319 this.waiting = undefined;
320 break;
321 }
322 case 'operation_activity_completed': {
323 const spanId = required('span_id');
324 const kind = activityKind();
325 if (!OPERATION_OUTCOMES.includes(event.outcome as OwnerOperationOutcome))
326 throw new Error('Missing Engine operation outcome.');
327 const outcome = event.outcome as OwnerOperationOutcome;
328 // A failure is recorded once, as its own onset event below; marking
329 // the span `error` too would count it twice on the tape.
330 const completed = this.finish(`operation:${spanId}`, at,
331 outcome === 'succeeded' ? 'success' : 'unknown');
332 if (completed && this.addOnce(this.completedSpans, spanId, 4096)) {
333 if (outcome === 'failed') {
334 this.add('operation_failed', 'error', at).status = 'error';
335 this.lastFailedTool = { activityKind: kind, actionId: completed.actionId, failedAtMs: at };
336 }
337 if (outcome === 'denied' || outcome === 'cancelled') this.waiting = undefined;
338 }
339 break;
340 }
341 case 'tool_call_heartbeat':
342 for (const [key, span] of this.active) if (span.group === 'operation') this.pulse(key, at);
343 break;
344 case 'approval_resolved': {
345 required('id');
346 if (!APPROVAL_OUTCOMES.includes(event.outcome as typeof APPROVAL_OUTCOMES[number]))
347 throw new Error('Invalid Engine approval outcome.');
348 this.waiting = undefined;
349 break;
350 }
351 case 'agent_spawned': {
352 const id = required('id');
353 this.start(`agent:${id}`, 'delegating', 'agent', at, id);
354 break;
355 }
356 case 'agent_progress': {
357 const id = required('id');
358 const key = `agent:${id}`;
359 if (['completed', 'failed', 'cancelled', 'interrupted', 'budget_exhausted'].includes(event.worker_status as string)) {
360 this.finish(key, at);
361 break;
362 }
363 if (!this.active.has(key)) this.start(key, 'delegating', 'agent', at, id);
364 else this.pulse(key, at);
365 break;
366 }
367 case 'agent_complete': this.finish(`agent:${required('id')}`, at); break;
368 case 'approval_required': case 'user_input_required': {
369 required('id');
370 if (!this.waiting) {
371 this.waiting = this.add('human_request', 'human', at);
372 this.waiting.status = 'pending';
373 }
374 break;
375 }
376 case 'turn_complete': {
377 const outcome = event.turn_outcome;
378 if (!TURN_OUTCOMES.includes(outcome as OwnerTurnOutcome))
379 throw new Error('Missing Engine turn outcome.');
380 const id = typeof event.turn_id === 'string' && event.turn_id.length ? event.turn_id : undefined;
381 this.active.clear();
382 this.waiting = undefined;
383 this.turnId = id;
384 // An outcome belongs to a turn. `/purge`, an edit rejection or a
385 // session switch mid-turn completes with no turn id; recording the
386 // outcome alone would break the projection invariant the Rust
387 // contract checks (`turn_outcome` requires `turn_id`).
388 this.turnOutcome = id ? outcome as OwnerTurnOutcome : undefined;
389 this.terminalAt = at;
390 if (outcome === 'completed' && id && this.addOnce(this.completedTurns, id, 256))
391 this.add('turn_completed', 'communication', at).status = 'success';
392 break;
393 }
394 default: throw new Error('Unsupported Engine pet event.');
395 }
396 }
397
398 /** The typed shell may extend a request already witnessed in Engine events,
399 * but a mid-turn attach cannot invent a NeedsYou state. */
400 confirmWaiting(at: number, waiting: boolean): void {
401 if (!waiting) {
402 this.waiting = undefined;
403 return;
404 }
405 if (this.waiting && at >= this.waiting.endTime) {
406 this.waiting.endTime = at;
407 this.lastObservedAt = at;
408 this.lastTime = Math.max(this.lastTime, at);
409 }
410 }
411
412 bucket(sequence: number): PetBucket {
413 const end = (sequence + 1) * PET_BIN_MS;
414 const input = this.events.filter(event => event.startTime < end && event.endTime >= end - 12_400)
415 .map(event => ({ ...event, endTime: Math.min(event.endTime, end) }));
416 return compilePetTelemetry(input, end, sequence)[0];
417 }
418 }
419
419 lines TYPESCRIPT