@cairul/mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +202 -0
  2. package/bin/cairul-mcp.mjs +3 -0
  3. package/dist/api/index.d.ts +6 -0
  4. package/dist/api/index.js +12 -0
  5. package/dist/check-executions.d.ts +16 -0
  6. package/dist/check-executions.js +89 -0
  7. package/dist/check-kinds.d.ts +16 -0
  8. package/dist/check-kinds.js +69 -0
  9. package/dist/checks/github.d.ts +1 -0
  10. package/dist/checks/github.js +1 -0
  11. package/dist/checks/shell.d.ts +10 -0
  12. package/dist/checks/shell.js +62 -0
  13. package/dist/environment.d.ts +1 -0
  14. package/dist/environment.js +4 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +76 -0
  17. package/dist/journeys.d.ts +14 -0
  18. package/dist/journeys.js +183 -0
  19. package/dist/local-config.d.ts +112 -0
  20. package/dist/local-config.js +210 -0
  21. package/dist/local-journeys.d.ts +647 -0
  22. package/dist/local-journeys.js +332 -0
  23. package/dist/local-plugins.d.ts +2 -0
  24. package/dist/local-plugins.js +54 -0
  25. package/dist/logging.d.ts +4 -0
  26. package/dist/logging.js +19 -0
  27. package/dist/observations/codex-rollout.d.ts +67 -0
  28. package/dist/observations/codex-rollout.js +241 -0
  29. package/dist/observations/codex.d.ts +18 -0
  30. package/dist/observations/codex.js +289 -0
  31. package/dist/observations/execution.d.ts +27 -0
  32. package/dist/observations/execution.js +84 -0
  33. package/dist/observations/harness.d.ts +40 -0
  34. package/dist/observations/harness.js +17 -0
  35. package/dist/observations/mcp.d.ts +8 -0
  36. package/dist/observations/mcp.js +15 -0
  37. package/dist/observations/publisher.d.ts +33 -0
  38. package/dist/observations/publisher.js +120 -0
  39. package/dist/observations/settings.d.ts +1 -0
  40. package/dist/observations/settings.js +2 -0
  41. package/dist/plugin.d.ts +22 -0
  42. package/dist/plugin.js +1 -0
  43. package/package.json +42 -3
  44. package/README.md +0 -3
