@jini-ai/agent-runtime 0.4.10 → 0.4.12
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.
- package/CHANGELOG.md +9 -0
- package/dist/acp-model-probe.d.ts +2 -20
- package/dist/agent-protocol/acp/json.js +46 -37
- package/dist/agent-protocol/acp/models.js +91 -73
- package/dist/agent-protocol/acp/rpc.d.ts +3 -2
- package/dist/agent-protocol/acp/rpc.js +3 -2
- package/dist/agent-protocol/acp/session-params.d.ts +1 -1
- package/dist/agent-protocol/acp/session-params.js +33 -30
- package/dist/agent-protocol/acp/session.d.ts +3 -1
- package/dist/agent-protocol/acp/session.js +62 -24
- package/dist/agent-protocol/acp/updates.js +49 -35
- package/dist/agent-protocol/pi-rpc/session.js +3 -1
- package/dist/anthropic-live-models.d.ts +12 -4
- package/dist/anthropic-live-models.js +0 -0
- package/dist/auth.js +84 -91
- package/dist/claude-code-models.d.ts +6 -5
- package/dist/claude-code-models.js +19 -12
- package/dist/claude-segment-usage.d.ts +3 -3
- package/dist/claude-segment-usage.js +63 -29
- package/dist/claude-stream.js +12 -5
- package/dist/copilot-stream.js +42 -50
- package/dist/defs/aider.js +3 -4
- package/dist/defs/amr.js +52 -61
- package/dist/defs/antigravity.d.ts +6 -5
- package/dist/defs/antigravity.js +48 -34
- package/dist/defs/auggie.d.ts +1 -1
- package/dist/defs/claude-compatible-args.d.ts +19 -0
- package/dist/defs/claude-compatible-args.js +42 -0
- package/dist/defs/claude.d.ts +7 -2
- package/dist/defs/claude.js +96 -85
- package/dist/defs/cline.d.ts +1 -1
- package/dist/defs/codebuddy.d.ts +1 -1
- package/dist/defs/codebuddy.js +29 -46
- package/dist/defs/codex.d.ts +15 -3
- package/dist/defs/codex.js +143 -108
- package/dist/defs/cursor-agent.d.ts +9 -7
- package/dist/defs/cursor-agent.js +53 -51
- package/dist/defs/devin.d.ts +1 -1
- package/dist/defs/goose.d.ts +1 -1
- package/dist/defs/hermes.d.ts +1 -1
- package/dist/defs/kilo.d.ts +1 -1
- package/dist/defs/kimi.d.ts +1 -1
- package/dist/defs/kiro.d.ts +1 -1
- package/dist/defs/opencode.d.ts +5 -4
- package/dist/defs/opencode.js +26 -32
- package/dist/defs/pi.d.ts +6 -5
- package/dist/defs/pi.js +24 -26
- package/dist/defs/qoder.d.ts +4 -3
- package/dist/defs/qoder.js +25 -25
- package/dist/defs/reasonix.d.ts +1 -1
- package/dist/defs/shared.d.ts +12 -3
- package/dist/defs/shared.js +19 -13
- package/dist/defs/trae-cli.d.ts +1 -1
- package/dist/defs/vibe.d.ts +1 -1
- package/dist/detection.d.ts +13 -20
- package/dist/detection.js +129 -111
- package/dist/env.js +56 -41
- package/dist/executables.js +103 -114
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/json-event-stream.js +611 -527
- package/dist/launch.js +44 -37
- package/dist/model-discovery-adapters.d.ts +17 -0
- package/dist/model-discovery-adapters.js +223 -164
- package/dist/model-discovery-config.js +107 -87
- package/dist/model-discovery-sdk.d.ts +16 -2
- package/dist/model-discovery-sdk.js +4 -3
- package/dist/model-discovery-shared.d.ts +14 -0
- package/dist/model-discovery-shared.js +50 -15
- package/dist/model-discovery-types.d.ts +2 -0
- package/dist/model-discovery.js +219 -117
- package/dist/models.d.ts +14 -1
- package/dist/models.js +75 -19
- package/dist/native-tool-policy.d.ts +29 -0
- package/dist/native-tool-policy.js +36 -0
- package/dist/opencode-log.js +46 -30
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +3 -3
- package/dist/providers/aihubmix.js +13 -18
- package/dist/providers/anthropic-messages.d.ts +7 -0
- package/dist/providers/anthropic-messages.js +45 -21
- package/dist/providers/azure-chat.d.ts +5 -0
- package/dist/providers/azure-chat.js +13 -5
- package/dist/providers/connection-guard.d.ts +2 -45
- package/dist/providers/connection-guard.js +11 -10
- package/dist/providers/connection-test.d.ts +4 -0
- package/dist/providers/connection-test.js +127 -110
- package/dist/providers/elevenlabs.js +4 -1
- package/dist/providers/google-messages.d.ts +7 -0
- package/dist/providers/google-messages.js +69 -23
- package/dist/providers/google-schema.js +17 -23
- package/dist/providers/model-catalog.js +160 -145
- package/dist/providers/oauth-callback-server.js +37 -34
- package/dist/providers/oauth-credentials.js +23 -23
- package/dist/providers/oauth-tokens.js +16 -24
- package/dist/providers/openai-chat.d.ts +42 -0
- package/dist/providers/openai-chat.js +80 -10
- package/dist/providers/operation-schema.d.ts +25 -0
- package/dist/providers/operation-schema.js +226 -0
- package/dist/providers/response-text.d.ts +10 -0
- package/dist/providers/response-text.js +23 -0
- package/dist/providers/tool-turn-types.d.ts +35 -9
- package/dist/providers/tool-turn.d.ts +7 -0
- package/dist/providers/tool-turn.js +113 -32
- package/dist/qoder-stream.js +93 -80
- package/dist/registry.d.ts +45 -0
- package/dist/registry.js +39 -0
- package/dist/runtime-state.d.ts +1 -1
- package/dist/types.d.ts +43 -1
- package/package.json +16 -7
- package/dist/defs/gemini.d.ts +0 -24
- package/dist/defs/gemini.js +0 -81
|
@@ -1,6 +1,37 @@
|
|
|
1
|
+
/** @module json-event-stream
|
|
2
|
+
* Multi-CLI JSON event parsing with per-handler stream state. */
|
|
3
|
+
import { sanitizeUntrustedText } from '@jini-ai/core/text';
|
|
1
4
|
function isRecord(value) {
|
|
2
5
|
return value != null && typeof value === 'object' && !Array.isArray(value);
|
|
3
6
|
}
|
|
7
|
+
function nonEmptyString(value) {
|
|
8
|
+
return typeof value === 'string' && value ? value : null;
|
|
9
|
+
}
|
|
10
|
+
function trimmedNonBlank(value) {
|
|
11
|
+
const trimmed = typeof value === 'string' ? value.trim() : '';
|
|
12
|
+
return trimmed || null;
|
|
13
|
+
}
|
|
14
|
+
function optionalString(value) {
|
|
15
|
+
return typeof value === 'string' ? value : undefined;
|
|
16
|
+
}
|
|
17
|
+
function optionalNumber(value) {
|
|
18
|
+
return typeof value === 'number' ? value : undefined;
|
|
19
|
+
}
|
|
20
|
+
/** Copies the numeric vendor counters named in `fields` into a `Usage`, skipping absent ones. */
|
|
21
|
+
function pickUsage(source, fields) {
|
|
22
|
+
const usage = {};
|
|
23
|
+
for (const [from, to] of fields) {
|
|
24
|
+
const value = source[from];
|
|
25
|
+
if (typeof value === 'number')
|
|
26
|
+
usage[to] = value;
|
|
27
|
+
}
|
|
28
|
+
return usage;
|
|
29
|
+
}
|
|
30
|
+
/** Routes a record frame to the handler registered for its `type`; unknown types are unhandled. */
|
|
31
|
+
function dispatchFrame(handlers, obj, onEvent, state) {
|
|
32
|
+
const handler = handlers.get(obj.type);
|
|
33
|
+
return handler ? handler(obj, onEvent, state) : false;
|
|
34
|
+
}
|
|
4
35
|
function safeParseJson(value) {
|
|
5
36
|
if (value == null)
|
|
6
37
|
return null;
|
|
@@ -60,302 +91,311 @@ function extractConnectorApiError(value) {
|
|
|
60
91
|
function connectorToolSelectionErrorMessage(content) {
|
|
61
92
|
if (!content.includes('CONNECTOR_TOOL_NOT_FOUND'))
|
|
62
93
|
return null;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (parsedError?.code === 'CONNECTOR_TOOL_NOT_FOUND') {
|
|
67
|
-
error = parsedError;
|
|
68
|
-
break;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
94
|
+
const error = parseJsonObjectsFromContent(content)
|
|
95
|
+
.map(extractConnectorApiError)
|
|
96
|
+
.find((parsedError) => parsedError?.code === 'CONNECTOR_TOOL_NOT_FOUND');
|
|
71
97
|
if (!error)
|
|
72
98
|
return null;
|
|
73
99
|
const details = isRecord(error.details) ? error.details : {};
|
|
74
|
-
const connectorId =
|
|
75
|
-
|
|
76
|
-
: undefined;
|
|
77
|
-
const toolName = typeof details.toolName === 'string' && details.toolName
|
|
78
|
-
? details.toolName
|
|
79
|
-
: 'the requested connector tool';
|
|
100
|
+
const connectorId = nonEmptyString(details.connectorId);
|
|
101
|
+
const toolName = nonEmptyString(details.toolName) ?? 'the requested connector tool';
|
|
80
102
|
const target = connectorId
|
|
81
103
|
? `Connector tool ${toolName} is not allowed for connector ${connectorId}.`
|
|
82
104
|
: `Connector tool ${toolName} is not allowed.`;
|
|
83
105
|
return `${target} Re-list the connector catalog and choose one of the currently allowed read-only tools.`;
|
|
84
106
|
}
|
|
107
|
+
function isNonNullObject(value) {
|
|
108
|
+
return value !== null && typeof value === 'object';
|
|
109
|
+
}
|
|
110
|
+
/** Unwrap string/record error envelopes, retaining string or numeric codes alongside messages. */
|
|
85
111
|
function extractErrorMessage(value, fallback) {
|
|
86
112
|
if (typeof value === 'string') {
|
|
87
113
|
const parsed = safeParseJson(value);
|
|
88
|
-
|
|
89
|
-
return extractErrorMessage(parsed, value);
|
|
90
|
-
}
|
|
91
|
-
return value;
|
|
92
|
-
}
|
|
93
|
-
if (isRecord(value)) {
|
|
94
|
-
if (typeof value.detail === 'string' && value.detail)
|
|
95
|
-
return value.detail;
|
|
96
|
-
if (typeof value.message === 'string' && value.message) {
|
|
97
|
-
return extractErrorMessage(value.message, value.message);
|
|
98
|
-
}
|
|
99
|
-
if (typeof value.error === 'string' && value.error)
|
|
100
|
-
return value.error;
|
|
101
|
-
if (value.error && typeof value.error === 'object') {
|
|
102
|
-
return extractErrorMessage(value.error, fallback);
|
|
103
|
-
}
|
|
104
|
-
if (value.data && typeof value.data === 'object') {
|
|
105
|
-
const dataMessage = extractErrorMessage(value.data, '');
|
|
106
|
-
if (dataMessage)
|
|
107
|
-
return dataMessage;
|
|
108
|
-
}
|
|
109
|
-
if (typeof value.name === 'string' && value.name)
|
|
110
|
-
return value.name;
|
|
114
|
+
return isNonNullObject(parsed) ? extractErrorMessage(parsed, value) : value;
|
|
111
115
|
}
|
|
112
|
-
|
|
116
|
+
if (!isRecord(value))
|
|
117
|
+
return fallback;
|
|
118
|
+
const message = extractRecordErrorMessage(value, '');
|
|
119
|
+
const code = typeof value.code === 'number' ? String(value.code) : trimmedNonBlank(value.code);
|
|
120
|
+
return (code ? [code, message].filter(Boolean).join(': ') : message) || fallback;
|
|
121
|
+
}
|
|
122
|
+
/** Field precedence for an error object: detail, message (itself maybe JSON), error, data, name. */
|
|
123
|
+
function extractRecordErrorMessage(value, fallback) {
|
|
124
|
+
const detail = nonEmptyString(value.detail);
|
|
125
|
+
if (detail)
|
|
126
|
+
return detail;
|
|
127
|
+
const message = nonEmptyString(value.message);
|
|
128
|
+
if (message)
|
|
129
|
+
return extractErrorMessage(message, message);
|
|
130
|
+
const error = nonEmptyString(value.error);
|
|
131
|
+
if (error)
|
|
132
|
+
return error;
|
|
133
|
+
if (isNonNullObject(value.error))
|
|
134
|
+
return extractErrorMessage(value.error, fallback);
|
|
135
|
+
const dataMessage = isNonNullObject(value.data) ? extractErrorMessage(value.data, '') : '';
|
|
136
|
+
return dataMessage || nonEmptyString(value.name) || fallback;
|
|
113
137
|
}
|
|
114
138
|
function isRecoverableCodexReconnect(message) {
|
|
115
139
|
return (message.startsWith('Reconnecting...') &&
|
|
116
140
|
(message.includes('timeout waiting for child process to exit') ||
|
|
117
141
|
message.includes('stream disconnected before completion')));
|
|
118
142
|
}
|
|
143
|
+
const OPENCODE_USAGE_FIELDS = [
|
|
144
|
+
['input', 'input_tokens'],
|
|
145
|
+
['output', 'output_tokens'],
|
|
146
|
+
['reasoning', 'thought_tokens'],
|
|
147
|
+
];
|
|
148
|
+
const OPENCODE_CACHE_USAGE_FIELDS = [
|
|
149
|
+
['read', 'cached_read_tokens'],
|
|
150
|
+
['write', 'cached_write_tokens'],
|
|
151
|
+
];
|
|
119
152
|
function formatOpenCodeUsage(tokens) {
|
|
120
153
|
if (!isRecord(tokens))
|
|
121
154
|
return null;
|
|
122
|
-
const usage = {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
usage.output_tokens = tokens.output;
|
|
127
|
-
if (typeof tokens.reasoning === 'number')
|
|
128
|
-
usage.thought_tokens = tokens.reasoning;
|
|
129
|
-
if (isRecord(tokens.cache)) {
|
|
130
|
-
if (typeof tokens.cache.read === 'number')
|
|
131
|
-
usage.cached_read_tokens = tokens.cache.read;
|
|
132
|
-
if (typeof tokens.cache.write === 'number')
|
|
133
|
-
usage.cached_write_tokens = tokens.cache.write;
|
|
134
|
-
}
|
|
155
|
+
const usage = {
|
|
156
|
+
...pickUsage(tokens, OPENCODE_USAGE_FIELDS),
|
|
157
|
+
...(isRecord(tokens.cache) ? pickUsage(tokens.cache, OPENCODE_CACHE_USAGE_FIELDS) : {}),
|
|
158
|
+
};
|
|
135
159
|
return Object.keys(usage).length > 0 ? usage : null;
|
|
136
160
|
}
|
|
137
|
-
function
|
|
138
|
-
|
|
161
|
+
function openCodePart(obj) {
|
|
162
|
+
return isRecord(obj.part) ? obj.part : {};
|
|
163
|
+
}
|
|
164
|
+
function handleOpenCodeStepStart(obj, onEvent) {
|
|
165
|
+
// `sessionID` is OpenCode's own session handle (capture-style resume).
|
|
166
|
+
// Surface it on the step-start status so the daemon can persist it to
|
|
167
|
+
// `agent_sessions` and replay it as `run -s <id>` next turn. OpenCode
|
|
168
|
+
// stamps it on every stream event; step_start is the turn opener, so a
|
|
169
|
+
// create turn always exposes it here.
|
|
170
|
+
onEvent({ type: 'status', label: 'running', sessionId: nonEmptyString(obj.sessionID) });
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
function handleOpenCodeText(obj, onEvent) {
|
|
174
|
+
const text = nonEmptyString(openCodePart(obj).text);
|
|
175
|
+
if (!text)
|
|
139
176
|
return false;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
// `sessionID` is OpenCode's own session handle (capture-style resume).
|
|
143
|
-
// Surface it on the step-start status so the daemon can persist it to
|
|
144
|
-
// `agent_sessions` and replay it as `run -s <id>` next turn. OpenCode
|
|
145
|
-
// stamps it on every stream event; step_start is the turn opener, so a
|
|
146
|
-
// create turn always exposes it here.
|
|
147
|
-
const sessionId = typeof obj.sessionID === 'string' && obj.sessionID.length > 0
|
|
148
|
-
? obj.sessionID
|
|
149
|
-
: null;
|
|
150
|
-
onEvent({ type: 'status', label: 'running', sessionId });
|
|
151
|
-
return true;
|
|
152
|
-
}
|
|
153
|
-
if (obj.type === 'text' && typeof part.text === 'string' && part.text.length > 0) {
|
|
154
|
-
onEvent({ type: 'text_delta', delta: part.text });
|
|
155
|
-
return true;
|
|
156
|
-
}
|
|
157
|
-
if (obj.type === 'tool_use' && typeof part.tool === 'string' && typeof part.callID === 'string') {
|
|
158
|
-
const statePart = isRecord(part.state) ? part.state : null;
|
|
159
|
-
const key = `${obj.sessionID || 'session'}:${part.callID}`;
|
|
160
|
-
if (!state.openCodeToolUses.has(key)) {
|
|
161
|
-
state.openCodeToolUses.add(key);
|
|
162
|
-
onEvent({
|
|
163
|
-
type: 'tool_use',
|
|
164
|
-
id: part.callID,
|
|
165
|
-
name: part.tool,
|
|
166
|
-
input: safeParseJson(statePart?.input) ?? statePart?.input ?? null,
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
if (statePart?.status === 'completed') {
|
|
170
|
-
onEvent({
|
|
171
|
-
type: 'tool_result',
|
|
172
|
-
toolUseId: part.callID,
|
|
173
|
-
content: stringifyContent(statePart.output),
|
|
174
|
-
isError: false,
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
return true;
|
|
178
|
-
}
|
|
179
|
-
if (obj.type === 'step_finish') {
|
|
180
|
-
const usage = formatOpenCodeUsage(part.tokens);
|
|
181
|
-
if (usage) {
|
|
182
|
-
onEvent({
|
|
183
|
-
type: 'usage',
|
|
184
|
-
usage,
|
|
185
|
-
costUsd: typeof part.cost === 'number' ? part.cost : undefined,
|
|
186
|
-
});
|
|
187
|
-
}
|
|
188
|
-
return true;
|
|
189
|
-
}
|
|
190
|
-
if (obj.type === 'error') {
|
|
191
|
-
// OpenCode emits structured error frames on stdout (e.g. provider auth
|
|
192
|
-
// failures, network errors, schema mismatches) and still exits 0. Surface
|
|
193
|
-
// them as proper `error` events so server.ts's `sendAgentEvent` wrapper
|
|
194
|
-
// can flip the run to `failed` and forward a visible SSE error to the
|
|
195
|
-
// chat UI. Previously we downgraded these to `type:'raw'`, which is not
|
|
196
|
-
// rendered as an assistant message — the run looked like a fast clean
|
|
197
|
-
// success while the user actually got nothing back. See issue #691.
|
|
198
|
-
//
|
|
199
|
-
// Shape mirrors the qoder-stream contract (`{type, message, raw}`) so
|
|
200
|
-
// the daemon's existing error-handling path recognises it without
|
|
201
|
-
// further wiring.
|
|
202
|
-
const message = extractErrorMessage(obj.error ?? obj.message, 'OpenCode error');
|
|
203
|
-
onEvent({ type: 'error', message, raw: stringifyContent(obj) });
|
|
204
|
-
return true;
|
|
205
|
-
}
|
|
206
|
-
return false;
|
|
177
|
+
onEvent({ type: 'text_delta', delta: text });
|
|
178
|
+
return true;
|
|
207
179
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
if (
|
|
180
|
+
function handleOpenCodeToolUse(obj, onEvent, state) {
|
|
181
|
+
const part = openCodePart(obj);
|
|
182
|
+
if (typeof part.tool !== 'string' || typeof part.callID !== 'string')
|
|
211
183
|
return false;
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
184
|
+
const statePart = isRecord(part.state) ? part.state : {};
|
|
185
|
+
const key = `${obj.sessionID || 'session'}:${part.callID}`;
|
|
186
|
+
if (!state.openCodeToolUses.has(key)) {
|
|
187
|
+
state.openCodeToolUses.add(key);
|
|
188
|
+
onEvent({
|
|
189
|
+
type: 'tool_use',
|
|
190
|
+
id: part.callID,
|
|
191
|
+
name: part.tool,
|
|
192
|
+
input: safeParseJson(statePart.input) ?? statePart.input ?? null,
|
|
193
|
+
});
|
|
218
194
|
}
|
|
219
|
-
if (
|
|
195
|
+
if (statePart.status === 'completed') {
|
|
220
196
|
onEvent({
|
|
221
|
-
type: '
|
|
222
|
-
|
|
223
|
-
|
|
197
|
+
type: 'tool_result',
|
|
198
|
+
toolUseId: part.callID,
|
|
199
|
+
content: stringifyContent(statePart.output),
|
|
200
|
+
isError: false,
|
|
224
201
|
});
|
|
225
|
-
return true;
|
|
226
202
|
}
|
|
227
|
-
|
|
228
|
-
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
function handleOpenCodeStepFinish(obj, onEvent) {
|
|
206
|
+
const part = openCodePart(obj);
|
|
207
|
+
const usage = formatOpenCodeUsage(part.tokens);
|
|
208
|
+
if (usage) {
|
|
209
|
+
onEvent({ type: 'usage', usage, costUsd: optionalNumber(part.cost) });
|
|
229
210
|
}
|
|
230
|
-
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
function handleOpenCodeError(obj, onEvent) {
|
|
214
|
+
// OpenCode emits structured error frames on stdout (e.g. provider auth
|
|
215
|
+
// failures, network errors, schema mismatches) and still exits 0. Surface
|
|
216
|
+
// them as proper `error` events so server.ts's `sendAgentEvent` wrapper
|
|
217
|
+
// can flip the run to `failed` and forward a visible SSE error to the
|
|
218
|
+
// chat UI. Previously we downgraded these to `type:'raw'`, which is not
|
|
219
|
+
// rendered as an assistant message — the run looked like a fast clean
|
|
220
|
+
// success while the user actually got nothing back. See issue #691.
|
|
221
|
+
//
|
|
222
|
+
// Shape mirrors the qoder-stream contract (`{type, message, raw}`) so
|
|
223
|
+
// the daemon's existing error-handling path recognises it without
|
|
224
|
+
// further wiring.
|
|
225
|
+
const message = extractErrorMessage(obj.error ?? obj.message, 'OpenCode error');
|
|
226
|
+
onEvent({ type: 'error', message, raw: stringifyContent(obj) });
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
const OPENCODE_FRAME_HANDLERS = new Map([
|
|
230
|
+
['step_start', handleOpenCodeStepStart],
|
|
231
|
+
['text', handleOpenCodeText],
|
|
232
|
+
['tool_use', handleOpenCodeToolUse],
|
|
233
|
+
['step_finish', handleOpenCodeStepFinish],
|
|
234
|
+
['error', handleOpenCodeError],
|
|
235
|
+
]);
|
|
236
|
+
function handleOpenCodeEvent(obj, onEvent, state) {
|
|
237
|
+
if (!isRecord(obj))
|
|
238
|
+
return false;
|
|
239
|
+
return dispatchFrame(OPENCODE_FRAME_HANDLERS, obj, onEvent, state);
|
|
240
|
+
}
|
|
241
|
+
function initializingStatus(obj) {
|
|
242
|
+
return { type: 'status', label: 'initializing', model: optionalString(obj.model) };
|
|
243
|
+
}
|
|
244
|
+
function isGoogleAssistantText(obj) {
|
|
245
|
+
return (obj.type === 'message' &&
|
|
231
246
|
obj.role === 'assistant' &&
|
|
232
247
|
typeof obj.content === 'string' &&
|
|
233
|
-
obj.content.length > 0)
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
248
|
+
obj.content.length > 0);
|
|
249
|
+
}
|
|
250
|
+
function handleGoogleInit(obj, onEvent) {
|
|
251
|
+
onEvent(initializingStatus(obj));
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
function handleGoogleMessage(obj, onEvent, state) {
|
|
255
|
+
if (obj.role === 'user')
|
|
237
256
|
return true;
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
});
|
|
252
|
-
return true;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
if (isFileWriteToolUse(obj.tool_name, input)) {
|
|
256
|
-
state.suppressNextArtifactText = true;
|
|
257
|
-
}
|
|
257
|
+
if (!isGoogleAssistantText(obj))
|
|
258
|
+
return false;
|
|
259
|
+
const delta = stripDuplicateArtifactText(obj.content, state);
|
|
260
|
+
if (delta)
|
|
261
|
+
onEvent({ type: 'text_delta', delta });
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
function handleGoogleToolUse(obj, onEvent, state) {
|
|
265
|
+
if (typeof obj.tool_id !== 'string' || typeof obj.tool_name !== 'string')
|
|
266
|
+
return false;
|
|
267
|
+
const input = safeParseJson(obj.parameters) ?? obj.parameters ?? null;
|
|
268
|
+
const todoInput = obj.tool_name === 'write_todos' ? todoWriteInputFromParsedValue(input) : null;
|
|
269
|
+
if (todoInput) {
|
|
258
270
|
onEvent({
|
|
259
271
|
type: 'tool_use',
|
|
260
|
-
id: obj.tool_id
|
|
261
|
-
name:
|
|
262
|
-
input,
|
|
272
|
+
id: `${obj.tool_id}:todo-native`,
|
|
273
|
+
name: 'TodoWrite',
|
|
274
|
+
input: todoInput,
|
|
263
275
|
});
|
|
264
276
|
return true;
|
|
265
277
|
}
|
|
266
|
-
if (obj.
|
|
267
|
-
|
|
268
|
-
const errorMessage = error ? extractErrorMessage(error, '') : '';
|
|
269
|
-
const output = typeof obj.output === 'string'
|
|
270
|
-
? obj.output
|
|
271
|
-
: errorMessage || stringifyContent(obj.output);
|
|
272
|
-
onEvent({
|
|
273
|
-
type: 'tool_result',
|
|
274
|
-
toolUseId: obj.tool_id,
|
|
275
|
-
content: output,
|
|
276
|
-
isError: obj.status === 'error' || Boolean(error),
|
|
277
|
-
});
|
|
278
|
-
return true;
|
|
278
|
+
if (isFileWriteToolUse(obj.tool_name, input)) {
|
|
279
|
+
state.suppressNextArtifactText = true;
|
|
279
280
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
281
|
+
onEvent({
|
|
282
|
+
type: 'tool_use',
|
|
283
|
+
id: obj.tool_id,
|
|
284
|
+
name: obj.tool_name,
|
|
285
|
+
input,
|
|
286
|
+
});
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
function handleGoogleToolResult(obj, onEvent) {
|
|
290
|
+
if (typeof obj.tool_id !== 'string')
|
|
291
|
+
return false;
|
|
292
|
+
const error = isRecord(obj.error) ? obj.error : null;
|
|
293
|
+
const errorMessage = error ? extractErrorMessage(error, '') : '';
|
|
294
|
+
const output = typeof obj.output === 'string'
|
|
295
|
+
? obj.output
|
|
296
|
+
: errorMessage || stringifyContent(obj.output);
|
|
297
|
+
onEvent({
|
|
298
|
+
type: 'tool_result',
|
|
299
|
+
toolUseId: obj.tool_id,
|
|
300
|
+
content: output,
|
|
301
|
+
isError: obj.status === 'error' || Boolean(error),
|
|
302
|
+
});
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
function handleGoogleError(obj, onEvent) {
|
|
306
|
+
const severity = typeof obj.severity === 'string' ? obj.severity.toLowerCase() : '';
|
|
307
|
+
const message = extractErrorMessage(obj.message ?? obj.error, severity === 'warning' ? 'Google stream warning' : 'Google stream error');
|
|
308
|
+
if (severity === 'warning') {
|
|
309
|
+
onEvent({ type: 'status', label: 'warning', detail: message });
|
|
290
310
|
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
if (typeof obj.stats.input_tokens === 'number')
|
|
304
|
-
usage.input_tokens = obj.stats.input_tokens;
|
|
305
|
-
if (typeof obj.stats.output_tokens === 'number')
|
|
306
|
-
usage.output_tokens = obj.stats.output_tokens;
|
|
307
|
-
if (typeof obj.stats.cached === 'number')
|
|
308
|
-
usage.cached_read_tokens = obj.stats.cached;
|
|
311
|
+
else {
|
|
312
|
+
onEvent({ type: 'error', message, raw: stringifyContent(obj) });
|
|
313
|
+
}
|
|
314
|
+
return true;
|
|
315
|
+
}
|
|
316
|
+
const GOOGLE_USAGE_FIELDS = [
|
|
317
|
+
['input_tokens', 'input_tokens'],
|
|
318
|
+
['output_tokens', 'output_tokens'],
|
|
319
|
+
['cached', 'cached_read_tokens'],
|
|
320
|
+
];
|
|
321
|
+
function handleGoogleResult(obj, onEvent) {
|
|
322
|
+
if (obj.status === 'error' || isRecord(obj.error)) {
|
|
309
323
|
onEvent({
|
|
310
|
-
type: '
|
|
311
|
-
|
|
312
|
-
|
|
324
|
+
type: 'error',
|
|
325
|
+
message: extractErrorMessage(obj.error, 'Google stream error'),
|
|
326
|
+
raw: stringifyContent(obj),
|
|
313
327
|
});
|
|
314
328
|
return true;
|
|
315
329
|
}
|
|
316
|
-
|
|
330
|
+
if (!isRecord(obj.stats))
|
|
331
|
+
return true;
|
|
332
|
+
onEvent({
|
|
333
|
+
type: 'usage',
|
|
334
|
+
usage: pickUsage(obj.stats, GOOGLE_USAGE_FIELDS),
|
|
335
|
+
durationMs: optionalNumber(obj.stats.duration_ms),
|
|
336
|
+
});
|
|
337
|
+
return true;
|
|
317
338
|
}
|
|
318
|
-
|
|
339
|
+
const GOOGLE_FRAME_HANDLERS = new Map([
|
|
340
|
+
['init', handleGoogleInit],
|
|
341
|
+
['message', handleGoogleMessage],
|
|
342
|
+
['tool_use', handleGoogleToolUse],
|
|
343
|
+
['tool_result', handleGoogleToolResult],
|
|
344
|
+
['error', handleGoogleError],
|
|
345
|
+
['result', handleGoogleResult],
|
|
346
|
+
]);
|
|
347
|
+
// Retain the neutral legacy wire decoder for stored streams; no CLI agent uses this kind.
|
|
348
|
+
function handleLegacyGoogleStreamEvent(obj, onEvent, state) {
|
|
319
349
|
if (!isRecord(obj))
|
|
320
350
|
return false;
|
|
321
|
-
if (
|
|
322
|
-
|
|
323
|
-
const call = isRecord(rawCall) ? rawCall : null;
|
|
324
|
-
const fn = isRecord(call?.function) ? call.function : null;
|
|
325
|
-
const id = typeof call?.id === 'string' && call.id.trim()
|
|
326
|
-
? call.id.trim()
|
|
327
|
-
: null;
|
|
328
|
-
const name = typeof fn?.name === 'string' && fn.name.trim()
|
|
329
|
-
? fn.name.trim()
|
|
330
|
-
: null;
|
|
331
|
-
if (!id || !name)
|
|
332
|
-
continue;
|
|
333
|
-
const input = safeParseJson(fn?.arguments) ?? fn?.arguments ?? null;
|
|
334
|
-
onEvent({ type: 'tool_use', id, name, input });
|
|
335
|
-
}
|
|
336
|
-
return true;
|
|
337
|
-
}
|
|
338
|
-
if (obj.role === 'tool' &&
|
|
339
|
-
typeof obj.tool_call_id === 'string' &&
|
|
340
|
-
obj.tool_call_id.trim()) {
|
|
341
|
-
onEvent({
|
|
342
|
-
type: 'tool_result',
|
|
343
|
-
toolUseId: obj.tool_call_id.trim(),
|
|
344
|
-
content: stringifyContent(obj.content),
|
|
345
|
-
isError: false,
|
|
346
|
-
});
|
|
347
|
-
return true;
|
|
351
|
+
if (!isGoogleAssistantText(obj)) {
|
|
352
|
+
flushPendingArtifactText(state, onEvent);
|
|
348
353
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
+
return dispatchFrame(GOOGLE_FRAME_HANDLERS, obj, onEvent, state);
|
|
355
|
+
}
|
|
356
|
+
function emitKimiToolCalls(toolCalls, onEvent) {
|
|
357
|
+
for (const rawCall of toolCalls) {
|
|
358
|
+
const call = isRecord(rawCall) ? rawCall : {};
|
|
359
|
+
const fn = isRecord(call.function) ? call.function : {};
|
|
360
|
+
const id = trimmedNonBlank(call.id);
|
|
361
|
+
const name = trimmedNonBlank(fn.name);
|
|
362
|
+
if (!id || !name)
|
|
363
|
+
continue;
|
|
364
|
+
const input = safeParseJson(fn.arguments) ?? fn.arguments ?? null;
|
|
365
|
+
onEvent({ type: 'tool_use', id, name, input });
|
|
354
366
|
}
|
|
355
|
-
|
|
367
|
+
}
|
|
368
|
+
function handleKimiAssistant(obj, onEvent) {
|
|
369
|
+
if (Array.isArray(obj.tool_calls)) {
|
|
370
|
+
emitKimiToolCalls(obj.tool_calls, onEvent);
|
|
356
371
|
return true;
|
|
357
372
|
}
|
|
358
|
-
|
|
373
|
+
const text = nonEmptyString(obj.content);
|
|
374
|
+
if (!text)
|
|
375
|
+
return false;
|
|
376
|
+
onEvent({ type: 'text_delta', delta: text });
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
function handleKimiToolResult(obj, onEvent) {
|
|
380
|
+
const toolUseId = trimmedNonBlank(obj.tool_call_id);
|
|
381
|
+
if (!toolUseId)
|
|
382
|
+
return false;
|
|
383
|
+
onEvent({
|
|
384
|
+
type: 'tool_result',
|
|
385
|
+
toolUseId,
|
|
386
|
+
content: stringifyContent(obj.content),
|
|
387
|
+
isError: false,
|
|
388
|
+
});
|
|
389
|
+
return true;
|
|
390
|
+
}
|
|
391
|
+
function handleKimiEvent(obj, onEvent) {
|
|
392
|
+
if (!isRecord(obj))
|
|
393
|
+
return false;
|
|
394
|
+
if (obj.role === 'assistant')
|
|
395
|
+
return handleKimiAssistant(obj, onEvent);
|
|
396
|
+
if (obj.role === 'tool')
|
|
397
|
+
return handleKimiToolResult(obj, onEvent);
|
|
398
|
+
return obj.role === 'meta' && obj.type === 'session.resume_hint';
|
|
359
399
|
}
|
|
360
400
|
function extractCursorText(message) {
|
|
361
401
|
const content = isRecord(message) ? message.content : undefined;
|
|
@@ -365,29 +405,34 @@ function extractCursorText(message) {
|
|
|
365
405
|
.map((block) => block.text)
|
|
366
406
|
.join('');
|
|
367
407
|
}
|
|
408
|
+
/** Ordered status buckets: the first rule whose exact alias or prefix matches wins; else `pending`. */
|
|
409
|
+
const TODO_STATUS_RULES = [
|
|
410
|
+
{ status: 'completed', exact: ['complete', 'done'], prefixes: ['completed'] },
|
|
411
|
+
{ status: 'in_progress', exact: ['doing', 'active'], prefixes: ['in_progress'] },
|
|
412
|
+
{ status: 'stopped', exact: [], prefixes: ['stopped', 'failed', 'blocked', 'canceled', 'cancelled'] },
|
|
413
|
+
];
|
|
368
414
|
function normalizeTodoStatus(value) {
|
|
369
415
|
const status = typeof value === 'string'
|
|
370
416
|
? value.trim().toLowerCase().replace(/[-\s]+/g, '_')
|
|
371
417
|
: '';
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
if (
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
status.
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
}
|
|
390
|
-
return 'pending';
|
|
418
|
+
const rule = TODO_STATUS_RULES.find((candidate) => candidate.exact.includes(status) || candidate.prefixes.some((prefix) => status.startsWith(prefix)));
|
|
419
|
+
return rule ? rule.status : 'pending';
|
|
420
|
+
}
|
|
421
|
+
/** Todo text fields in precedence order; the first string-typed one wins, even when empty. */
|
|
422
|
+
const TODO_CONTENT_FIELDS = ['content', 'label', 'description', 'text'];
|
|
423
|
+
function todoFromItem(raw) {
|
|
424
|
+
if (!isRecord(raw))
|
|
425
|
+
return null;
|
|
426
|
+
const field = TODO_CONTENT_FIELDS.find((key) => typeof raw[key] === 'string');
|
|
427
|
+
const content = field ? raw[field] : '';
|
|
428
|
+
if (!content)
|
|
429
|
+
return null;
|
|
430
|
+
return {
|
|
431
|
+
content,
|
|
432
|
+
status: raw.completed === true
|
|
433
|
+
? 'completed'
|
|
434
|
+
: normalizeTodoStatus(raw.status),
|
|
435
|
+
};
|
|
391
436
|
}
|
|
392
437
|
// Takes `unknown[]`, not `unknown`: every real call site
|
|
393
438
|
// (`todoWriteInputFromParsedValue`'s three call sites and
|
|
@@ -397,27 +442,7 @@ function normalizeTodoStatus(value) {
|
|
|
397
442
|
// padding a test around unreachable data.
|
|
398
443
|
function todoWriteInputFromItems(items) {
|
|
399
444
|
const todos = items
|
|
400
|
-
.map(
|
|
401
|
-
if (!isRecord(raw))
|
|
402
|
-
return null;
|
|
403
|
-
const content = typeof raw.content === 'string'
|
|
404
|
-
? raw.content
|
|
405
|
-
: typeof raw.label === 'string'
|
|
406
|
-
? raw.label
|
|
407
|
-
: typeof raw.description === 'string'
|
|
408
|
-
? raw.description
|
|
409
|
-
: typeof raw.text === 'string'
|
|
410
|
-
? raw.text
|
|
411
|
-
: '';
|
|
412
|
-
if (!content)
|
|
413
|
-
return null;
|
|
414
|
-
return {
|
|
415
|
-
content,
|
|
416
|
-
status: raw.completed === true
|
|
417
|
-
? 'completed'
|
|
418
|
-
: normalizeTodoStatus(raw.status),
|
|
419
|
-
};
|
|
420
|
-
})
|
|
445
|
+
.map(todoFromItem)
|
|
421
446
|
.filter((todo) => todo !== null);
|
|
422
447
|
return todos.length > 0 ? { todos } : null;
|
|
423
448
|
}
|
|
@@ -528,6 +553,35 @@ function emitCodexTodoList(item, onEvent) {
|
|
|
528
553
|
});
|
|
529
554
|
return true;
|
|
530
555
|
}
|
|
556
|
+
function hasStringId(item) {
|
|
557
|
+
return typeof item.id === 'string';
|
|
558
|
+
}
|
|
559
|
+
/** Marks `key` as emitted in `state.codexToolUses`; `true` only the first time (Codex repeats frames per call). */
|
|
560
|
+
function claimCodexToolUse(state, key) {
|
|
561
|
+
if (state.codexToolUses.has(key))
|
|
562
|
+
return false;
|
|
563
|
+
state.codexToolUses.add(key);
|
|
564
|
+
return true;
|
|
565
|
+
}
|
|
566
|
+
function resetCodexAgentMessageBoundary(state) {
|
|
567
|
+
state.codexPreviousEventWasAgentMessage = false;
|
|
568
|
+
state.codexLastAgentMessageEndedWithNewline = false;
|
|
569
|
+
}
|
|
570
|
+
/** Emits a Codex `error` only for the first error of the stream; later ones are dropped. */
|
|
571
|
+
function emitCodexErrorOnce(message, onEvent, state) {
|
|
572
|
+
if (state.codexErrorEmitted)
|
|
573
|
+
return;
|
|
574
|
+
state.codexErrorEmitted = true;
|
|
575
|
+
onEvent({ type: 'error', message });
|
|
576
|
+
}
|
|
577
|
+
function codexMcpToolName(item) {
|
|
578
|
+
const tool = nonEmptyString(item.tool);
|
|
579
|
+
// Preserve the bridge's catalog names; external MCP must never masquerade as Bash/Edit.
|
|
580
|
+
if (item.server === 'jini')
|
|
581
|
+
return tool ?? 'mcp_tool_call';
|
|
582
|
+
const server = typeof item.server === 'string' ? item.server : 'external';
|
|
583
|
+
return `mcp__${server}__${tool ?? 'call'}`;
|
|
584
|
+
}
|
|
531
585
|
/**
|
|
532
586
|
* Emits the `tool_use` for one `item.type: 'mcp_tool_call'` item, deduped per `item.id` via
|
|
533
587
|
* `state.codexToolUses` (the same dedup `command_execution`'s two call sites — `item.started` and
|
|
@@ -550,19 +604,231 @@ function emitCodexTodoList(item, onEvent) {
|
|
|
550
604
|
* @overallScore 100
|
|
551
605
|
*/
|
|
552
606
|
function emitCodexMcpToolUse(item, onEvent, state) {
|
|
553
|
-
if (item.type !== 'mcp_tool_call' ||
|
|
607
|
+
if (item.type !== 'mcp_tool_call' || !hasStringId(item))
|
|
554
608
|
return false;
|
|
555
|
-
if (
|
|
556
|
-
state.codexToolUses.add(item.id);
|
|
609
|
+
if (claimCodexToolUse(state, item.id)) {
|
|
557
610
|
onEvent({
|
|
558
611
|
type: 'tool_use',
|
|
559
612
|
id: item.id,
|
|
560
|
-
name:
|
|
613
|
+
name: codexMcpToolName(item),
|
|
561
614
|
input: item.arguments ?? {},
|
|
562
615
|
});
|
|
563
616
|
}
|
|
564
617
|
return true;
|
|
565
618
|
}
|
|
619
|
+
function emitCodexBashToolUse(item, onEvent, state) {
|
|
620
|
+
if (!claimCodexToolUse(state, item.id))
|
|
621
|
+
return;
|
|
622
|
+
onEvent({
|
|
623
|
+
type: 'tool_use',
|
|
624
|
+
id: item.id,
|
|
625
|
+
name: 'Bash',
|
|
626
|
+
input: {
|
|
627
|
+
command: typeof item.command === 'string' ? item.command : '',
|
|
628
|
+
},
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
function emitCodexCollabToolCall(item, completed, onEvent, state) {
|
|
632
|
+
if (claimCodexToolUse(state, item.id)) {
|
|
633
|
+
onEvent({ type: 'tool_use', id: item.id,
|
|
634
|
+
name: typeof item.tool === 'string' ? item.tool : 'collab_tool_call', input: {} });
|
|
635
|
+
}
|
|
636
|
+
if (completed && claimCodexToolUse(state, `${item.id}:completed`)) {
|
|
637
|
+
onEvent({ type: 'tool_result', toolUseId: item.id,
|
|
638
|
+
content: 'Native agent action completed.', isError: item.status === 'failed' });
|
|
639
|
+
}
|
|
640
|
+
return true;
|
|
641
|
+
}
|
|
642
|
+
function handleCodexItemStarted(item, onEvent, state) {
|
|
643
|
+
if (emitCodexTodoList(item, onEvent)) {
|
|
644
|
+
resetCodexAgentMessageBoundary(state);
|
|
645
|
+
return true;
|
|
646
|
+
}
|
|
647
|
+
if (item.type === 'command_execution' && hasStringId(item)) {
|
|
648
|
+
resetCodexAgentMessageBoundary(state);
|
|
649
|
+
emitCodexBashToolUse(item, onEvent, state);
|
|
650
|
+
return true;
|
|
651
|
+
}
|
|
652
|
+
if (item.type !== 'mcp_tool_call')
|
|
653
|
+
return false;
|
|
654
|
+
resetCodexAgentMessageBoundary(state);
|
|
655
|
+
return emitCodexMcpToolUse(item, onEvent, state);
|
|
656
|
+
}
|
|
657
|
+
function handleCodexItemUpdated(item, onEvent, state) {
|
|
658
|
+
if (!emitCodexTodoList(item, onEvent))
|
|
659
|
+
return false;
|
|
660
|
+
resetCodexAgentMessageBoundary(state);
|
|
661
|
+
return true;
|
|
662
|
+
}
|
|
663
|
+
function completeCodexFileChange(item, onEvent, state) {
|
|
664
|
+
// Codex reports direct patches as file_change, rather than command_execution. Surface paths
|
|
665
|
+
// through the SAME native-tool event channel so audit sees edits without persisting patches.
|
|
666
|
+
if (!claimCodexToolUse(state, item.id))
|
|
667
|
+
return true;
|
|
668
|
+
const changes = Array.isArray(item.changes) ? item.changes : [];
|
|
669
|
+
onEvent({ type: 'tool_use', id: item.id, name: 'apply_patch',
|
|
670
|
+
input: { paths: changes.filter(isRecord).map(change => change.path).filter(path => typeof path === 'string') } });
|
|
671
|
+
onEvent({ type: 'tool_result', toolUseId: item.id, content: 'File change reported by Codex.', isError: item.status === 'failed' });
|
|
672
|
+
return true;
|
|
673
|
+
}
|
|
674
|
+
function completeCodexCommand(item, onEvent, state) {
|
|
675
|
+
resetCodexAgentMessageBoundary(state);
|
|
676
|
+
emitCodexBashToolUse(item, onEvent, state);
|
|
677
|
+
const content = stringifyContent(item.aggregated_output ?? '');
|
|
678
|
+
onEvent({
|
|
679
|
+
type: 'tool_result',
|
|
680
|
+
toolUseId: item.id,
|
|
681
|
+
content,
|
|
682
|
+
isError: typeof item.exit_code === 'number' ? item.exit_code !== 0 : item.status === 'failed',
|
|
683
|
+
});
|
|
684
|
+
const connectorToolError = connectorToolSelectionErrorMessage(content);
|
|
685
|
+
if (connectorToolError)
|
|
686
|
+
emitCodexErrorOnce(connectorToolError, onEvent, state);
|
|
687
|
+
return true;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Select a failed MCP call's diagnostic without exposing arguments or result metadata.
|
|
691
|
+
* Codex 0.161.0's exec mapper carries result content/structured_content independently of error:
|
|
692
|
+
* https://github.com/openai/codex/blob/rust-v0.161.0/codex-rs/exec/src/event_processor_with_jsonl_output.rs#L195
|
|
693
|
+
* @returns Sanitized error text, or the generic failure when no diagnostic is present.
|
|
694
|
+
* @complexity O(n) time/space for n diagnostic characters, including the shared sanitizer pass.
|
|
695
|
+
*/
|
|
696
|
+
function codexMcpFailureContent({ item }, _options = {}) {
|
|
697
|
+
const error = trimmedNonBlank(extractErrorMessage(item.error, ''));
|
|
698
|
+
const result = isRecord(item.result) ? item.result : {};
|
|
699
|
+
const blocks = Array.isArray(result.content) ? result.content : [];
|
|
700
|
+
// Keep text verbatim until sanitizing so JSON error envelopes retain codes and recovery hints.
|
|
701
|
+
const text = blocks.filter(isRecord)
|
|
702
|
+
.filter(block => block.type === 'text')
|
|
703
|
+
.map(block => trimmedNonBlank(block.text))
|
|
704
|
+
.filter(Boolean)
|
|
705
|
+
.join('\n');
|
|
706
|
+
const structuredText = extractErrorMessage(result.structured_content, '');
|
|
707
|
+
const diagnostic = error || text || trimmedNonBlank(structuredText) || 'MCP tool call failed';
|
|
708
|
+
return sanitizeUntrustedText({ text: diagnostic });
|
|
709
|
+
}
|
|
710
|
+
function completeCodexMcpToolCall(item, onEvent, state) {
|
|
711
|
+
resetCodexAgentMessageBoundary(state);
|
|
712
|
+
// `item.started` normally already emitted the matching `tool_use` (see
|
|
713
|
+
// `emitCodexMcpToolUse`); this call is a no-op then, and only actually emits one for a
|
|
714
|
+
// call whose `item.started` frame this parser never saw (a truncated/mid-stream feed —
|
|
715
|
+
// the same fallback shape `command_execution`'s own `item.completed` branch above uses).
|
|
716
|
+
emitCodexMcpToolUse(item, onEvent, state);
|
|
717
|
+
// A call Codex's own approval gate denies before ever reaching the target MCP server
|
|
718
|
+
// reports back exactly this shape — `status: 'failed'`, `result: null`, an `error` object
|
|
719
|
+
// — which is otherwise indistinguishable from "never happened" downstream: no
|
|
720
|
+
// `tool_use`/`tool_result` pair means no audit row, no error card, nothing an operator or
|
|
721
|
+
// the model itself can ground a claim on. `isError` on `status !== 'completed'` (not a
|
|
722
|
+
// truthiness check on `item.error`) matches every other status branch in this file and
|
|
723
|
+
// stays correct even for a hypothetical future status this union does not name yet.
|
|
724
|
+
const isError = item.status !== 'completed';
|
|
725
|
+
const content = isError
|
|
726
|
+
? codexMcpFailureContent({ item })
|
|
727
|
+
: stringifyContent(item.result);
|
|
728
|
+
onEvent({ type: 'tool_result', toolUseId: item.id, content, isError });
|
|
729
|
+
return true;
|
|
730
|
+
}
|
|
731
|
+
function emitCodexAgentMessage(item, onEvent, state) {
|
|
732
|
+
const text = item.type === 'agent_message' ? nonEmptyString(item.text) : null;
|
|
733
|
+
if (!text)
|
|
734
|
+
return false;
|
|
735
|
+
const needsBoundary = state.codexPreviousEventWasAgentMessage &&
|
|
736
|
+
!state.codexLastAgentMessageEndedWithNewline &&
|
|
737
|
+
!text.startsWith('\n');
|
|
738
|
+
const delta = needsBoundary ? `\n${text}` : text;
|
|
739
|
+
onEvent({ type: 'text_delta', delta });
|
|
740
|
+
state.codexPreviousEventWasAgentMessage = true;
|
|
741
|
+
state.codexLastAgentMessageEndedWithNewline = text.endsWith('\n');
|
|
742
|
+
return true;
|
|
743
|
+
}
|
|
744
|
+
function handleCodexItemCompleted(item, onEvent, state) {
|
|
745
|
+
if (item.type === 'file_change' && hasStringId(item))
|
|
746
|
+
return completeCodexFileChange(item, onEvent, state);
|
|
747
|
+
if (emitCodexTodoList(item, onEvent)) {
|
|
748
|
+
resetCodexAgentMessageBoundary(state);
|
|
749
|
+
return true;
|
|
750
|
+
}
|
|
751
|
+
if (item.type === 'command_execution' && hasStringId(item))
|
|
752
|
+
return completeCodexCommand(item, onEvent, state);
|
|
753
|
+
if (item.type === 'mcp_tool_call' && hasStringId(item))
|
|
754
|
+
return completeCodexMcpToolCall(item, onEvent, state);
|
|
755
|
+
return emitCodexAgentMessage(item, onEvent, state);
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Wraps a per-frame item handler with the checks every `item.*` frame shares: a record `item`, and
|
|
759
|
+
* native `collab_tool_call` items, which report the same way on started/updated/completed.
|
|
760
|
+
*/
|
|
761
|
+
function codexItemFrame(handleItem) {
|
|
762
|
+
return (obj, onEvent, state) => {
|
|
763
|
+
if (!isRecord(obj.item))
|
|
764
|
+
return false;
|
|
765
|
+
const item = obj.item;
|
|
766
|
+
if (item.type === 'collab_tool_call' && hasStringId(item)) {
|
|
767
|
+
return emitCodexCollabToolCall(item, obj.type === 'item.completed', onEvent, state);
|
|
768
|
+
}
|
|
769
|
+
return handleItem(item, onEvent, state);
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
function handleCodexError(obj, onEvent, state) {
|
|
773
|
+
const message = extractErrorMessage(obj.message ?? obj.error, 'Codex error');
|
|
774
|
+
// Reconnecting events are recoverable — treat as status warning, not fatal
|
|
775
|
+
if (isRecoverableCodexReconnect(message)) {
|
|
776
|
+
onEvent({ type: 'status', label: message });
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
emitCodexErrorOnce(message, onEvent, state);
|
|
780
|
+
return true;
|
|
781
|
+
}
|
|
782
|
+
function handleCodexTurnFailed(obj, onEvent, state) {
|
|
783
|
+
emitCodexErrorOnce(extractErrorMessage(obj.error ?? obj.message, 'Codex turn failed'), onEvent, state);
|
|
784
|
+
return true;
|
|
785
|
+
}
|
|
786
|
+
function handleCodexThreadStarted(obj, onEvent) {
|
|
787
|
+
// `thread_id` is Codex's own session handle, surfaced on the same
|
|
788
|
+
// `sessionId` status channel claude uses (claude-stream.ts). It serves two
|
|
789
|
+
// consumers: (1) the daemon persists it to `agent_sessions` and replays it
|
|
790
|
+
// as `exec resume <thread_id>` on the next turn (capture-style resume), and
|
|
791
|
+
// (2) it identifies this run's rollout file
|
|
792
|
+
// (`$CODEX_HOME/sessions/**/rollout-*-<thread_id>.jsonl`), the only place
|
|
793
|
+
// codex records per-call usage, which run_finished reads to recover the
|
|
794
|
+
// turn's first-call cache hit (codex's stream usage is cumulative only).
|
|
795
|
+
// Codex emits this both for a fresh `exec` and for `exec resume` (echoing
|
|
796
|
+
// the resumed id), so it is a stable capture point either way.
|
|
797
|
+
onEvent({ type: 'status', label: 'initializing', sessionId: nonEmptyString(obj.thread_id) });
|
|
798
|
+
return true;
|
|
799
|
+
}
|
|
800
|
+
function handleCodexTurnStarted(_obj, onEvent, state) {
|
|
801
|
+
resetCodexAgentMessageBoundary(state);
|
|
802
|
+
onEvent({ type: 'status', label: 'thinking' });
|
|
803
|
+
return true;
|
|
804
|
+
}
|
|
805
|
+
const CODEX_USAGE_FIELDS = [
|
|
806
|
+
['input_tokens', 'input_tokens'],
|
|
807
|
+
['output_tokens', 'output_tokens'],
|
|
808
|
+
['reasoning_output_tokens', 'thought_tokens'],
|
|
809
|
+
['cached_input_tokens', 'cached_read_tokens'],
|
|
810
|
+
];
|
|
811
|
+
function handleCodexTurnCompleted(obj, onEvent) {
|
|
812
|
+
if (!isRecord(obj.usage))
|
|
813
|
+
return false;
|
|
814
|
+
onEvent({ type: 'usage', usage: pickUsage(obj.usage, CODEX_USAGE_FIELDS) });
|
|
815
|
+
return true;
|
|
816
|
+
}
|
|
817
|
+
const CODEX_FRAME_HANDLERS = new Map([
|
|
818
|
+
['error', handleCodexError],
|
|
819
|
+
['turn.failed', handleCodexTurnFailed],
|
|
820
|
+
['thread.started', handleCodexThreadStarted],
|
|
821
|
+
['turn.started', handleCodexTurnStarted],
|
|
822
|
+
['item.started', codexItemFrame(handleCodexItemStarted)],
|
|
823
|
+
['item.updated', codexItemFrame(handleCodexItemUpdated)],
|
|
824
|
+
['item.completed', codexItemFrame(handleCodexItemCompleted)],
|
|
825
|
+
['turn.completed', handleCodexTurnCompleted],
|
|
826
|
+
]);
|
|
827
|
+
function handleCodexEvent(obj, onEvent, state) {
|
|
828
|
+
if (!isRecord(obj))
|
|
829
|
+
return false;
|
|
830
|
+
return dispatchFrame(CODEX_FRAME_HANDLERS, obj, onEvent, state);
|
|
831
|
+
}
|
|
566
832
|
function emitCursorTextDelta(text, onEvent, state) {
|
|
567
833
|
// Timestamped assistant events WITHOUT `model_call_id` are cursor-agent's
|
|
568
834
|
// real-time incremental deltas (`--stream-partial-output`): the final turn
|
|
@@ -575,7 +841,7 @@ function emitCursorTextDelta(text, onEvent, state) {
|
|
|
575
841
|
// (`model_call_id` and no-timestamp events) via reconcileCursorTurnReplay.
|
|
576
842
|
//
|
|
577
843
|
// No `!text` guard: this function's only real call site
|
|
578
|
-
// (`
|
|
844
|
+
// (`handleCursorAssistant`, below) already returns early on `if (!text) return
|
|
579
845
|
// false;` before ever calling in, so `text` is always non-empty here. The
|
|
580
846
|
// guard was dead code for the one real caller; removed rather than padded
|
|
581
847
|
// with a test.
|
|
@@ -607,240 +873,77 @@ function reconcileCursorTurnReplay(text, onEvent, state) {
|
|
|
607
873
|
}
|
|
608
874
|
state.cursorTurnStart = state.cursorTextSoFar.length;
|
|
609
875
|
}
|
|
876
|
+
function handleCursorAssistant(obj, onEvent, state) {
|
|
877
|
+
// Cursor sends a final assistant message that replays the full text for
|
|
878
|
+
// the current turn — either tagged with `model_call_id`, or (fallback)
|
|
879
|
+
// as a non-timestamped terminal assistant message. Both are reconciled
|
|
880
|
+
// against the current turn's emitted text via reconcileCursorTurnReplay.
|
|
881
|
+
const text = extractCursorText(obj.message);
|
|
882
|
+
if (typeof obj.model_call_id === 'string') {
|
|
883
|
+
reconcileCursorTurnReplay(text, onEvent, state);
|
|
884
|
+
return true;
|
|
885
|
+
}
|
|
886
|
+
if (!text)
|
|
887
|
+
return false;
|
|
888
|
+
if (typeof obj.timestamp_ms === 'number') {
|
|
889
|
+
// Incremental streaming chunk within a turn — accumulate as usual.
|
|
890
|
+
emitCursorTextDelta(text, onEvent, state);
|
|
891
|
+
return true;
|
|
892
|
+
}
|
|
893
|
+
// Non-timestamped final assistant message: a terminal replay that marks a
|
|
894
|
+
// turn boundary. Reconcile against the current turn (not the whole
|
|
895
|
+
// cross-turn buffer) so later fallback-terminated turns do not duplicate
|
|
896
|
+
// output, then advance the turn boundary.
|
|
897
|
+
reconcileCursorTurnReplay(text, onEvent, state);
|
|
898
|
+
return true;
|
|
899
|
+
}
|
|
900
|
+
const CURSOR_USAGE_FIELDS = [
|
|
901
|
+
['inputTokens', 'input_tokens'],
|
|
902
|
+
['outputTokens', 'output_tokens'],
|
|
903
|
+
['cacheReadTokens', 'cached_read_tokens'],
|
|
904
|
+
['cacheWriteTokens', 'cached_write_tokens'],
|
|
905
|
+
];
|
|
610
906
|
function handleCursorEvent(obj, onEvent, state) {
|
|
611
907
|
if (!isRecord(obj))
|
|
612
908
|
return false;
|
|
613
909
|
if (obj.type === 'system' && obj.subtype === 'init') {
|
|
614
|
-
onEvent(
|
|
615
|
-
type: 'status',
|
|
616
|
-
label: 'initializing',
|
|
617
|
-
model: typeof obj.model === 'string' ? obj.model : undefined,
|
|
618
|
-
});
|
|
619
|
-
return true;
|
|
620
|
-
}
|
|
621
|
-
if (obj.type === 'assistant' && obj.message) {
|
|
622
|
-
// Cursor sends a final assistant message that replays the full text for
|
|
623
|
-
// the current turn — either tagged with `model_call_id`, or (fallback)
|
|
624
|
-
// as a non-timestamped terminal assistant message. Both are reconciled
|
|
625
|
-
// against the current turn's emitted text via reconcileCursorTurnReplay.
|
|
626
|
-
if (typeof obj.model_call_id === 'string') {
|
|
627
|
-
const text = extractCursorText(obj.message);
|
|
628
|
-
reconcileCursorTurnReplay(text, onEvent, state);
|
|
629
|
-
return true;
|
|
630
|
-
}
|
|
631
|
-
const text = extractCursorText(obj.message);
|
|
632
|
-
if (!text)
|
|
633
|
-
return false;
|
|
634
|
-
if (typeof obj.timestamp_ms === 'number') {
|
|
635
|
-
// Incremental streaming chunk within a turn — accumulate as usual.
|
|
636
|
-
emitCursorTextDelta(text, onEvent, state);
|
|
637
|
-
return true;
|
|
638
|
-
}
|
|
639
|
-
// Non-timestamped final assistant message: a terminal replay that marks a
|
|
640
|
-
// turn boundary. Reconcile against the current turn (not the whole
|
|
641
|
-
// cross-turn buffer) so later fallback-terminated turns do not duplicate
|
|
642
|
-
// output, then advance the turn boundary.
|
|
643
|
-
reconcileCursorTurnReplay(text, onEvent, state);
|
|
910
|
+
onEvent(initializingStatus(obj));
|
|
644
911
|
return true;
|
|
645
912
|
}
|
|
913
|
+
if (obj.type === 'assistant' && obj.message)
|
|
914
|
+
return handleCursorAssistant(obj, onEvent, state);
|
|
646
915
|
if (obj.type === 'result' && isRecord(obj.usage)) {
|
|
647
|
-
const usage = {};
|
|
648
|
-
if (typeof obj.usage.inputTokens === 'number')
|
|
649
|
-
usage.input_tokens = obj.usage.inputTokens;
|
|
650
|
-
if (typeof obj.usage.outputTokens === 'number')
|
|
651
|
-
usage.output_tokens = obj.usage.outputTokens;
|
|
652
|
-
if (typeof obj.usage.cacheReadTokens === 'number') {
|
|
653
|
-
usage.cached_read_tokens = obj.usage.cacheReadTokens;
|
|
654
|
-
}
|
|
655
|
-
if (typeof obj.usage.cacheWriteTokens === 'number') {
|
|
656
|
-
usage.cached_write_tokens = obj.usage.cacheWriteTokens;
|
|
657
|
-
}
|
|
658
916
|
onEvent({
|
|
659
917
|
type: 'usage',
|
|
660
|
-
usage,
|
|
661
|
-
durationMs:
|
|
918
|
+
usage: pickUsage(obj.usage, CURSOR_USAGE_FIELDS),
|
|
919
|
+
durationMs: optionalNumber(obj.duration_ms),
|
|
662
920
|
});
|
|
663
921
|
return true;
|
|
664
922
|
}
|
|
665
923
|
return false;
|
|
666
924
|
}
|
|
667
|
-
|
|
925
|
+
const MODEL_RECEIPT_FRAME_TYPES = new Set(['session.created', 'thread.started', 'turn.started', 'model.changed']);
|
|
926
|
+
// Preserve structured model receipts before vendor event translation. These fields describe
|
|
927
|
+
// session/turn/assistant-message metadata; generated text is never used for model identity.
|
|
928
|
+
function emitModelReceipts(obj, onEvent) {
|
|
668
929
|
if (!isRecord(obj))
|
|
669
|
-
return
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
onEvent({ type: 'status', label: message });
|
|
675
|
-
return true;
|
|
676
|
-
}
|
|
677
|
-
if (!state.codexErrorEmitted) {
|
|
678
|
-
state.codexErrorEmitted = true;
|
|
679
|
-
onEvent({ type: 'error', message });
|
|
680
|
-
}
|
|
681
|
-
return true;
|
|
682
|
-
}
|
|
683
|
-
if (obj.type === 'turn.failed') {
|
|
684
|
-
if (!state.codexErrorEmitted) {
|
|
685
|
-
state.codexErrorEmitted = true;
|
|
686
|
-
onEvent({
|
|
687
|
-
type: 'error',
|
|
688
|
-
message: extractErrorMessage(obj.error ?? obj.message, 'Codex turn failed'),
|
|
689
|
-
});
|
|
690
|
-
}
|
|
691
|
-
return true;
|
|
692
|
-
}
|
|
693
|
-
if (obj.type === 'thread.started') {
|
|
694
|
-
// `thread_id` is Codex's own session handle, surfaced on the same
|
|
695
|
-
// `sessionId` status channel claude uses (claude-stream.ts). It serves two
|
|
696
|
-
// consumers: (1) the daemon persists it to `agent_sessions` and replays it
|
|
697
|
-
// as `exec resume <thread_id>` on the next turn (capture-style resume), and
|
|
698
|
-
// (2) it identifies this run's rollout file
|
|
699
|
-
// (`$CODEX_HOME/sessions/**/rollout-*-<thread_id>.jsonl`), the only place
|
|
700
|
-
// codex records per-call usage, which run_finished reads to recover the
|
|
701
|
-
// turn's first-call cache hit (codex's stream usage is cumulative only).
|
|
702
|
-
// Codex emits this both for a fresh `exec` and for `exec resume` (echoing
|
|
703
|
-
// the resumed id), so it is a stable capture point either way.
|
|
704
|
-
const threadId = typeof obj.thread_id === 'string' && obj.thread_id.length > 0
|
|
705
|
-
? obj.thread_id
|
|
706
|
-
: null;
|
|
707
|
-
onEvent({ type: 'status', label: 'initializing', sessionId: threadId });
|
|
708
|
-
return true;
|
|
709
|
-
}
|
|
710
|
-
if (obj.type === 'turn.started') {
|
|
711
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
712
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
713
|
-
onEvent({ type: 'status', label: 'thinking' });
|
|
714
|
-
return true;
|
|
715
|
-
}
|
|
716
|
-
if (obj.type === 'item.started' && isRecord(obj.item)) {
|
|
717
|
-
const item = obj.item;
|
|
718
|
-
if (emitCodexTodoList(item, onEvent)) {
|
|
719
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
720
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
721
|
-
return true;
|
|
722
|
-
}
|
|
723
|
-
if (item.type === 'command_execution' && typeof item.id === 'string') {
|
|
724
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
725
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
726
|
-
if (!state.codexToolUses.has(item.id)) {
|
|
727
|
-
state.codexToolUses.add(item.id);
|
|
728
|
-
onEvent({
|
|
729
|
-
type: 'tool_use',
|
|
730
|
-
id: item.id,
|
|
731
|
-
name: 'Bash',
|
|
732
|
-
input: {
|
|
733
|
-
command: typeof item.command === 'string' ? item.command : '',
|
|
734
|
-
},
|
|
735
|
-
});
|
|
736
|
-
}
|
|
737
|
-
return true;
|
|
738
|
-
}
|
|
739
|
-
if (item.type === 'mcp_tool_call') {
|
|
740
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
741
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
742
|
-
if (emitCodexMcpToolUse(item, onEvent, state))
|
|
743
|
-
return true;
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
if (obj.type === 'item.updated' && isRecord(obj.item)) {
|
|
747
|
-
const item = obj.item;
|
|
748
|
-
if (emitCodexTodoList(item, onEvent)) {
|
|
749
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
750
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
751
|
-
return true;
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
if (obj.type === 'item.completed' && isRecord(obj.item)) {
|
|
755
|
-
const item = obj.item;
|
|
756
|
-
if (emitCodexTodoList(item, onEvent)) {
|
|
757
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
758
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
759
|
-
return true;
|
|
760
|
-
}
|
|
761
|
-
if (item.type === 'command_execution' && typeof item.id === 'string') {
|
|
762
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
763
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
764
|
-
if (!state.codexToolUses.has(item.id)) {
|
|
765
|
-
state.codexToolUses.add(item.id);
|
|
766
|
-
onEvent({
|
|
767
|
-
type: 'tool_use',
|
|
768
|
-
id: item.id,
|
|
769
|
-
name: 'Bash',
|
|
770
|
-
input: {
|
|
771
|
-
command: typeof item.command === 'string' ? item.command : '',
|
|
772
|
-
},
|
|
773
|
-
});
|
|
774
|
-
}
|
|
775
|
-
const content = stringifyContent(item.aggregated_output ?? '');
|
|
776
|
-
onEvent({
|
|
777
|
-
type: 'tool_result',
|
|
778
|
-
toolUseId: item.id,
|
|
779
|
-
content,
|
|
780
|
-
isError: typeof item.exit_code === 'number' ? item.exit_code !== 0 : item.status === 'failed',
|
|
781
|
-
});
|
|
782
|
-
const connectorToolError = connectorToolSelectionErrorMessage(content);
|
|
783
|
-
if (connectorToolError && !state.codexErrorEmitted) {
|
|
784
|
-
state.codexErrorEmitted = true;
|
|
785
|
-
onEvent({ type: 'error', message: connectorToolError });
|
|
786
|
-
}
|
|
787
|
-
return true;
|
|
788
|
-
}
|
|
789
|
-
if (item.type === 'mcp_tool_call' && typeof item.id === 'string') {
|
|
790
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
791
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
792
|
-
// `item.started` normally already emitted the matching `tool_use` (see
|
|
793
|
-
// `emitCodexMcpToolUse`); this call is a no-op then, and only actually emits one for a
|
|
794
|
-
// call whose `item.started` frame this parser never saw (a truncated/mid-stream feed —
|
|
795
|
-
// the same fallback shape `command_execution`'s own `item.completed` branch above uses).
|
|
796
|
-
emitCodexMcpToolUse(item, onEvent, state);
|
|
797
|
-
// A call Codex's own approval gate denies before ever reaching the target MCP server
|
|
798
|
-
// reports back exactly this shape — `status: 'failed'`, `result: null`, an `error` object
|
|
799
|
-
// — which is otherwise indistinguishable from "never happened" downstream: no
|
|
800
|
-
// `tool_use`/`tool_result` pair means no audit row, no error card, nothing an operator or
|
|
801
|
-
// the model itself can ground a claim on. `isError` on `status !== 'completed'` (not a
|
|
802
|
-
// truthiness check on `item.error`) matches every other status branch in this file and
|
|
803
|
-
// stays correct even for a hypothetical future status this union does not name yet.
|
|
804
|
-
const isError = item.status !== 'completed';
|
|
805
|
-
const content = isError
|
|
806
|
-
? extractErrorMessage(item.error, 'MCP tool call failed')
|
|
807
|
-
: stringifyContent(item.result);
|
|
808
|
-
onEvent({ type: 'tool_result', toolUseId: item.id, content, isError });
|
|
809
|
-
return true;
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
if (obj.type === 'item.completed' &&
|
|
813
|
-
isRecord(obj.item) &&
|
|
814
|
-
obj.item.type === 'agent_message' &&
|
|
815
|
-
typeof obj.item.text === 'string' &&
|
|
816
|
-
obj.item.text.length > 0) {
|
|
817
|
-
const text = obj.item.text;
|
|
818
|
-
const needsBoundary = state.codexPreviousEventWasAgentMessage &&
|
|
819
|
-
!state.codexLastAgentMessageEndedWithNewline &&
|
|
820
|
-
!text.startsWith('\n');
|
|
821
|
-
const delta = needsBoundary ? `\n${text}` : text;
|
|
822
|
-
onEvent({ type: 'text_delta', delta });
|
|
823
|
-
state.codexPreviousEventWasAgentMessage = true;
|
|
824
|
-
state.codexLastAgentMessageEndedWithNewline = text.endsWith('\n');
|
|
825
|
-
return true;
|
|
930
|
+
return;
|
|
931
|
+
const properties = obj.properties;
|
|
932
|
+
const info = obj.type === 'message.updated' ? properties?.info : undefined;
|
|
933
|
+
if (info?.role === 'assistant' && typeof info.modelID === 'string') {
|
|
934
|
+
onEvent({ type: 'status', label: 'model', model: info.providerID ? `${info.providerID}/${info.modelID}` : info.modelID });
|
|
826
935
|
}
|
|
827
|
-
if (obj.
|
|
828
|
-
|
|
829
|
-
if (typeof obj.usage.input_tokens === 'number')
|
|
830
|
-
usage.input_tokens = obj.usage.input_tokens;
|
|
831
|
-
if (typeof obj.usage.output_tokens === 'number')
|
|
832
|
-
usage.output_tokens = obj.usage.output_tokens;
|
|
833
|
-
if (typeof obj.usage.reasoning_output_tokens === 'number') {
|
|
834
|
-
usage.thought_tokens = obj.usage.reasoning_output_tokens;
|
|
835
|
-
}
|
|
836
|
-
if (typeof obj.usage.cached_input_tokens === 'number') {
|
|
837
|
-
usage.cached_read_tokens = obj.usage.cached_input_tokens;
|
|
838
|
-
}
|
|
839
|
-
onEvent({ type: 'usage', usage });
|
|
840
|
-
return true;
|
|
936
|
+
if (typeof obj.model === 'string' && MODEL_RECEIPT_FRAME_TYPES.has(String(obj.type))) {
|
|
937
|
+
onEvent({ type: 'status', label: 'model', model: obj.model });
|
|
841
938
|
}
|
|
842
|
-
return false;
|
|
843
939
|
}
|
|
940
|
+
const PARSERS_BY_KIND = new Map([
|
|
941
|
+
['opencode', handleOpenCodeEvent],
|
|
942
|
+
['legacy-google-stream-json', handleLegacyGoogleStreamEvent],
|
|
943
|
+
['kimi', handleKimiEvent],
|
|
944
|
+
['cursor-agent', handleCursorEvent],
|
|
945
|
+
['codex', handleCodexEvent],
|
|
946
|
+
]);
|
|
844
947
|
export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
845
948
|
let buffer = '';
|
|
846
949
|
const state = {
|
|
@@ -856,6 +959,7 @@ export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
|
856
959
|
artifactOpenCandidate: '',
|
|
857
960
|
pendingArtifactText: '',
|
|
858
961
|
};
|
|
962
|
+
const parse = PARSERS_BY_KIND.get(kind);
|
|
859
963
|
function handleLine(line) {
|
|
860
964
|
let obj;
|
|
861
965
|
try {
|
|
@@ -865,28 +969,8 @@ export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
|
865
969
|
onEvent({ type: 'raw', line });
|
|
866
970
|
return;
|
|
867
971
|
}
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
|
|
871
|
-
const frame = obj;
|
|
872
|
-
const properties = frame.properties;
|
|
873
|
-
const info = frame.type === 'message.updated' ? properties?.info : undefined;
|
|
874
|
-
if (info?.role === 'assistant' && typeof info.modelID === 'string') {
|
|
875
|
-
onEvent({ type: 'status', label: 'model', model: info.providerID ? `${info.providerID}/${info.modelID}` : info.modelID });
|
|
876
|
-
}
|
|
877
|
-
if (typeof frame.model === 'string' && ['session.created', 'thread.started', 'turn.started', 'model.changed'].includes(String(frame.type))) {
|
|
878
|
-
onEvent({ type: 'status', label: 'model', model: frame.model });
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
if (kind === 'opencode' && handleOpenCodeEvent(obj, onEvent, state))
|
|
882
|
-
return;
|
|
883
|
-
if (kind === 'legacy-google-stream-json' && handleLegacyGoogleStreamEvent(obj, onEvent, state))
|
|
884
|
-
return;
|
|
885
|
-
if (kind === 'kimi' && handleKimiEvent(obj, onEvent))
|
|
886
|
-
return;
|
|
887
|
-
if (kind === 'cursor-agent' && handleCursorEvent(obj, onEvent, state))
|
|
888
|
-
return;
|
|
889
|
-
if (kind === 'codex' && handleCodexEvent(obj, onEvent, state))
|
|
972
|
+
emitModelReceipts(obj, onEvent);
|
|
973
|
+
if (parse?.(obj, onEvent, state))
|
|
890
974
|
return;
|
|
891
975
|
onEvent({ type: 'raw', line });
|
|
892
976
|
}
|