forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruns.ts
More file actions
1584 lines (1524 loc) · 67.4 KB
/
Copy pathruns.ts
File metadata and controls
1584 lines (1524 loc) · 67.4 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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-nocheck
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { todoSnapshotHasUnfinishedWork } from '@open-design/contracts';
import { normalizeMediaExecutionPolicyForRun } from '../media/policy.js';
import {
normalizeRunToolBundleForRun,
summarizeRunToolBundle,
} from '../run-tool-bundle.js';
import { createRunLifecycleTracer } from '../run-lifecycle-tracer.js';
import { projectWorkspaceProvenance } from '../workspace-contract.js';
import { OPEN_DESIGN_PLUGIN_ID } from '../mcp-observability.js';
import {
scanRunEventsForUsageAnalytics,
summarizeRunTimingAnalytics,
} from '../run-analytics-observability.js';
import {
interruptDurableRunAfterDaemonRestart,
RESTART_ERROR_CODE,
RESTART_ERROR_MESSAGE,
} from './run-restart-recovery.js';
export const TERMINAL_RUN_STATUSES = new Set(['succeeded', 'failed', 'canceled']);
const RUN_STATE_SCHEMA_VERSION = 1;
const DIAGNOSTIC_SOURCE = 'open-design-daemon';
function availableDiagnostic(value, definition, complete = true, source = DIAGNOSTIC_SOURCE) {
return {
state: 'available',
value,
evidence: 'computed',
source,
complete,
definition,
};
}
function missingDiagnostic(missingReason, source = DIAGNOSTIC_SOURCE, state = 'not_collected') {
return { state, source, missingReason };
}
function optionalDiagnostic(value, definition, complete = true, missingReason = 'upstream_did_not_emit_metric', source = DIAGNOSTIC_SOURCE) {
return value === undefined
? missingDiagnostic(missingReason, source, 'upstream_unavailable')
: availableDiagnostic(value, definition, complete, source);
}
function summarizeToolEvents(events, complete) {
const calls = new Map();
const byName = {};
for (const record of events) {
if (record?.event !== 'agent' || !record.data || typeof record.data !== 'object') continue;
const data = record.data;
if (data.type === 'tool_use' && typeof data.id === 'string') {
const name = typeof data.name === 'string' && data.name.trim() ? data.name.trim() : 'unknown';
const startedAt = typeof data.startedAt === 'number' && Number.isFinite(data.startedAt)
? data.startedAt
: record.timestamp;
calls.set(data.id, { name, startedAt, status: 'unknown' });
byName[name] = (byName[name] ?? 0) + 1;
} else if (data.type === 'tool_result' && typeof data.toolUseId === 'string') {
const call = calls.get(data.toolUseId);
if (!call) continue;
call.status = data.isError === true ? 'error' : 'ok';
if (
typeof record.timestamp === 'number' &&
typeof call.startedAt === 'number' &&
record.timestamp >= call.startedAt
) {
call.durationMs = record.timestamp - call.startedAt;
}
}
}
let succeeded = 0;
let failed = 0;
let unknown = 0;
let durationMs = 0;
for (const call of calls.values()) {
if (call.status === 'ok') succeeded += 1;
else if (call.status === 'error') failed += 1;
else unknown += 1;
if (typeof call.durationMs === 'number') durationMs += call.durationMs;
}
return { total: calls.size, succeeded, failed, unknown, durationMs, byName, complete };
}
function percentileNearestRank(values, percentile) {
if (!Array.isArray(values) || values.length === 0) return undefined;
const sorted = [...values].sort((a, b) => a - b);
const index = Math.max(0, Math.ceil(percentile * sorted.length) - 1);
return sorted[index];
}
function summarizeModelStepEvents(events) {
const steps = new Map();
let lifecycleObserved = false;
let retryCount = 0;
let fallbackOrdinal = 0;
for (const record of events) {
if (record?.event !== 'agent' || !record.data || typeof record.data !== 'object') continue;
const data = record.data;
if (data.type !== 'diagnostic') continue;
if (data.name === 'model_retry') {
retryCount += 1;
continue;
}
if (data.name !== 'model_step_lifecycle') continue;
lifecycleObserved = true;
const messageIndex = Number.isFinite(data.assistantMessageIndex)
? data.assistantMessageIndex
: 'unknown';
const stepIndex = Number.isFinite(data.stepIndex) ? data.stepIndex : undefined;
const key = stepIndex === undefined
? `fallback-${fallbackOrdinal += 1}`
: `${messageIndex}:${stepIndex}`;
const current = steps.get(key) ?? {
status: 'incomplete',
startedAtMs: undefined,
endedAtMs: undefined,
durationMs: undefined,
reasoningTokens: undefined,
};
if (data.phase === 'start') {
if (Number.isFinite(data.startedAtMs)) current.startedAtMs = data.startedAtMs;
} else if (data.phase === 'end') {
if (Number.isFinite(data.startedAtMs)) current.startedAtMs = data.startedAtMs;
if (Number.isFinite(data.endedAtMs)) current.endedAtMs = data.endedAtMs;
const usage = data.usage && typeof data.usage === 'object' ? data.usage : undefined;
if (Number.isFinite(usage?.reasoningTokens) && usage.reasoningTokens >= 0) {
current.reasoningTokens = usage.reasoningTokens;
}
const preciseDurationBoundary = data.timingEvidence !== 'first_output_fallback';
if (preciseDurationBoundary && Number.isFinite(data.durationMs) && data.durationMs >= 0) {
current.durationMs = data.durationMs;
} else if (
preciseDurationBoundary &&
Number.isFinite(current.startedAtMs) &&
Number.isFinite(current.endedAtMs) &&
current.endedAtMs >= current.startedAtMs
) {
current.durationMs = current.endedAtMs - current.startedAtMs;
}
current.status =
data.status === 'failed' || data.status === 'cancelled' || data.status === 'completed'
? data.status
: 'incomplete';
}
steps.set(key, current);
}
const durations = [];
let completed = 0;
let failed = 0;
let cancelled = 0;
let incomplete = 0;
let reasoningTokens = 0;
let reasoningTokenSampleCount = 0;
for (const step of steps.values()) {
if (Number.isFinite(step.durationMs) && step.durationMs >= 0) durations.push(step.durationMs);
if (Number.isFinite(step.reasoningTokens) && step.reasoningTokens >= 0) {
reasoningTokens += step.reasoningTokens;
reasoningTokenSampleCount += 1;
}
if (step.status === 'completed') completed += 1;
else if (step.status === 'failed') failed += 1;
else if (step.status === 'cancelled') cancelled += 1;
else incomplete += 1;
}
const totalDurationMs = durations.reduce((sum, value) => sum + value, 0);
return {
lifecycleObserved,
count: steps.size,
durations,
durationSampleCount: durations.length,
durationComplete: steps.size > 0 && durations.length === steps.size,
totalDurationMs,
averageDurationMs: durations.length > 0 ? totalDurationMs / durations.length : undefined,
p50DurationMs: percentileNearestRank(durations, 0.5),
p90DurationMs: percentileNearestRank(durations, 0.9),
maxDurationMs: durations.length > 0 ? Math.max(...durations) : undefined,
over60sCount: durations.filter((duration) => duration > 60_000).length,
completed,
failed,
cancelled,
incomplete,
retryCount,
// AMR/OpenCode reports provider usage per model step. Summing the unique
// step records recovers the turn total without treating the values as
// cumulative snapshots or double-counting repeated lifecycle frames.
reasoningTokens: reasoningTokenSampleCount > 0 ? reasoningTokens : undefined,
reasoningTokensComplete: steps.size > 0 && reasoningTokenSampleCount === steps.size,
};
}
function summarizeAssistantMessageEvents(events) {
const messages = new Map();
let lifecycleObserved = false;
let retryCount = 0;
let rateLimitedCount = 0;
let timeoutCount = 0;
let upstreamErrorCount = 0;
let provider;
let model;
let fallbackOrdinal = 0;
const countErrorClass = (value) => {
if (value === 'rate_limited') rateLimitedCount += 1;
else if (value === 'timeout') timeoutCount += 1;
else if (value === 'upstream_error') upstreamErrorCount += 1;
};
for (const record of events) {
if (record?.event !== 'agent' || !record.data || typeof record.data !== 'object') continue;
const data = record.data;
if (data.type !== 'diagnostic') continue;
if (data.name === 'model_retry') {
retryCount += 1;
countErrorClass(data.errorClass);
continue;
}
if (data.name !== 'assistant_message_lifecycle') continue;
lifecycleObserved = true;
if (typeof data.provider === 'string' && data.provider.trim()) provider = data.provider.trim();
if (typeof data.model === 'string' && data.model.trim()) model = data.model.trim();
const messageIndex = Number.isFinite(data.assistantMessageIndex)
? data.assistantMessageIndex
: `fallback-${fallbackOrdinal += 1}`;
const current = messages.get(messageIndex) ?? {
status: 'incomplete',
startedAtMs: undefined,
endedAtMs: undefined,
durationMs: undefined,
};
if (data.phase === 'start') {
if (Number.isFinite(data.startedAtMs)) current.startedAtMs = data.startedAtMs;
} else if (data.phase === 'end') {
if (Number.isFinite(data.startedAtMs)) current.startedAtMs = data.startedAtMs;
if (Number.isFinite(data.endedAtMs)) current.endedAtMs = data.endedAtMs;
if (Number.isFinite(data.durationMs) && data.durationMs >= 0) {
current.durationMs = data.durationMs;
} else if (
Number.isFinite(current.startedAtMs)
&& Number.isFinite(current.endedAtMs)
&& current.endedAtMs >= current.startedAtMs
) {
current.durationMs = current.endedAtMs - current.startedAtMs;
}
current.status =
data.status === 'failed' || data.status === 'cancelled' || data.status === 'completed'
? data.status
: 'incomplete';
countErrorClass(data.errorClass);
}
messages.set(messageIndex, current);
}
const durations = [];
let completed = 0;
let failed = 0;
let cancelled = 0;
let incomplete = 0;
for (const message of messages.values()) {
if (Number.isFinite(message.durationMs) && message.durationMs >= 0) durations.push(message.durationMs);
if (message.status === 'completed') completed += 1;
else if (message.status === 'failed') failed += 1;
else if (message.status === 'cancelled') cancelled += 1;
else incomplete += 1;
}
const totalDurationMs = durations.reduce((sum, value) => sum + value, 0);
return {
lifecycleObserved,
count: messages.size,
durationSampleCount: durations.length,
durationComplete: messages.size > 0 && durations.length === messages.size,
totalDurationMs,
averageDurationMs: durations.length > 0 ? totalDurationMs / durations.length : undefined,
maxDurationMs: durations.length > 0 ? Math.max(...durations) : undefined,
completed,
failed,
cancelled,
incomplete,
retryCount,
rateLimitedCount,
timeoutCount,
upstreamErrorCount,
provider,
model,
};
}
function classifyTerminalRunError(run) {
const value = `${run.errorCode ?? ''} ${run.error ?? ''}`.trim().toLowerCase();
if (!value) return undefined;
if (value.includes('429') || value.includes('rate limit') || value.includes('too many requests')) {
return 'rate_limited';
}
if (value.includes('timeout') || value.includes('timed out') || value.includes('deadline exceeded')) {
return 'timeout';
}
if (value.includes('upstream') || value.includes('service unavailable') || value.includes('bad gateway') || value.includes('gateway timeout')) {
return 'upstream_error';
}
return undefined;
}
function buildExecutionDiagnostics(run) {
if (!TERMINAL_RUN_STATUSES.has(run.status)) return undefined;
const eventStreamComplete = run.events.length === 0 || run.events[0]?.id === 1;
const timing = summarizeRunTimingAnalytics({
runCreatedAt: run.createdAt,
runUpdatedAt: run.updatedAt,
analyticsCapturedAt: run.updatedAt,
...(run.analyticsTelemetry ? { telemetry: run.analyticsTelemetry } : {}),
events: run.events,
});
const usage = scanRunEventsForUsageAnalytics(run.events, run.model, 0);
const tools = summarizeToolEvents(run.events, eventStreamComplete);
const modelSteps = summarizeModelStepEvents(run.events);
const assistantMessages = summarizeAssistantMessageEvents(run.events);
const terminalErrorClass = classifyTerminalRunError(run);
const firstModelEventAt = run.analyticsTelemetry?.firstModelEventAt;
const agentExecutionDurationMs =
typeof firstModelEventAt === 'number' && run.updatedAt >= firstModelEventAt
? Math.round(run.updatedAt - firstModelEventAt)
: undefined;
const eventCompletenessReason = eventStreamComplete
? undefined
: 'run_event_ring_buffer_truncated';
const toolValue = (value, definition) =>
eventStreamComplete
? availableDiagnostic(value, definition, true)
: missingDiagnostic(eventCompletenessReason);
const cacheSource = usage.cache_token_source === 'unavailable'
? 'model-provider'
: 'agent-runtime';
const cacheMetric = (value, definition) => optionalDiagnostic(
value,
definition,
eventStreamComplete,
usage.cache_token_source === 'unavailable'
? 'model_provider_did_not_return_cache_usage'
: eventCompletenessReason ?? 'upstream_did_not_emit_metric',
cacheSource,
);
const modelStepMetric = (value, definition, complete = modelSteps.durationComplete) => {
if (!eventStreamComplete) return missingDiagnostic(eventCompletenessReason, 'agent-runtime');
if (!modelSteps.lifecycleObserved) {
return missingDiagnostic('assistant_message_lifecycle_not_exposed_by_runtime', 'agent-runtime');
}
return value === undefined
? missingDiagnostic('model_step_duration_boundary_incomplete', 'agent-runtime', 'upstream_unavailable')
: availableDiagnostic(value, definition, complete, 'agent-runtime');
};
const percentileMetric = (value, definition, minimumSamples) => {
if (!eventStreamComplete) return missingDiagnostic(eventCompletenessReason, 'agent-runtime');
if (!modelSteps.lifecycleObserved) {
return missingDiagnostic('assistant_message_lifecycle_not_exposed_by_runtime', 'agent-runtime');
}
if (modelSteps.durationSampleCount < minimumSamples) {
return missingDiagnostic(
`insufficient_model_step_samples_min_${minimumSamples}`,
'agent-runtime',
'upstream_unavailable',
);
}
return availableDiagnostic(value, definition, modelSteps.durationComplete, 'agent-runtime');
};
const assistantMetric = (value, definition, complete = assistantMessages.durationComplete) => {
if (!eventStreamComplete) return missingDiagnostic(eventCompletenessReason, 'agent-runtime');
if (!assistantMessages.lifecycleObserved) {
return missingDiagnostic('assistant_message_lifecycle_not_exposed_by_runtime', 'agent-runtime');
}
return value === undefined
? missingDiagnostic('assistant_message_duration_boundary_incomplete', 'agent-runtime', 'upstream_unavailable')
: availableDiagnostic(value, definition, complete, 'agent-runtime');
};
const anomalyMetric = (value, definition) => eventStreamComplete
? availableDiagnostic(value, definition, true, 'agent-runtime')
: missingDiagnostic(eventCompletenessReason, 'agent-runtime');
const reasoningTokens = usage.thought_tokens ?? modelSteps.reasoningTokens;
const reasoningTokensComplete = usage.thought_tokens !== undefined
? eventStreamComplete
: eventStreamComplete && modelSteps.reasoningTokensComplete;
return {
schemaVersion: 1,
collectorVersion: 'open-design-execution-diagnostics-v2',
collectedAt: run.updatedAt,
eventStreamCompleteness: eventStreamComplete ? 'complete' : 'partial',
timing: {
queueDurationMs: optionalDiagnostic(timing.queue_duration_ms, 'run accepted to execution start'),
promptBuildDurationMs: optionalDiagnostic(timing.prompt_build_duration_ms, 'prompt build start to end'),
launchPreflightDurationMs: optionalDiagnostic(timing.launch_preflight_duration_ms, 'runtime preflight start to end'),
processSpawnDurationMs: optionalDiagnostic(timing.process_spawn_duration_ms, 'process spawn start to child ready'),
stdinWriteDurationMs: optionalDiagnostic(timing.stdin_write_duration_ms, 'prompt stdin write start to end'),
firstModelEventWaitMs: optionalDiagnostic(timing.time_to_first_model_event_ms, 'execution start to first model event'),
firstVisibleOutputWaitMs: optionalDiagnostic(timing.time_to_first_visible_output_ms, 'execution start to first visible assistant output'),
agentExecutionDurationMs: optionalDiagnostic(agentExecutionDurationMs, 'first model event to terminal run state'),
toolDurationMs: optionalDiagnostic(timing.tool_duration_ms, 'sum of paired tool_use to tool_result intervals', eventStreamComplete, eventCompletenessReason ?? 'no_paired_tool_duration'),
artifactWriteDurationMs: optionalDiagnostic(timing.artifact_write_duration_ms, 'first observed artifact-write tool interval'),
totalDurationMs: availableDiagnostic(timing.total_duration_ms, 'run accepted to terminal state'),
...(timing.phase_timing_status ? { phaseTimingStatus: timing.phase_timing_status } : {}),
...(timing.bottleneck_phase ? { bottleneckPhase: timing.bottleneck_phase } : {}),
},
modelSteps: {
count: modelStepMetric(modelSteps.count, 'unique observed model-step lifecycle records', true),
totalDurationMs: modelStepMetric(modelSteps.durationSampleCount > 0 ? modelSteps.totalDurationMs : undefined, 'sum of measured model-step durations'),
averageDurationMs: percentileMetric(modelSteps.averageDurationMs, 'average measured model-step duration; shown with at least 3 samples', 3),
p50DurationMs: percentileMetric(modelSteps.p50DurationMs, 'nearest-rank p50 measured model-step duration; shown with at least 3 samples', 3),
p90DurationMs: percentileMetric(modelSteps.p90DurationMs, 'nearest-rank p90 measured model-step duration; shown with at least 10 samples', 10),
maxDurationMs: modelStepMetric(modelSteps.maxDurationMs, 'maximum measured model-step duration'),
over60sCount: modelStepMetric(modelSteps.durationSampleCount > 0 ? modelSteps.over60sCount : undefined, 'measured model steps longer than 60 seconds'),
durationSampleCount: modelStepMetric(modelSteps.durationSampleCount, 'model steps with both start and end timing boundaries', true),
completed: modelStepMetric(modelSteps.completed, 'model steps ending completed', true),
failed: modelStepMetric(modelSteps.failed, 'model steps ending failed', true),
cancelled: modelStepMetric(modelSteps.cancelled, 'model steps ending cancelled', true),
incomplete: modelStepMetric(modelSteps.incomplete, 'model steps without a terminal lifecycle event', true),
retryCount: modelStepMetric(modelSteps.retryCount, 'runtime-observed model retry events; retries do not increment model-step count', true),
reasoningTokens: optionalDiagnostic(reasoningTokens, 'provider-reported reasoning token count summed across unique model steps when turn-level usage is absent', reasoningTokensComplete, 'model_provider_did_not_return_reasoning_tokens', 'model-provider'),
reasoningDurationMs: missingDiagnostic('reasoning_interval_boundaries_not_exposed_by_runtime', 'agent-runtime'),
},
assistantMessages: {
count: assistantMetric(assistantMessages.count, 'unique observed assistant-message lifecycle records', true),
totalDurationMs: assistantMetric(assistantMessages.durationSampleCount > 0 ? assistantMessages.totalDurationMs : undefined, 'sum of measured assistant-message durations'),
averageDurationMs: assistantMetric(assistantMessages.averageDurationMs, 'average measured assistant-message duration'),
maxDurationMs: assistantMetric(assistantMessages.maxDurationMs, 'maximum measured assistant-message duration'),
durationSampleCount: assistantMetric(assistantMessages.durationSampleCount, 'assistant messages with both timing boundaries', true),
completed: assistantMetric(assistantMessages.completed, 'assistant messages ending completed', true),
failed: assistantMetric(assistantMessages.failed, 'assistant messages ending failed', true),
cancelled: assistantMetric(assistantMessages.cancelled, 'assistant messages ending cancelled', true),
incomplete: assistantMetric(assistantMessages.incomplete, 'assistant messages without a terminal lifecycle event', true),
},
anomalies: {
retryCount: anomalyMetric(assistantMessages.retryCount, 'runtime-observed model retry events'),
rateLimitedCount: anomalyMetric(Math.max(assistantMessages.rateLimitedCount, terminalErrorClass === 'rate_limited' ? 1 : 0), 'runtime-observed 429 or rate-limit events'),
timeoutCount: anomalyMetric(Math.max(assistantMessages.timeoutCount, terminalErrorClass === 'timeout' ? 1 : 0), 'runtime-observed provider timeout events'),
upstreamErrorCount: anomalyMetric(Math.max(assistantMessages.upstreamErrorCount, terminalErrorClass === 'upstream_error' ? 1 : 0), 'runtime-observed upstream provider errors'),
},
tools: {
total: toolValue(tools.total, 'count of observed tool_use events'),
succeeded: toolValue(tools.succeeded, 'tool_result events without isError'),
failed: toolValue(tools.failed, 'tool_result events with isError'),
unknown: toolValue(tools.unknown, 'tool_use events without a matching terminal result'),
durationMs: toolValue(tools.durationMs, 'sum of paired tool_use to tool_result intervals'),
byName: toolValue(tools.byName, 'tool_use count grouped by redacted tool name'),
},
cache: {
inputTokensEffective: cacheMetric(usage.input_tokens_effective, 'normalized full prompt tokens'),
cacheReadInputTokens: cacheMetric(usage.cache_read_input_tokens, 'provider-reported cache-read input tokens'),
cacheCreationInputTokens: cacheMetric(usage.cache_creation_input_tokens, 'provider-reported cache-write input tokens'),
uncachedInputTokens: cacheMetric(usage.uncached_input_tokens, 'normalized uncached input tokens'),
cacheHitRatio: cacheMetric(usage.cache_hit_ratio, 'cache read tokens divided by effective input tokens'),
firstCallInputTokens: cacheMetric(usage.first_call_input_tokens, 'opening model call input tokens'),
firstCallCacheReadInputTokens: cacheMetric(usage.first_call_cache_read_input_tokens, 'opening model call cache-read tokens'),
firstCallCacheHitRatio: cacheMetric(usage.first_call_cache_hit_ratio, 'opening model call cache read divided by effective input'),
stablePromptCacheHit: run.promptCache
? availableDiagnostic(Boolean(run.promptCache.hit), 'local stable-prompt hash matched the prior run')
: missingDiagnostic('stable_prompt_cache_not_enabled'),
stablePromptCacheMissReason: run.promptCache?.missReason
? availableDiagnostic(run.promptCache.missReason, 'local stable-prompt cache miss classification')
: missingDiagnostic(run.promptCache?.hit ? 'stable_prompt_cache_hit' : 'stable_prompt_cache_not_enabled'),
},
environment: {
agentId: run.agentId
? availableDiagnostic(run.agentId, 'requested agent runtime', true, 'agent-runtime')
: missingDiagnostic('agent_id_not_recorded', 'agent-runtime'),
provider: assistantMessages.provider
? availableDiagnostic(assistantMessages.provider, 'provider id reported by the agent runtime', true, 'agent-runtime')
: missingDiagnostic('provider_not_reported_by_runtime', 'agent-runtime'),
requestedModel: run.model
? availableDiagnostic(run.model, 'requested model configuration', true, 'agent-runtime')
: missingDiagnostic('requested_model_not_recorded', 'agent-runtime'),
resolvedModel: run.resolvedModelId || assistantMessages.model
? availableDiagnostic(run.resolvedModelId || assistantMessages.model, 'runtime-resolved model id', true, 'agent-runtime')
: missingDiagnostic('resolved_model_not_reported', 'agent-runtime'),
reasoning: run.reasoning
? availableDiagnostic(run.reasoning, 'requested reasoning configuration', true, 'agent-runtime')
: missingDiagnostic('reasoning_configuration_not_recorded', 'agent-runtime'),
agentCliVersion: run.preflightAgentCliVersion
? availableDiagnostic(run.preflightAgentCliVersion, 'runtime CLI version observed during preflight', true, 'agent-runtime')
: missingDiagnostic('agent_cli_version_not_recorded', 'agent-runtime'),
},
};
}
function atomicWriteJson(filePath, value) {
const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(tempPath, `${JSON.stringify(value)}\n`, { encoding: 'utf8', mode: 0o600 });
fs.renameSync(tempPath, filePath);
} catch {
try { fs.unlinkSync(tempPath); } catch { /* best-effort cleanup */ }
}
}
function durableRunState(run) {
return {
schemaVersion: RUN_STATE_SCHEMA_VERSION,
id: run.id,
projectId: run.projectId,
conversationId: run.conversationId,
assistantMessageId: run.assistantMessageId,
clientRequestId: run.clientRequestId,
requestFingerprint: run.requestFingerprint,
agentId: run.agentId,
status: run.status,
createdAt: run.createdAt,
updatedAt: run.updatedAt,
exitCode: run.exitCode,
signal: run.signal,
error: run.error,
errorCode: run.errorCode,
failureCategory: run.failureCategory ?? null,
failureDetail: run.failureDetail ?? null,
failureAction: run.failureAction ?? null,
cancelOrigin: run.cancelOrigin ?? null,
terminalTrigger: run.terminalTrigger ?? null,
resumable: run.resumable ?? false,
artifactCount: Number.isFinite(run.artifactCount) ? run.artifactCount : 0,
...(Array.isArray(run.artifactPaths) ? { artifactPaths: run.artifactPaths } : {}),
endedWithUnfinishedWork: Boolean(run.endedWithUnfinishedWork),
...(typeof run.userPrompt === 'string' ? { userPrompt: run.userPrompt } : {}),
...(typeof run.model === 'string' ? { model: run.model } : {}),
...(typeof run.resolvedModelId === 'string'
? { resolvedModelId: run.resolvedModelId }
: {}),
...(typeof run.preflightAgentCliVersion === 'string'
? { preflightAgentCliVersion: run.preflightAgentCliVersion }
: {}),
...(typeof run.reasoning === 'string' ? { reasoning: run.reasoning } : {}),
...(typeof run.skillId === 'string' ? { skillId: run.skillId } : {}),
...(typeof run.designSystemId === 'string' ? { designSystemId: run.designSystemId } : {}),
...(typeof run.designSystemDigest === 'string' ? { designSystemDigest: run.designSystemDigest } : {}),
...(typeof run.designSystemSelectionSource === 'string'
? { designSystemSelectionSource: run.designSystemSelectionSource }
: {}),
...(typeof run.clientType === 'string' ? { clientType: run.clientType } : {}),
...(run.workspaceScope !== undefined ? { workspaceScope: run.workspaceScope } : {}),
...(run.designSystemScope !== undefined
? { designSystemScope: run.designSystemScope }
: {}),
...(run.analyticsTelemetry ? { analyticsTelemetry: run.analyticsTelemetry } : {}),
...(run.promptTelemetry ? { promptTelemetry: run.promptTelemetry } : {}),
...(run.promptCache ? { promptCache: run.promptCache } : {}),
...(run.analyticsRecovery ? { analyticsRecovery: run.analyticsRecovery } : {}),
...(run.externalPluginAnalytics
? { externalPluginAnalytics: run.externalPluginAnalytics }
: {}),
...(typeof run.manualResumeAttemptCount === 'number'
? { manualResumeAttemptCount: run.manualResumeAttemptCount }
: {}),
...(typeof run.rechargeWaitDurationMs === 'number'
? { rechargeWaitDurationMs: run.rechargeWaitDurationMs }
: {}),
...(typeof run.artifactOriginStatus === 'string'
? { artifactOriginStatus: run.artifactOriginStatus }
: {}),
...(typeof run.artifactVersionId === 'string'
? { artifactVersionId: run.artifactVersionId }
: {}),
...(typeof run.deliverableValid === 'boolean'
? { deliverableValid: run.deliverableValid }
: {}),
...(typeof run.deliverableValidation === 'string'
? { deliverableValidation: run.deliverableValidation }
: {}),
...(typeof run.deliverableEntryFile === 'string'
? { deliverableEntryFile: run.deliverableEntryFile }
: {}),
...(typeof run.deliverableArtifactKind === 'string'
? { deliverableArtifactKind: run.deliverableArtifactKind }
: {}),
...(typeof run.langfuseCompletedAt === 'number'
? { langfuseCompletedAt: run.langfuseCompletedAt }
: {}),
};
}
function readString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function extractErrorDetails(data) {
const payload = data && typeof data === 'object' ? data : {};
const nested = payload.error && typeof payload.error === 'object' ? payload.error : {};
return {
error: readString(nested.message) ?? readString(payload.message),
errorCode: readString(nested.code) ?? readString(payload.code),
};
}
function readDurableRunState(statePath) {
try {
const value = JSON.parse(fs.readFileSync(statePath, 'utf8'));
if (
!value
|| typeof value !== 'object'
|| value.schemaVersion !== RUN_STATE_SCHEMA_VERSION
|| typeof value.id !== 'string'
|| typeof value.status !== 'string'
) {
return null;
}
return value;
} catch {
return null;
}
}
function readDurableRunEvents(eventsLogPath) {
try {
return fs.readFileSync(eventsLogPath, 'utf8')
.split('\n')
.filter(Boolean)
.map((line) => JSON.parse(line))
.filter((record) =>
record
&& typeof record === 'object'
&& Number.isFinite(record.id)
&& typeof record.event === 'string');
} catch {
return [];
}
}
export function createChatRunService({
createSseResponse,
createSseErrorPayload,
maxEvents = 2_000,
ttlMs = 30 * 60 * 1000,
shutdownGraceMs = 3_000,
// Absolute directory under which per-run event JSONL logs are written
// (one file per run at <runsLogDir>/<runId>/events.jsonl). When null,
// event persistence is disabled and statusBody.eventsLogPath = null —
// legacy behavior. The path is surfaced through MCP get_run so an
// external coding agent can `tail` the file in its own shell during
// a long OD generation, instead of polling blindly and giving up.
runsLogDir = null,
// Optional observer invoked for every emitted event BEFORE the in-memory
// ring buffer is truncated. The daemon uses it to fold committed side
// effects (tool calls, artifact writes) into a per-run accumulator that
// outlives buffer truncation. Kept generic here: this service does not
// interpret event semantics, it just hands each record to the observer.
onEventEmitted = null,
}) {
const runs = new Map();
const runIdsByClientRequestId = new Map();
const runIdsByPluginWorkflowId = new Map();
if (runsLogDir) {
try {
for (const entry of fs.readdirSync(runsLogDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const state = readDurableRunState(path.join(runsLogDir, entry.name, 'state.json'));
if (
typeof state?.clientRequestId === 'string'
&& state.clientRequestId
&& typeof state.id === 'string'
) {
runIdsByClientRequestId.set(state.clientRequestId, state.id);
}
const pluginWorkflowId =
state?.externalPluginAnalytics?.externalPluginId
=== OPEN_DESIGN_PLUGIN_ID
&& typeof state.externalPluginAnalytics.pluginWorkflowId === 'string'
? state.externalPluginAnalytics.pluginWorkflowId
: null;
if (pluginWorkflowId && typeof state.id === 'string') {
runIdsByPluginWorkflowId.set(pluginWorkflowId, state.id);
}
}
} catch {
// A fresh data root has no runs directory yet.
}
}
const hydrateDurableRun = (id) => {
if (!runsLogDir || typeof id !== 'string' || !id) return null;
const statePath = path.join(runsLogDir, id, 'state.json');
const state = readDurableRunState(statePath);
if (!state || state.id !== id) return null;
const interruptedAfterRestart =
interruptDurableRunAfterDaemonRestart(state);
if (interruptedAfterRestart) atomicWriteJson(statePath, state);
if (!TERMINAL_RUN_STATUSES.has(state.status)) return null;
const eventsLogPath = path.join(runsLogDir, id, 'events.jsonl');
const events = readDurableRunEvents(eventsLogPath);
if (interruptedAfterRestart) {
const timestamp = state.updatedAt;
const nextEventId =
events.reduce((max, record) => Math.max(max, record.id), 0) + 1;
events.push(
{
id: nextEventId,
event: 'error',
data: {
error: {
code: RESTART_ERROR_CODE,
message: RESTART_ERROR_MESSAGE,
retryable: true,
},
},
timestamp,
},
{
id: nextEventId + 1,
event: 'end',
data: {
code: 1,
signal: null,
status: 'failed',
resumable: false,
endedWithUnfinishedWork: Boolean(state.endedWithUnfinishedWork),
},
timestamp,
},
);
}
const run = {
...state,
projectId: typeof state.projectId === 'string' ? state.projectId : null,
conversationId: typeof state.conversationId === 'string' ? state.conversationId : null,
assistantMessageId:
typeof state.assistantMessageId === 'string' ? state.assistantMessageId : null,
clientRequestId:
typeof state.clientRequestId === 'string' ? state.clientRequestId : null,
requestFingerprint:
typeof state.requestFingerprint === 'string' ? state.requestFingerprint : null,
agentId: typeof state.agentId === 'string' ? state.agentId : null,
projectMetadata: null,
events,
nextEventId: events.reduce((max, record) => Math.max(max, record.id), 0) + 1,
clients: new Set(),
waiters: new Set(),
child: null,
acpSession: null,
childPid: null,
processGroupId: null,
cancelRequested: false,
cancelOrigin: state.cancelOrigin ?? null,
terminalTrigger: state.terminalTrigger ?? null,
eventsLogPath,
statePath,
eventsLogStream: null,
eventsLogClosed: true,
mediaExecution: normalizeMediaExecutionPolicyForRun(null),
toolBundle: normalizeRunToolBundleForRun(null),
};
runs.set(id, run);
return run;
};
const create = (meta = {}) => {
const now = Date.now();
const id = randomUUID();
const run = {
id,
projectId: typeof meta.projectId === 'string' && meta.projectId ? meta.projectId : null,
conversationId: typeof meta.conversationId === 'string' && meta.conversationId ? meta.conversationId : null,
assistantMessageId: typeof meta.assistantMessageId === 'string' && meta.assistantMessageId ? meta.assistantMessageId : null,
clientRequestId: typeof meta.clientRequestId === 'string' && meta.clientRequestId ? meta.clientRequestId : null,
requestFingerprint:
typeof meta.requestFingerprint === 'string' && meta.requestFingerprint
? meta.requestFingerprint
: null,
agentId: typeof meta.agentId === 'string' && meta.agentId ? meta.agentId : null,
projectMetadata:
meta.projectMetadata && typeof meta.projectMetadata === 'object' && !Array.isArray(meta.projectMetadata)
? meta.projectMetadata
: null,
workspace: projectWorkspaceProvenance(meta.projectMetadata),
// Plan §3.A1 / spec §11.5. The applied plugin snapshot id pins
// every prompt fragment and tool gate to a frozen view so replay
// is byte-equal across plugin upgrades. Runs are in-memory in
// v1 — the id lives on the run object plus on the
// `applied_plugin_snapshots` row (FK back via run_id).
appliedPluginSnapshotId:
typeof meta.appliedPluginSnapshotId === 'string' && meta.appliedPluginSnapshotId
? meta.appliedPluginSnapshotId
: null,
pluginId:
typeof meta.pluginId === 'string' && meta.pluginId ? meta.pluginId : null,
mediaExecution: normalizeMediaExecutionPolicyForRun(meta.mediaExecution),
toolBundle: normalizeRunToolBundleForRun(meta.toolBundle),
browserUse: meta.browserUse && typeof meta.browserUse === 'object' ? meta.browserUse : null,
sessionMode:
meta.sessionMode === 'chat' || meta.sessionMode === 'design' || meta.sessionMode === 'plan'
? meta.sessionMode
: null,
context:
meta.context && typeof meta.context === 'object' && !Array.isArray(meta.context)
? meta.context
: null,
externalPluginAnalytics:
meta.analyticsHints
&& typeof meta.analyticsHints === 'object'
&& !Array.isArray(meta.analyticsHints)
&& meta.analyticsHints.externalPluginId === OPEN_DESIGN_PLUGIN_ID
? {
entrySurface: meta.analyticsHints.entrySurface,
hostProduct: meta.analyticsHints.hostProduct,
externalPluginId: OPEN_DESIGN_PLUGIN_ID,
externalPluginVersion: meta.analyticsHints.externalPluginVersion,
distributionMechanism:
meta.analyticsHints.distributionMechanism,
publisherClass: meta.analyticsHints.publisherClass,
attributionQuality: meta.analyticsHints.attributionQuality,
pluginWorkflowId: meta.analyticsHints.pluginWorkflowId,
logicalRequestDigest: meta.analyticsHints.logicalRequestDigest,
logicalRequestDigestVersion:
meta.analyticsHints.logicalRequestDigestVersion,
briefState: meta.analyticsHints.briefState,
generationSloWindowMs:
meta.analyticsHints.generationSloWindowMs,
}
: null,
status: 'queued',
createdAt: now,
updatedAt: now,
events: [],
nextEventId: 1,
clients: new Set(),
waiters: new Set(),
child: null,
acpSession: null,
childPid: null,
processGroupId: null,
childExitObservedAt: null,
exitCode: null,
signal: null,
error: null,
errorCode: null,
cancelRequested: false,
cancelOrigin: null,
terminalTrigger: null,
runtimeFailureObservedBeforeCancellation: false,
retryRestartTimer: null,
// First failure that triggered a same-run retry. The next attempt creates
// a fresh startChatRun closure and clears run.error/errorCode, so keep the
// compact analytics snapshot on the shared run until terminal telemetry.
retryOriginFailure: null,
retryOriginErrorCode: null,
retryStrategy: null,
retryMaxAttempts: null,
nativeSessionContinueAttemptCount: 0,
nativeSessionContinuePending: null,
stdinOpen: false,
// E-lite root-cause telemetry. `stdinBackpressure` records whether the
// prompt write to the child's stdin was queued (pipe buffer full — a
// corroborating signal for a `stdin_write`-phase stall). `lastAgentActivityAt`
// is the clock the inactivity watchdog keys off, read at finish to derive
// `last_progress_age_ms`. (`approval_requested` and `tool_result_sent` are
// derived from run.events by summarizeRunDiagnosticsForAnalytics.)
stdinBackpressure: false,
lastAgentActivityAt: now,
// Work-completeness signals (#1247 / #1060), folded from agent events by
// captureRunWorkCompletenessSignals (server.ts). `lastTodoSnapshot` is the
// most recent TodoWrite `todos` array; `truncatedMidTurn` records a
// max_tokens cut-off. At terminal time finish() derives
// `endedWithUnfinishedWork` from them via the canonical predicate.
lastTodoSnapshot: null,
truncatedMidTurn: false,
endedWithUnfinishedWork: false,
artifactCount: undefined as number | undefined,
artifactPaths: undefined as string[] | undefined,
artifactOutcome: undefined,
eventsLogPath: runsLogDir ? path.join(runsLogDir, id, 'events.jsonl') : null,
statePath: runsLogDir ? path.join(runsLogDir, id, 'state.json') : null,
eventsLogStream: null,
// Set once finish() has closed the log stream, so a late post-finish emit
// can't lazily re-open a stream nothing will ever close (FD leak).
eventsLogClosed: false,
cleanupGeneration: 0,
manualResumeAttemptCount: 0,
rechargeWaitDurationMs: 0,
};
if (Object.prototype.hasOwnProperty.call(meta, 'workspaceScope')) {
run.workspaceScope = meta.workspaceScope ?? null;
}
if (Object.prototype.hasOwnProperty.call(meta, 'designSystemScope')) {
run.designSystemScope = meta.designSystemScope ?? null;
}
runs.set(run.id, run);
if (run.clientRequestId) runIdsByClientRequestId.set(run.clientRequestId, run.id);
if (
run.externalPluginAnalytics?.externalPluginId === OPEN_DESIGN_PLUGIN_ID
&& typeof run.externalPluginAnalytics.pluginWorkflowId === 'string'
) {
runIdsByPluginWorkflowId.set(
run.externalPluginAnalytics.pluginWorkflowId,
run.id,
);
}
if (run.statePath) atomicWriteJson(run.statePath, durableRunState(run));
return run;
};
const createOrReuse = (meta = {}) => {
const clientRequestId =
typeof meta.clientRequestId === 'string' && meta.clientRequestId
? meta.clientRequestId
: null;
if (clientRequestId) {
const existingId = runIdsByClientRequestId.get(clientRequestId);
const existing = existingId
? runs.get(existingId) ?? hydrateDurableRun(existingId)
: null;
if (existing) {
const fingerprint =
typeof meta.requestFingerprint === 'string' ? meta.requestFingerprint : null;
if (
fingerprint
&& typeof existing.requestFingerprint === 'string'
&& existing.requestFingerprint
&& fingerprint !== existing.requestFingerprint
) {
return { kind: 'conflict', run: existing };
}
return { kind: 'reused', run: existing };
}
}
return { kind: 'created', run: create(meta) };
};
const persistState = (run) => {
if (run?.statePath) atomicWriteJson(run.statePath, durableRunState(run));
};
const setAnalyticsRecovery = (run, recovery) => {
if (!run || !recovery) return;
run.analyticsRecovery = {
context: recovery.context,
properties: recovery.properties,
insertId: recovery.insertId,
};
persistState(run);
};
const markAnalyticsCompleted = (run) => {
if (!run?.analyticsRecovery) return;
run.analyticsRecovery.completedAt = Date.now();
persistState(run);
};
const markLangfuseCompleted = (run) => {
if (!run) return;
run.langfuseCompletedAt = Date.now();
persistState(run);
};
const setDeliverableValidation = (run, result) => {
if (!run || !result) return;
run.deliverableValid = result.valid === true;
run.deliverableValidation =
typeof result.validation === 'string' ? result.validation : 'entry_missing';
run.deliverableEntryFile =
typeof result.entryFile === 'string' ? result.entryFile : undefined;
run.deliverableArtifactKind =
typeof result.artifactKind === 'string' ? result.artifactKind : undefined;
persistState(run);
};
const get = (id) => runs.get(id) ?? hydrateDurableRun(id);
const findByPluginWorkflowId = (pluginWorkflowId) => {
if (typeof pluginWorkflowId !== 'string' || !pluginWorkflowId) return null;
const runId = runIdsByPluginWorkflowId.get(pluginWorkflowId);
return runId ? get(runId) : null;
};
const scheduleCleanup = (run) => {
const generation = (run.cleanupGeneration ?? 0) + 1;
run.cleanupGeneration = generation;
setTimeout(() => {
if (
run.cleanupGeneration === generation
&& TERMINAL_RUN_STATUSES.has(run.status)
) {
runs.delete(run.id);
}
}, ttlMs).unref?.();
};
const prepareRestart = (run) => {
if (!run || !TERMINAL_RUN_STATUSES.has(run.status)) return null;
const resumedAt = Date.now();
const rechargeWaitDurationMs = Math.max(0, resumedAt - run.updatedAt);
// Invalidate the cleanup timer scheduled for the prior terminal attempt.
run.cleanupGeneration = (run.cleanupGeneration ?? 0) + 1;
run.status = 'queued';
run.updatedAt = resumedAt;
run.exitCode = null;
run.signal = null;
run.error = null;
run.errorCode = null;
run.failureCategory = null;
run.failureDetail = null;
run.failureAction = null;
run.resumable = false;
run.cancelRequested = false;
run.cancelOrigin = null;