@@ -0,0 +1,241 @@
1
+ import { glob, open } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { env } from 'node:process';
5
+ import { z } from 'zod';
6
+ const identifier = z.string().regex(/^[\w.:/-]{1,200}$/);
7
+ const identityMetadata = z.object({
8
+ sessionId: z.uuid(),
9
+ threadId: z.uuid(),
10
+ 'x-codex-turn-metadata': z.object({ codex_version: identifier.optional() }).optional(),
11
+ });
12
+ export function readCodexIdentity(input) {
13
+ const meta = identityMetadata.safeParse(input);
14
+ if (!meta.success)
15
+ return;
16
+ return {
17
+ sessionId: meta.data.sessionId,
18
+ threadId: meta.data.threadId,
19
+ harnessVersion: meta.data['x-codex-turn-metadata']?.codex_version,
20
+ };
21
+ }
22
+ const metadata = identityMetadata.extend({
23
+ callId: identifier,
24
+ 'x-codex-turn-metadata': z.object({
25
+ turn_id: identifier,
26
+ model: identifier.optional(),
27
+ codex_version: identifier.optional(),
28
+ }),
29
+ });
30
+ export function readCodexCall(input, name, at) {
31
+ const meta = metadata.safeParse(input);
32
+ if (!meta.success)
33
+ return;
34
+ const { sessionId, threadId, callId, 'x-codex-turn-metadata': turn } = meta.data;
35
+ return {
36
+ session: sessionId,
37
+ thread: threadId,
38
+ call: callId,
39
+ turn: turn.turn_id,
40
+ model: turn.model,
41
+ version: turn.codex_version,
42
+ tool: 'mcp__cairul__' + name,
43
+ at,
44
+ };
45
+ }
46
+ const tokens = {
47
+ input_tokens: 'inputTokens',
48
+ output_tokens: 'outputTokens',
49
+ cached_input_tokens: 'cachedInputTokens',
50
+ cache_write_input_tokens: 'cacheWriteInputTokens',
51
+ reasoning_output_tokens: 'reasoningOutputTokens',
52
+ };
53
+ function object(value) {
54
+ if (typeof value === 'object' && value !== null && !Array.isArray(value))
55
+ return value;
56
+ }
57
+ function id(value) {
58
+ return identifier.safeParse(value).data;
59
+ }
60
+ function toolName(payload) {
61
+ const name = id(payload.name);
62
+ const namespace = id(payload.namespace);
63
+ return namespace && name ? namespace + '__' + name : name;
64
+ }
65
+ function decode(line, thread) {
66
+ let value;
67
+ try {
68
+ value = JSON.parse(line.toString('utf8'));
69
+ }
70
+ catch {
71
+ return;
72
+ }
73
+ const record = object(value);
74
+ const payload = object(record?.payload);
75
+ if (!record || !payload || typeof record.timestamp !== 'string')
76
+ return;
77
+ const at = Date.parse(record.timestamp);
78
+ if (!Number.isFinite(at) || (payload.thread_id && payload.thread_id !== thread))
79
+ return;
80
+ const turn = id(payload.turn_id);
81
+ if (record.type === 'session_meta' && payload.id === thread) {
82
+ return { type: 'session', at, provider: id(payload.model_provider), version: id(payload.cli_version) };
83
+ }
84
+ if (record.type === 'turn_context' && turn)
85
+ return { type: 'turn', at, turn, model: id(payload.model) };
86
+ if (record.type === 'token_usage_record' && turn) {
87
+ const response = id(payload.response_id);
88
+ if (!response)
89
+ return;
90
+ const usage = object(payload.usage);
91
+ const values = {};
92
+ for (const [field, attr] of Object.entries(tokens)) {
93
+ const count = usage?.[field];
94
+ if (typeof count === 'number' && Number.isSafeInteger(count) && count >= 0)
95
+ values[attr] = count;
96
+ }
97
+ return { type: 'generation', at, turn, response, usage: values };
98
+ }
99
+ if (record.type === 'response_item') {
100
+ const call = id(payload.call_id);
101
+ if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
102
+ const name = toolName(payload);
103
+ if (call && name)
104
+ return { type: 'tool', at, call, name };
105
+ }
106
+ if (call && (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output')) {
107
+ const success = object(payload.output)?.success;
108
+ return { type: 'tool_end', at, call, failed: typeof success === 'boolean' ? !success : undefined };
109
+ }
110
+ if (payload.type === 'reasoning' || (payload.type === 'message' && payload.role === 'assistant')) {
111
+ return { type: 'output', at };
112
+ }
113
+ }
114
+ if (record.type !== 'event_msg' || !turn)
115
+ return;
116
+ if (payload.type === 'task_started')
117
+ return { type: 'turn', at, turn };
118
+ if (payload.type === 'task_complete' || payload.type === 'turn_aborted') {
119
+ return { type: payload.type === 'task_complete' ? 'stop' : 'interrupt', at, turn };
120
+ }
121
+ if (payload.type === 'item_completed') {
122
+ const item = object(payload.item);
123
+ const call = id(item?.id);
124
+ if (!item || !call)
125
+ return;
126
+ const server = id(item.server);
127
+ const tool = id(item.tool);
128
+ const name = item.type === 'McpToolCall' && server && tool
129
+ ? 'mcp__' + server + '__' + tool
130
+ : item.type === 'CommandExecution'
131
+ ? 'exec_command'
132
+ : item.type === 'FileChange'
133
+ ? 'apply_patch'
134
+ : item.type === 'WebSearch'
135
+ ? 'web_search'
136
+ : undefined;
137
+ if (!name)
138
+ return;
139
+ const started = typeof payload.started_at_ms === 'number' ? payload.started_at_ms : undefined;
140
+ const ended = typeof payload.completed_at_ms === 'number' ? payload.completed_at_ms : at;
141
+ const failed = ['failed', 'declined', 'cancelled'].includes(String(item.status))
142
+ ? true
143
+ : item.status === 'completed'
144
+ ? false
145
+ : undefined;
146
+ return { type: 'tool_end', at: Math.min(at, ended), call, name, started, failed };
147
+ }
148
+ }
149
+ const chunkSize = 64 * 1024;
150
+ const tailSize = 512 * 1024;
151
+ const maxLine = 2 * 1024 * 1024;
152
+ async function locateRollout(thread) {
153
+ const codexHome = env.CODEX_HOME ?? join(homedir(), '.codex');
154
+ const cwd = join(codexHome, 'sessions');
155
+ for await (const name of glob('**/rollout-*-' + thread + '.jsonl', { cwd })) {
156
+ return open(join(cwd, name), 'r');
157
+ }
158
+ }
159
+ export async function readCodexProject(thread) {
160
+ const file = await locateRollout(thread);
161
+ if (!file)
162
+ return;
163
+ try {
164
+ const buffer = Buffer.allocUnsafe(chunkSize);
165
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
166
+ const newline = buffer.subarray(0, bytesRead).indexOf(10);
167
+ if (newline === -1)
168
+ return;
169
+ const record = object(JSON.parse(buffer.toString('utf8', 0, newline)));
170
+ const payload = object(record?.payload);
171
+ if (record?.type === 'session_meta' && payload?.id === thread && typeof payload.cwd === 'string') {
172
+ return payload.cwd;
173
+ }
174
+ }
175
+ finally {
176
+ await file.close();
177
+ }
178
+ }
179
+ export class CodexRollout {
180
+ thread;
181
+ file;
182
+ offset = 0;
183
+ pending = Buffer.alloc(0);
184
+ skipLine = false;
185
+ nextLookup = 0;
186
+ constructor(thread) {
187
+ this.thread = thread;
188
+ }
189
+ async locate() {
190
+ if (Date.now() < this.nextLookup)
191
+ return;
192
+ this.nextLookup = Date.now() + 1000;
193
+ const file = await locateRollout(this.thread);
194
+ if (file) {
195
+ this.file = file;
196
+ this.offset = Math.max(0, (await file.stat()).size - tailSize);
197
+ this.skipLine = this.offset > 0;
198
+ }
199
+ }
200
+ async *read() {
201
+ if (!this.file)
202
+ await this.locate();
203
+ const file = this.file;
204
+ if (!file)
205
+ return;
206
+ const size = (await file.stat()).size;
207
+ const buffer = Buffer.allocUnsafe(chunkSize);
208
+ while (this.offset < size) {
209
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - this.offset), this.offset);
210
+ if (bytesRead === 0)
211
+ break;
212
+ this.offset += bytesRead;
213
+ for (let pos = 0; pos < bytesRead;) {
214
+ const lf = buffer.indexOf(10, pos);
215
+ const complete = lf >= 0 && lf < bytesRead;
216
+ const end = complete ? lf : bytesRead;
217
+ const part = buffer.subarray(pos, end);
218
+ if (this.pending.length + part.length > maxLine)
219
+ this.skipLine = true;
220
+ if (complete) {
221
+ const line = this.pending.length ? Buffer.concat([this.pending, part]) : part;
222
+ const event = this.skipLine ? undefined : decode(line, this.thread);
223
+ this.pending = Buffer.alloc(0);
224
+ this.skipLine = false;
225
+ if (event)
226
+ yield event;
227
+ }
228
+ else if (!this.skipLine) {
229
+ this.pending = this.pending.length ? Buffer.concat([this.pending, part]) : Buffer.from(part);
230
+ }
231
+ pos = end + 1;
232
+ }
233
+ }
234
+ }
235
+ get available() {
236
+ return this.file !== undefined;
237
+ }
238
+ async close() {
239
+ await this.file?.close();
240
+ }
241
+ }
@@ -0,0 +1,18 @@
1
+ import type { HarnessTracker, JourneyState, RequestOutcome } from './harness.js';
2
+ import type { ObservationPublisher } from './publisher.js';
3
+ export declare class CodexTracker implements HarnessTracker {
4
+ private readonly publisher;
5
+ private readonly readJourney;
6
+ private readonly captures;
7
+ private queue;
8
+ private readonly timer;
9
+ private stopping;
10
+ private checking;
11
+ constructor(publisher: ObservationPublisher, readJourney: (id: string) => Promise<JourneyState>);
12
+ private poll;
13
+ beginTool(input: unknown, name: string, at: number): Promise<((outcome: RequestOutcome) => Promise<void>) | undefined>;
14
+ private finishJourney;
15
+ shutdown(): Promise<void>;
16
+ private close;
17
+ private enqueue;
18
+ }
@@ -0,0 +1,289 @@
1
+ import { log } from '../logging.js';
2
+ import { CodexRollout, readCodexCall } from './codex-rollout.js';
3
+ import { Execution, timestamp } from './execution.js';
4
+ class Capture {
5
+ recording;
6
+ opening;
7
+ journey;
8
+ started;
9
+ reader;
10
+ batches = new Set();
11
+ calls = new Map();
12
+ completedCalls = new Set();
13
+ responses = new Set();
14
+ deferred = [];
15
+ current;
16
+ model;
17
+ provider;
18
+ turn;
19
+ openingInferencePending = false;
20
+ pendingTerminalCalls = 0;
21
+ constructor(recording, opening, journey, started) {
22
+ this.recording = recording;
23
+ this.opening = opening;
24
+ this.journey = journey;
25
+ this.started = started;
26
+ this.reader = new CodexRollout(opening.thread);
27
+ this.model = opening.model;
28
+ this.turn = opening.turn;
29
+ }
30
+ async drain(cutoff) {
31
+ const deferred = this.deferred;
32
+ this.deferred = [];
33
+ for (const event of deferred)
34
+ this.acceptBefore(event, cutoff);
35
+ for await (const event of this.reader.read())
36
+ this.acceptBefore(event, cutoff);
37
+ }
38
+ acceptBefore(event, cutoff) {
39
+ if (event.at > cutoff) {
40
+ this.deferred.push(event);
41
+ return;
42
+ }
43
+ if (event.type === 'session') {
44
+ this.provider = event.provider;
45
+ return;
46
+ }
47
+ // The opening tool can finish after activation, but its inference was already in flight.
48
+ if (event.type === 'tool' && event.call === this.opening.call) {
49
+ this.openingInferencePending = true;
50
+ return;
51
+ }
52
+ if (event.type === 'generation' && this.openingInferencePending) {
53
+ this.openingInferencePending = false;
54
+ if (event.turn === this.opening.turn)
55
+ return;
56
+ }
57
+ if (event.at < this.started)
58
+ return;
59
+ switch (event.type) {
60
+ case 'turn':
61
+ if (event.turn !== this.turn)
62
+ this.changeTurn(event.turn);
63
+ if (event.model)
64
+ this.model = event.model;
65
+ break;
66
+ case 'output':
67
+ this.batch(event.at);
68
+ break;
69
+ case 'generation':
70
+ if (this.responses.has(event.response))
71
+ return;
72
+ if (event.turn !== this.turn)
73
+ this.changeTurn(event.turn);
74
+ this.responses.add(event.response);
75
+ this.batch(event.at).generation(event.at, event.response, event.usage, this.model, this.provider);
76
+ break;
77
+ case 'tool':
78
+ this.declareTool(event.call, event.name, event.at);
79
+ break;
80
+ case 'tool_end':
81
+ if (event.call === this.opening.call || (event.started !== undefined && event.started < this.started))
82
+ return;
83
+ if (event.name && this.current)
84
+ this.declareTool(event.call, event.name, event.started ?? event.at, this.current);
85
+ this.completeTool(event.call, event.at, event.failed, event.started);
86
+ break;
87
+ case 'stop':
88
+ case 'interrupt':
89
+ if (event.turn === this.turn)
90
+ this.closeBatches(event.type);
91
+ break;
92
+ }
93
+ }
94
+ changeTurn(turn) {
95
+ this.closeBatches('next_turn');
96
+ this.turn = turn;
97
+ this.model = undefined;
98
+ }
99
+ batch(at) {
100
+ if (this.current?.response !== undefined) {
101
+ this.current.sealed = true;
102
+ this.closeIfFinished(this.current);
103
+ this.current = undefined;
104
+ }
105
+ if (!this.current) {
106
+ this.current = new Execution(this.turn, Math.max(at, this.started));
107
+ this.batches.add(this.current);
108
+ }
109
+ return this.current;
110
+ }
111
+ declareTool(call, name, at, existing) {
112
+ if (this.completedCalls.has(call))
113
+ return;
114
+ const batch = this.calls.get(call) ?? existing ?? this.batch(at);
115
+ batch.declareTool(call, name, at);
116
+ this.calls.set(call, batch);
117
+ return batch;
118
+ }
119
+ beginTool(call) {
120
+ if (call.turn !== this.turn)
121
+ this.changeTurn(call.turn);
122
+ if (call.model)
123
+ this.model = call.model;
124
+ this.declareTool(call.call, call.tool, call.at)?.beginMCP(call.call, call.at);
125
+ }
126
+ completeTool(call, at, failed, started, request) {
127
+ const execution = this.calls.get(call);
128
+ if (!execution)
129
+ return;
130
+ execution.completeTool(call, at, started, failed, request);
131
+ this.calls.delete(call);
132
+ this.completedCalls.add(call);
133
+ this.closeIfFinished(execution);
134
+ }
135
+ closeIfFinished(batch) {
136
+ if (!batch.sealed || batch.tools.size)
137
+ return;
138
+ this.collect(batch, 'next_model_response');
139
+ this.batches.delete(batch);
140
+ }
141
+ closeBatches(reason, cutoff) {
142
+ for (const batch of this.batches)
143
+ this.collect(batch, reason, cutoff);
144
+ this.batches.clear();
145
+ this.calls.clear();
146
+ this.current = undefined;
147
+ }
148
+ collect(batch, reason, cutoff) {
149
+ const observation = batch.close(reason, cutoff);
150
+ if (observation)
151
+ this.recording.collect(observation);
152
+ }
153
+ async close(reason, at) {
154
+ this.closeBatches(reason, at);
155
+ this.recording.close(reason, at, this.reader.available);
156
+ await this.reader.close();
157
+ }
158
+ }
159
+ export class CodexTracker {
160
+ publisher;
161
+ readJourney;
162
+ captures = new Map();
163
+ queue = Promise.resolve(undefined);
164
+ timer;
165
+ stopping = false;
166
+ checking = false;
167
+ constructor(publisher, readJourney) {
168
+ this.publisher = publisher;
169
+ this.readJourney = readJourney;
170
+ this.timer = setInterval(() => {
171
+ void this.poll();
172
+ void this.publisher.flush();
173
+ }, 1000).unref();
174
+ }
175
+ async poll() {
176
+ if (this.stopping || this.checking || this.captures.size === 0)
177
+ return;
178
+ this.checking = true;
179
+ try {
180
+ await Promise.all([...this.captures].map(async ([thread, capture]) => {
181
+ const observedAt = Date.now();
182
+ const state = await this.readJourney(capture.journey.id).catch(() => undefined);
183
+ if (!state || this.stopping)
184
+ return;
185
+ await this.enqueue(async () => {
186
+ if (this.captures.get(thread) !== capture)
187
+ return;
188
+ if (state.status === 'active') {
189
+ await capture.drain(observedAt);
190
+ if (Date.parse(state.updated_at) >= Date.parse(capture.journey.updated_at))
191
+ capture.journey = state;
192
+ }
193
+ else if (capture.pendingTerminalCalls === 0) {
194
+ const terminal = Date.parse(state.updated_at);
195
+ const now = Date.now();
196
+ await this.finishJourney(thread, capture, state, Number.isFinite(terminal) ? Math.min(terminal, now) : now);
197
+ }
198
+ });
199
+ }));
200
+ }
201
+ finally {
202
+ this.checking = false;
203
+ }
204
+ }
205
+ beginTool(input, name, at) {
206
+ const call = readCodexCall(input, name, at);
207
+ if (!call || this.stopping)
208
+ return Promise.resolve(undefined);
209
+ return this.enqueue(async () => {
210
+ const capture = this.captures.get(call.thread);
211
+ await capture?.drain(at);
212
+ capture?.beginTool(call);
213
+ const terminal = capture && (name === 'journey_complete' || name === 'journey_abort') ? capture : undefined;
214
+ if (terminal)
215
+ terminal.pendingTerminalCalls++;
216
+ return ({ failed, endedAt, journey, httpStatus }) => this.enqueue(async () => {
217
+ if (terminal)
218
+ terminal.pendingTerminalCalls--;
219
+ const request = {
220
+ callId: call.call,
221
+ tool: name,
222
+ startedAt: timestamp(at),
223
+ endedAt: timestamp(endedAt),
224
+ failed,
225
+ httpStatus,
226
+ };
227
+ capture?.completeTool(call.call, endedAt, failed, undefined, request);
228
+ if (!journey || this.stopping)
229
+ return;
230
+ const current = this.captures.get(call.thread);
231
+ if (journey.status === 'active') {
232
+ if (current?.journey.id === journey.id) {
233
+ current.journey = journey;
234
+ }
235
+ else {
236
+ if (current)
237
+ await this.close(call.thread, 'journey_switched', endedAt);
238
+ const policy = journey.capture_policy;
239
+ if (policy.mode === 'none')
240
+ return;
241
+ const recording = this.publisher.open(journey.id, {
242
+ name: 'codex',
243
+ sessionId: call.session,
244
+ threadId: call.thread,
245
+ version: call.version,
246
+ }, policy, endedAt, request);
247
+ this.captures.set(call.thread, new Capture(recording, call, journey, endedAt));
248
+ }
249
+ }
250
+ else if (current?.journey.id === journey.id) {
251
+ await this.finishJourney(call.thread, current, journey, endedAt);
252
+ }
253
+ });
254
+ });
255
+ }
256
+ async finishJourney(thread, capture, journey, at) {
257
+ await capture.drain(at);
258
+ capture.journey = journey;
259
+ await this.close(thread, journey.status === 'completed' ? 'completed' : 'aborted', at);
260
+ void this.publisher.flush();
261
+ }
262
+ async shutdown() {
263
+ if (this.stopping)
264
+ return;
265
+ this.stopping = true;
266
+ clearInterval(this.timer);
267
+ await this.enqueue(async () => {
268
+ const now = Date.now();
269
+ for (const [thread, capture] of this.captures) {
270
+ await capture.drain(now);
271
+ await this.close(thread, 'session_end', now);
272
+ }
273
+ });
274
+ await this.publisher.shutdown();
275
+ }
276
+ async close(thread, reason, at) {
277
+ const capture = this.captures.get(thread);
278
+ this.captures.delete(thread);
279
+ await capture?.close(reason, at);
280
+ }
281
+ enqueue(work) {
282
+ const next = this.queue.then(work).catch((error) => {
283
+ log('warn', 'Codex telemetry collection failed', { error_type: error instanceof Error ? error.name : 'unknown' });
284
+ return undefined;
285
+ });
286
+ this.queue = next;
287
+ return next;
288
+ }
289
+ }
@@ -0,0 +1,27 @@
1
+ import type { ExecutionObservation, MCPRequestObservation, TokenUsage } from '@cairul/sdk';
2
+ type PendingTool = {
3
+ name: string;
4
+ at: number;
5
+ mcpAt?: number;
6
+ };
7
+ export declare const timestamp: (ms: number) => string;
8
+ export declare class Execution {
9
+ readonly turnId: string;
10
+ private readonly at;
11
+ readonly tools: Map<string, PendingTool>;
12
+ private readonly completed;
13
+ private model?;
14
+ sealed: boolean;
15
+ private last;
16
+ constructor(turnId: string, at: number);
17
+ get response(): string | undefined;
18
+ generation(at: number, response: string, usage: TokenUsage, name?: string, provider?: string): void;
19
+ declareTool(call: string, name: string, at: number): void;
20
+ beginMCP(call: string, at: number): void;
21
+ completeTool(call: string, at: number, started?: number, failed?: boolean, request?: MCPRequestObservation): void;
22
+ close(reason: string, cutoff?: number): {
23
+ occurredAt: string;
24
+ execution: ExecutionObservation;
25
+ } | undefined;
26
+ }
27
+ export {};
@@ -0,0 +1,84 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export const timestamp = (ms) => new Date(ms).toISOString();
3
+ export class Execution {
4
+ turnId;
5
+ at;
6
+ tools = new Map();
7
+ completed = [];
8
+ model;
9
+ sealed = false;
10
+ last;
11
+ constructor(turnId, at) {
12
+ this.turnId = turnId;
13
+ this.at = at;
14
+ this.last = at;
15
+ }
16
+ get response() {
17
+ return this.model?.responseId;
18
+ }
19
+ generation(at, response, usage, name, provider) {
20
+ this.model = { responseId: response, observedAt: timestamp(Math.max(at, this.at)), usage, name, provider };
21
+ this.last = Math.max(this.last, at);
22
+ }
23
+ declareTool(call, name, at) {
24
+ if (this.tools.has(call))
25
+ return;
26
+ this.tools.set(call, { name, at });
27
+ }
28
+ beginMCP(call, at) {
29
+ const tool = this.tools.get(call);
30
+ if (tool)
31
+ tool.mcpAt = at;
32
+ }
33
+ completeTool(call, at, started, failed, request) {
34
+ const tool = this.tools.get(call);
35
+ if (!tool)
36
+ return;
37
+ const start = Math.max(this.at, tool.mcpAt ?? started ?? tool.at);
38
+ const end = Math.max(start, at);
39
+ this.completed.push({
40
+ callId: call,
41
+ name: tool.name,
42
+ startedAt: timestamp(start),
43
+ endedAt: timestamp(end),
44
+ failed,
45
+ request,
46
+ timing: tool.mcpAt !== undefined ? 'mcp_request' : started !== undefined ? 'runtime' : 'rollout',
47
+ });
48
+ this.last = Math.max(this.last, end);
49
+ this.tools.delete(call);
50
+ }
51
+ close(reason, cutoff = Infinity) {
52
+ if (this.at > cutoff)
53
+ return;
54
+ const end = Math.min(Math.max(this.last, this.at), cutoff);
55
+ const occurredAt = timestamp(end);
56
+ const model = this.model && this.model.observedAt <= occurredAt ? this.model : undefined;
57
+ const tools = this.completed
58
+ .filter((tool) => tool.startedAt <= occurredAt)
59
+ .map((tool) => tool.endedAt && tool.endedAt > occurredAt
60
+ ? { ...tool, endedAt: undefined, failed: undefined, request: undefined }
61
+ : tool);
62
+ for (const [callId, tool] of this.tools) {
63
+ const start = tool.mcpAt ?? tool.at;
64
+ if (start > cutoff)
65
+ continue;
66
+ tools.push({
67
+ callId,
68
+ name: tool.name,
69
+ startedAt: timestamp(Math.min(end, Math.max(this.at, start))),
70
+ timing: tool.mcpAt !== undefined ? 'mcp_request' : 'rollout',
71
+ });
72
+ }
73
+ const execution = {
74
+ id: randomUUID(),
75
+ turnId: this.turnId,
76
+ observedStartedAt: timestamp(this.at),
77
+ model,
78
+ tools,
79
+ partial: model === undefined || tools.some((tool) => tool.endedAt === undefined),
80
+ endReason: reason,
81
+ };
82
+ return { occurredAt, execution };
83
+ }
84
+ }