@gajae-code/ai 0.18.5 → 0.18.6
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 +48 -0
- package/dist/types/auth-storage.d.ts +8 -1
- package/dist/types/providers/cursor.d.ts +6 -3
- package/dist/types/providers/kiro-api-key.d.ts +1 -0
- package/dist/types/providers/openai-codex-responses.d.ts +2 -0
- package/dist/types/types.d.ts +1 -1
- package/dist/types/utils/fallback-transport.d.ts +6 -0
- package/dist/types/utils/oauth/glm-zcode.d.ts +5 -0
- package/dist/types/utils/oauth/index.d.ts +4 -0
- package/package.json +3 -3
- package/src/auth-storage.ts +115 -39
- package/src/model-thinking.ts +8 -0
- package/src/providers/aws-eventstream.ts +2 -1
- package/src/providers/cursor.d.ts +6 -3
- package/src/providers/cursor.ts +73 -64
- package/src/providers/kiro-api-key.d.ts +1 -0
- package/src/providers/kiro-api-key.ts +1 -1
- package/src/providers/kiro-codewhisperer.ts +87 -9
- package/src/providers/openai-codex-responses.d.ts +2 -0
- package/src/providers/openai-codex-responses.ts +438 -40
- package/src/stream.ts +20 -0
- package/src/types.d.ts +1 -1
- package/src/types.ts +3 -0
- package/src/utils/fallback-transport.d.ts +6 -0
- package/src/utils/fallback-transport.ts +6 -0
- package/src/utils/idle-iterator.ts +10 -3
- package/src/utils/oauth/glm-zcode.d.ts +5 -0
- package/src/utils/oauth/glm-zcode.ts +8 -1
- package/src/utils/oauth/index.ts +11 -1
- package/src/utils/validation.ts +5 -0
package/src/providers/cursor.ts
CHANGED
|
@@ -32,7 +32,6 @@ import { kProviderResolvedToolCall } from "../utils/block-symbols";
|
|
|
32
32
|
import { AssistantMessageEventStream } from "../utils/event-stream";
|
|
33
33
|
import { transportFailureFacts } from "../utils/fallback-transport";
|
|
34
34
|
import { FirstEventTimeoutError, getStreamFirstEventTimeoutMs, getStreamIdleTimeoutMs } from "../utils/idle-iterator";
|
|
35
|
-
import { captureUnicodeEscapeEvidence, parseStreamingJson } from "../utils/json-parse";
|
|
36
35
|
import { connectProxiedSocket, getProxyForUrl } from "../utils/proxy";
|
|
37
36
|
import { formatErrorMessageWithRetryAfter } from "../utils/retry-after";
|
|
38
37
|
import { flattenToolRootCombinators, toolWireSchema } from "../utils/schema";
|
|
@@ -2288,10 +2287,8 @@ export const streamCursor: StreamFunction<"cursor-agent"> = (
|
|
|
2288
2287
|
}
|
|
2289
2288
|
if (state.currentToolCall) {
|
|
2290
2289
|
const idx = output.content.indexOf(state.currentToolCall);
|
|
2291
|
-
state.currentToolCall
|
|
2292
|
-
|
|
2293
|
-
delete (state.currentToolCall as any).partialJson;
|
|
2294
|
-
delete (state.currentToolCall as any).index;
|
|
2290
|
+
delete (state.currentToolCall as Partial<ToolCallState>).index;
|
|
2291
|
+
delete (state.currentToolCall as Partial<ToolCallState>).kind;
|
|
2295
2292
|
stream.push({
|
|
2296
2293
|
type: "toolcall_end",
|
|
2297
2294
|
contentIndex: idx,
|
|
@@ -2428,9 +2425,8 @@ export const streamCursor: StreamFunction<"cursor-agent"> = (
|
|
|
2428
2425
|
|
|
2429
2426
|
type ToolCallState = ToolCall & {
|
|
2430
2427
|
index: number;
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
[kProviderResolvedToolCall]?: true;
|
|
2428
|
+
kind: "todo_write" | "native" | "cursor-exec";
|
|
2429
|
+
[kProviderResolvedToolCall]: true;
|
|
2434
2430
|
};
|
|
2435
2431
|
|
|
2436
2432
|
interface BlockState {
|
|
@@ -2493,6 +2489,57 @@ async function handleServerMessage(
|
|
|
2493
2489
|
}
|
|
2494
2490
|
}
|
|
2495
2491
|
|
|
2492
|
+
/** Offline test seam for the same server-message boundary used by streamCursor. */
|
|
2493
|
+
export function createCursorServerMessageHandlerForTest(
|
|
2494
|
+
output: AssistantMessage,
|
|
2495
|
+
stream: AssistantMessageEventStream,
|
|
2496
|
+
write: (frame: Uint8Array, done: () => void) => boolean,
|
|
2497
|
+
options: CursorOptions = {},
|
|
2498
|
+
): (message: AgentServerMessage) => Promise<void> {
|
|
2499
|
+
const state: BlockState = {
|
|
2500
|
+
currentTextBlock: null,
|
|
2501
|
+
currentThinkingBlock: null,
|
|
2502
|
+
currentToolCall: null,
|
|
2503
|
+
firstTokenTime: undefined,
|
|
2504
|
+
setTextBlock(block) {
|
|
2505
|
+
this.currentTextBlock = block;
|
|
2506
|
+
},
|
|
2507
|
+
setThinkingBlock(block) {
|
|
2508
|
+
this.currentThinkingBlock = block;
|
|
2509
|
+
},
|
|
2510
|
+
setToolCall(block) {
|
|
2511
|
+
this.currentToolCall = block;
|
|
2512
|
+
},
|
|
2513
|
+
setFirstTokenTime() {
|
|
2514
|
+
this.firstTokenTime ??= Date.now();
|
|
2515
|
+
},
|
|
2516
|
+
};
|
|
2517
|
+
const usageState: UsageState = {
|
|
2518
|
+
sawTokenDelta: false,
|
|
2519
|
+
conversationUsedTokens: 0,
|
|
2520
|
+
checkpointOutputTokens: 0,
|
|
2521
|
+
hasConversationCheckpoint: false,
|
|
2522
|
+
};
|
|
2523
|
+
const writer = { write, isActive: () => true } as unknown as CursorRequestWriter;
|
|
2524
|
+
const blobs = new Map<string, Uint8Array>();
|
|
2525
|
+
return message =>
|
|
2526
|
+
handleServerMessage(
|
|
2527
|
+
message,
|
|
2528
|
+
output,
|
|
2529
|
+
stream,
|
|
2530
|
+
state,
|
|
2531
|
+
blobs,
|
|
2532
|
+
writer,
|
|
2533
|
+
options.execHandlers,
|
|
2534
|
+
options.onToolResult,
|
|
2535
|
+
usageState,
|
|
2536
|
+
[],
|
|
2537
|
+
undefined,
|
|
2538
|
+
[],
|
|
2539
|
+
options.signal,
|
|
2540
|
+
);
|
|
2541
|
+
}
|
|
2542
|
+
|
|
2496
2543
|
function handleKvServerMessage(
|
|
2497
2544
|
kvMsg: KvServerMessage,
|
|
2498
2545
|
blobStore: Map<string, Uint8Array>,
|
|
@@ -3164,6 +3211,7 @@ async function handleExecServerMessage(
|
|
|
3164
3211
|
case "mcpArgs": {
|
|
3165
3212
|
const args = execMsg.message.value;
|
|
3166
3213
|
const mcpCall = decodeMcpCall(args);
|
|
3214
|
+
synthesizeCursorExecToolCall(output, stream, mcpCall.toolCallId, mcpCall.toolName, mcpCall.args);
|
|
3167
3215
|
const { execResult } = await resolveExecHandler(
|
|
3168
3216
|
mcpCall,
|
|
3169
3217
|
execHandlers?.mcp?.bind(execHandlers),
|
|
@@ -4063,17 +4111,6 @@ function decodeMcpArgValue(value: Uint8Array): unknown {
|
|
|
4063
4111
|
return parseToolArgsJson(text);
|
|
4064
4112
|
}
|
|
4065
4113
|
|
|
4066
|
-
function decodeMcpArgsMap(args?: Record<string, Uint8Array>): Record<string, unknown> | undefined {
|
|
4067
|
-
if (!args) {
|
|
4068
|
-
return undefined;
|
|
4069
|
-
}
|
|
4070
|
-
const decoded: Record<string, unknown> = {};
|
|
4071
|
-
for (const [key, value] of Object.entries(args)) {
|
|
4072
|
-
decoded[key] = decodeMcpArgValue(value);
|
|
4073
|
-
}
|
|
4074
|
-
return decoded;
|
|
4075
|
-
}
|
|
4076
|
-
|
|
4077
4114
|
function decodeMcpCall(args: {
|
|
4078
4115
|
name: string;
|
|
4079
4116
|
args: Record<string, Uint8Array>;
|
|
@@ -4089,7 +4126,7 @@ function decodeMcpCall(args: {
|
|
|
4089
4126
|
name: args.name,
|
|
4090
4127
|
providerIdentifier: args.providerIdentifier,
|
|
4091
4128
|
toolName: args.toolName || args.name,
|
|
4092
|
-
toolCallId: args.toolCallId,
|
|
4129
|
+
toolCallId: args.toolCallId || crypto.randomUUID(),
|
|
4093
4130
|
args: decodedArgs,
|
|
4094
4131
|
rawArgs: args.args ?? {},
|
|
4095
4132
|
};
|
|
@@ -4336,7 +4373,7 @@ const CURSOR_EXEC_OWNED_TOOL_CASES = new Set([
|
|
|
4336
4373
|
]);
|
|
4337
4374
|
|
|
4338
4375
|
function isExecOwnedToolCall(toolCall: any): boolean {
|
|
4339
|
-
return CURSOR_EXEC_OWNED_TOOL_CASES.has(toolCall?.tool?.case);
|
|
4376
|
+
return !!selectMcpToolCall(toolCall) || CURSOR_EXEC_OWNED_TOOL_CASES.has(toolCall?.tool?.case);
|
|
4340
4377
|
}
|
|
4341
4378
|
|
|
4342
4379
|
export function buildNativeToolCallBlock(
|
|
@@ -4358,6 +4395,7 @@ export function buildNativeToolCallBlock(
|
|
|
4358
4395
|
: { raw: convertedArgs },
|
|
4359
4396
|
index,
|
|
4360
4397
|
kind: "native",
|
|
4398
|
+
[kProviderResolvedToolCall]: true,
|
|
4361
4399
|
};
|
|
4362
4400
|
}
|
|
4363
4401
|
for (const [key, payload] of Object.entries(toolCall)) {
|
|
@@ -4380,6 +4418,7 @@ export function buildNativeToolCallBlock(
|
|
|
4380
4418
|
arguments: safeArguments,
|
|
4381
4419
|
index,
|
|
4382
4420
|
kind: "native",
|
|
4421
|
+
[kProviderResolvedToolCall]: true,
|
|
4383
4422
|
};
|
|
4384
4423
|
}
|
|
4385
4424
|
return null;
|
|
@@ -4445,6 +4484,7 @@ function synthesizeCursorExecToolCall(
|
|
|
4445
4484
|
name: string,
|
|
4446
4485
|
args: Record<string, unknown>,
|
|
4447
4486
|
): void {
|
|
4487
|
+
if (output.content.some(block => block.type === "toolCall" && block.id === toolCallId)) return;
|
|
4448
4488
|
const block: ToolCallState = {
|
|
4449
4489
|
type: "toolCall",
|
|
4450
4490
|
id: toolCallId,
|
|
@@ -4518,33 +4558,19 @@ function processInteractionUpdate(
|
|
|
4518
4558
|
state.setThinkingBlock(null);
|
|
4519
4559
|
}
|
|
4520
4560
|
} else if (updateCase === "toolCallStarted" && isExecOwnedToolCall(update.message.value.toolCall)) {
|
|
4521
|
-
//
|
|
4522
|
-
//
|
|
4561
|
+
// Exec owns MCP and Pi tools. Suppress interaction announcements and
|
|
4562
|
+
// synthesize canonical, provider-resolved blocks before executing them.
|
|
4523
4563
|
log("exec", "streamedToolCallOwnedByExec", { case: update.message.value.toolCall?.tool?.case });
|
|
4524
4564
|
} else if (updateCase === "toolCallStarted") {
|
|
4525
4565
|
const toolCall = update.message.value.toolCall;
|
|
4526
4566
|
if (toolCall) {
|
|
4527
|
-
const
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
const block: ToolCallState = {
|
|
4531
|
-
type: "toolCall",
|
|
4532
|
-
id: args.toolCallId || crypto.randomUUID(),
|
|
4533
|
-
name: args.name || args.toolName || "",
|
|
4534
|
-
arguments: {},
|
|
4535
|
-
index: output.content.length,
|
|
4536
|
-
partialJson: "",
|
|
4537
|
-
kind: "mcp",
|
|
4538
|
-
};
|
|
4539
|
-
output.content.push(block);
|
|
4540
|
-
state.setToolCall(block);
|
|
4541
|
-
stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
|
|
4542
|
-
return;
|
|
4543
|
-
}
|
|
4567
|
+
const callId = update.message.value.callId || crypto.randomUUID();
|
|
4568
|
+
// Repeated announcements describe the same provider-owned execution.
|
|
4569
|
+
if (output.content.some(block => block.type === "toolCall" && block.id === callId)) return;
|
|
4544
4570
|
|
|
4545
4571
|
const todoArgs = buildTodoWriteArgs(toolCall);
|
|
4546
4572
|
if (todoArgs) {
|
|
4547
|
-
|
|
4573
|
+
// Cursor owns its todo state; this snapshot is for display, not local { ops } dispatch.
|
|
4548
4574
|
const block: ToolCallState = {
|
|
4549
4575
|
type: "toolCall",
|
|
4550
4576
|
id: callId,
|
|
@@ -4552,6 +4578,7 @@ function processInteractionUpdate(
|
|
|
4552
4578
|
arguments: todoArgs,
|
|
4553
4579
|
index: output.content.length,
|
|
4554
4580
|
kind: "todo_write",
|
|
4581
|
+
[kProviderResolvedToolCall]: true,
|
|
4555
4582
|
};
|
|
4556
4583
|
output.content.push(block);
|
|
4557
4584
|
state.setToolCall(block);
|
|
@@ -4562,44 +4589,26 @@ function processInteractionUpdate(
|
|
|
4562
4589
|
// Fallback: cursor-native tool variants (shell/glob/grep/…) we don't model
|
|
4563
4590
|
// explicitly. Render them so the call and its result are visible instead of
|
|
4564
4591
|
// vanishing.
|
|
4565
|
-
const nativeBlock = buildNativeToolCallBlock(
|
|
4566
|
-
toolCall,
|
|
4567
|
-
update.message.value.callId || crypto.randomUUID(),
|
|
4568
|
-
output.content.length,
|
|
4569
|
-
);
|
|
4592
|
+
const nativeBlock = buildNativeToolCallBlock(toolCall, callId, output.content.length);
|
|
4570
4593
|
if (nativeBlock) {
|
|
4571
4594
|
output.content.push(nativeBlock);
|
|
4572
4595
|
state.setToolCall(nativeBlock);
|
|
4573
4596
|
stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
|
|
4574
4597
|
}
|
|
4575
4598
|
}
|
|
4576
|
-
} else if (updateCase === "toolCallDelta" || updateCase === "partialToolCall") {
|
|
4577
|
-
if (state.currentToolCall?.kind === "mcp") {
|
|
4578
|
-
const delta = update.message.value.argsTextDelta || "";
|
|
4579
|
-
state.currentToolCall.partialJson = `${state.currentToolCall.partialJson ?? ""}${delta}`;
|
|
4580
|
-
state.currentToolCall.arguments = parseStreamingJson(state.currentToolCall.partialJson ?? "");
|
|
4581
|
-
const idx = output.content.indexOf(state.currentToolCall);
|
|
4582
|
-
stream.push({ type: "toolcall_delta", contentIndex: idx, delta, partial: output });
|
|
4583
|
-
}
|
|
4584
4599
|
} else if (updateCase === "toolCallCompleted") {
|
|
4600
|
+
if (isExecOwnedToolCall(update.message.value.toolCall)) return;
|
|
4585
4601
|
if (state.currentToolCall) {
|
|
4586
4602
|
const toolCall = update.message.value.toolCall;
|
|
4587
|
-
if (state.currentToolCall.kind === "
|
|
4588
|
-
captureUnicodeEscapeEvidence(state.currentToolCall, state.currentToolCall.partialJson ?? "");
|
|
4589
|
-
const decodedArgs = decodeMcpArgsMap(selectMcpToolCall(toolCall)?.args?.args);
|
|
4590
|
-
if (decodedArgs) {
|
|
4591
|
-
state.currentToolCall.arguments = decodedArgs;
|
|
4592
|
-
}
|
|
4593
|
-
} else if (state.currentToolCall.kind === "todo_write" && toolCall) {
|
|
4603
|
+
if (state.currentToolCall.kind === "todo_write" && toolCall) {
|
|
4594
4604
|
const todoArgs = buildTodoWriteArgs(toolCall);
|
|
4595
4605
|
if (todoArgs) {
|
|
4596
4606
|
state.currentToolCall.arguments = todoArgs;
|
|
4597
4607
|
}
|
|
4598
4608
|
}
|
|
4599
4609
|
const idx = output.content.indexOf(state.currentToolCall);
|
|
4600
|
-
delete (state.currentToolCall as
|
|
4601
|
-
delete (state.currentToolCall as
|
|
4602
|
-
delete (state.currentToolCall as any).kind;
|
|
4610
|
+
delete (state.currentToolCall as Partial<ToolCallState>).index;
|
|
4611
|
+
delete (state.currentToolCall as Partial<ToolCallState>).kind;
|
|
4603
4612
|
stream.push({ type: "toolcall_end", contentIndex: idx, toolCall: state.currentToolCall, partial: output });
|
|
4604
4613
|
state.setToolCall(null);
|
|
4605
4614
|
}
|
|
@@ -5,6 +5,7 @@ export declare function kiroApiRegion(options?: {
|
|
|
5
5
|
}): string;
|
|
6
6
|
export declare function kiroApiBaseUrl(region: string): string;
|
|
7
7
|
export declare function toKiroModelId(modelId: string): string;
|
|
8
|
+
export declare function sanitizeKiroError(value: unknown, secret?: string): string;
|
|
8
9
|
export declare function kiroApiStaticModels(): Model<"kiro-codewhisperer-stream">[];
|
|
9
10
|
/** Discover models this API key can use. Returns null when the key is missing. */
|
|
10
11
|
export declare function fetchKiroApiModels(apiKey: string, region?: string): Promise<Model<"kiro-codewhisperer-stream">[]>;
|
|
@@ -118,7 +118,7 @@ function kiroApiHeaders(apiKey: string, target: string): Record<string, string>
|
|
|
118
118
|
};
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
function sanitizeKiroError(value: unknown, secret?: string): string {
|
|
121
|
+
export function sanitizeKiroError(value: unknown, secret?: string): string {
|
|
122
122
|
let message = value instanceof Error ? value.message : String(value);
|
|
123
123
|
if (secret) message = message.split(secret).join("[redacted]");
|
|
124
124
|
message = message.replace(/bearer\s+[^\s,;]+/gi, "Bearer [redacted]");
|
|
@@ -26,11 +26,11 @@ import type {
|
|
|
26
26
|
ToolResultMessage,
|
|
27
27
|
} from "../types";
|
|
28
28
|
import { AssistantMessageEventStream } from "../utils/event-stream";
|
|
29
|
-
import { transportFailureFacts } from "../utils/fallback-transport";
|
|
29
|
+
import { PROVIDER_PROTOCOL_MISMATCH_ERROR_CODE, transportFailureFacts } from "../utils/fallback-transport";
|
|
30
30
|
import { withHttpStatus } from "../utils/http-inspector";
|
|
31
31
|
import { captureUnicodeEscapeEvidence } from "../utils/json-parse";
|
|
32
32
|
import { decodeEventStream } from "./aws-eventstream";
|
|
33
|
-
import { isKiroApiKey, streamKiroApiKey, toKiroModelId } from "./kiro-api-key";
|
|
33
|
+
import { isKiroApiKey, sanitizeKiroError, streamKiroApiKey, toKiroModelId } from "./kiro-api-key";
|
|
34
34
|
|
|
35
35
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
36
36
|
// Provider options
|
|
@@ -78,7 +78,7 @@ interface WireUserMessage {
|
|
|
78
78
|
toolResults?: WireToolResult[];
|
|
79
79
|
editorStateContext?: Record<string, unknown>;
|
|
80
80
|
};
|
|
81
|
-
origin
|
|
81
|
+
origin: typeof KIRO_ORIGIN;
|
|
82
82
|
};
|
|
83
83
|
}
|
|
84
84
|
|
|
@@ -142,6 +142,12 @@ interface ErrorPayload {
|
|
|
142
142
|
|
|
143
143
|
const DEFAULT_REGION = "us-east-1";
|
|
144
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Without `origin` the service ignores `modelId` and routes every request to
|
|
147
|
+
* `auto`; with it, response frames report the requested model.
|
|
148
|
+
*/
|
|
149
|
+
const KIRO_ORIGIN = "AI_EDITOR";
|
|
150
|
+
|
|
145
151
|
type Block = (TextContent | ToolCall) & { index?: number; partialJson?: string };
|
|
146
152
|
|
|
147
153
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -240,14 +246,29 @@ export const streamKiroCodeWhisperer: StreamFunction<"kiro-codewhisperer-stream"
|
|
|
240
246
|
});
|
|
241
247
|
|
|
242
248
|
if (!response.ok) {
|
|
243
|
-
const errBody = await response
|
|
249
|
+
const errBody = await readBodyPrefix(response);
|
|
244
250
|
throw withHttpStatus(
|
|
245
|
-
new Error(`Kiro CodeWhisperer HTTP ${response.status}: ${errBody
|
|
251
|
+
new Error(sanitizeKiroError(`Kiro CodeWhisperer HTTP ${response.status}: ${errBody}`, bearerToken)),
|
|
246
252
|
response.status,
|
|
247
253
|
);
|
|
248
254
|
}
|
|
249
255
|
|
|
250
|
-
|
|
256
|
+
// Verify content-type is eventstream; if not, read and report the actual error
|
|
257
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
258
|
+
const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
259
|
+
if (!response.body || mediaType !== "application/vnd.amazon.eventstream") {
|
|
260
|
+
const errBody = await readBodyPrefix(response);
|
|
261
|
+
// Deliberately no HTTP status metadata and no "HTTP <code>" wording: a 2xx
|
|
262
|
+
// protocol mismatch is deterministic, and a status would materialize
|
|
263
|
+
// transport-failure facts that session fallback retries.
|
|
264
|
+
// Sanitize each untrusted part on its own so the fixed prefix does not eat
|
|
265
|
+
// into the body's 1000-character diagnostic budget.
|
|
266
|
+
const safeContentType = contentType ? sanitizeKiroError(contentType, bearerToken) : "";
|
|
267
|
+
const safeBody = errBody ? sanitizeKiroError(errBody, bearerToken) : "";
|
|
268
|
+
throw new KiroNonEventStreamError(
|
|
269
|
+
`Kiro CodeWhisperer returned a non-eventstream ${response.status} response (${safeContentType}): ${safeBody}`,
|
|
270
|
+
);
|
|
271
|
+
}
|
|
251
272
|
|
|
252
273
|
// Decode eventstream
|
|
253
274
|
for await (const message of decodeEventStream(response.body)) {
|
|
@@ -348,8 +369,10 @@ export const streamKiroCodeWhisperer: StreamFunction<"kiro-codewhisperer-stream"
|
|
|
348
369
|
delete (block as Block).partialJson;
|
|
349
370
|
}
|
|
350
371
|
output.stopReason = options.signal?.aborted ? "aborted" : "error";
|
|
351
|
-
|
|
372
|
+
// The non-eventstream diagnostic embeds untrusted body text; never parse a status out of it.
|
|
373
|
+
output.errorStatus = error instanceof KiroNonEventStreamError ? undefined : extractHttpStatusFromError(error);
|
|
352
374
|
output.transportFailure = transportFailureFacts(error);
|
|
375
|
+
if (error instanceof KiroNonEventStreamError) output.errorCode = PROVIDER_PROTOCOL_MISMATCH_ERROR_CODE;
|
|
353
376
|
const baseMessage = error instanceof Error ? error.message : JSON.stringify(error);
|
|
354
377
|
output.errorMessage = baseMessage;
|
|
355
378
|
output.duration = Date.now() - startTime;
|
|
@@ -386,7 +409,20 @@ function buildConversationState(
|
|
|
386
409
|
const history: WireHistoryMessage[] = [];
|
|
387
410
|
const systemPrompt = context.systemPrompt?.join("\n") ?? "";
|
|
388
411
|
|
|
389
|
-
|
|
412
|
+
// Parallel tool calls end the conversation with several consecutive toolResult
|
|
413
|
+
// messages. They all answer the last assistant turn, so they must travel
|
|
414
|
+
// together in currentMessage; leaving the earlier ones as a separate history
|
|
415
|
+
// entry is rejected upstream with TOOL_USE_RESULT_MISMATCH.
|
|
416
|
+
let currentStart = messages.length - 1;
|
|
417
|
+
while (
|
|
418
|
+
currentStart > 0 &&
|
|
419
|
+
messages[currentStart].role === "toolResult" &&
|
|
420
|
+
messages[currentStart - 1].role === "toolResult"
|
|
421
|
+
) {
|
|
422
|
+
currentStart--;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
for (let i = 0; i < currentStart; i++) {
|
|
390
426
|
const msg = messages[i];
|
|
391
427
|
const previous = history[history.length - 1];
|
|
392
428
|
// Parallel tool calls produce consecutive toolResult messages; they answer one
|
|
@@ -406,9 +442,14 @@ function buildConversationState(
|
|
|
406
442
|
history.push(convertToWireMessage(msg, modelId, i === 0 ? systemPrompt : undefined));
|
|
407
443
|
}
|
|
408
444
|
|
|
409
|
-
// Convert the last message as currentMessage
|
|
445
|
+
// Convert the last message as currentMessage, carrying every trailing parallel result.
|
|
410
446
|
const lastMsg = messages[messages.length - 1];
|
|
411
447
|
const currentMessage = convertToWireUserMessage(lastMsg, modelId, systemPrompt);
|
|
448
|
+
if (currentStart < messages.length - 1) {
|
|
449
|
+
currentMessage.userInputMessage.userInputMessageContext = {
|
|
450
|
+
toolResults: messages.slice(currentStart).map(msg => convertToolResult(msg as ToolResultMessage)),
|
|
451
|
+
};
|
|
452
|
+
}
|
|
412
453
|
|
|
413
454
|
// Add tools to the current message context
|
|
414
455
|
if (context.tools && context.tools.length > 0) {
|
|
@@ -480,6 +521,7 @@ function convertToWireUserMessage(
|
|
|
480
521
|
userInputMessage: {
|
|
481
522
|
content,
|
|
482
523
|
modelId,
|
|
524
|
+
origin: KIRO_ORIGIN,
|
|
483
525
|
},
|
|
484
526
|
};
|
|
485
527
|
|
|
@@ -603,6 +645,42 @@ function handleToolUseEvent(
|
|
|
603
645
|
// Helpers
|
|
604
646
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
605
647
|
|
|
648
|
+
/** A 2xx response that is not an AWS event stream: a deterministic protocol error, never a transport failure. */
|
|
649
|
+
class KiroNonEventStreamError extends Error {
|
|
650
|
+
override name = "KiroNonEventStreamError";
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** Byte cap for diagnostic error bodies; the rest of the stream is cancelled unread. */
|
|
654
|
+
const ERROR_BODY_PREFIX_BYTES = 4096;
|
|
655
|
+
|
|
656
|
+
/** Read at most {@link ERROR_BODY_PREFIX_BYTES} of a response body for diagnostics, then cancel the remainder. */
|
|
657
|
+
async function readBodyPrefix(response: Response): Promise<string> {
|
|
658
|
+
if (!response.body) return "";
|
|
659
|
+
const reader = response.body.getReader();
|
|
660
|
+
const chunks: Uint8Array[] = [];
|
|
661
|
+
let total = 0;
|
|
662
|
+
try {
|
|
663
|
+
while (total < ERROR_BODY_PREFIX_BYTES) {
|
|
664
|
+
const { done, value } = await reader.read();
|
|
665
|
+
if (done) break;
|
|
666
|
+
const take = value.subarray(0, ERROR_BODY_PREFIX_BYTES - total);
|
|
667
|
+
chunks.push(take);
|
|
668
|
+
total += take.length;
|
|
669
|
+
}
|
|
670
|
+
} catch {
|
|
671
|
+
// Diagnostic read only; report whatever prefix arrived.
|
|
672
|
+
} finally {
|
|
673
|
+
reader.cancel().catch(() => {});
|
|
674
|
+
}
|
|
675
|
+
const bytes = new Uint8Array(total);
|
|
676
|
+
let offset = 0;
|
|
677
|
+
for (const chunk of chunks) {
|
|
678
|
+
bytes.set(chunk, offset);
|
|
679
|
+
offset += chunk.length;
|
|
680
|
+
}
|
|
681
|
+
return new TextDecoder().decode(bytes);
|
|
682
|
+
}
|
|
683
|
+
|
|
606
684
|
function resolveBearerToken(apiKey: string | undefined): string | undefined {
|
|
607
685
|
if (!apiKey) {
|
|
608
686
|
return $credentialEnv("KIRO_API_KEY") ?? $credentialEnv("AWS_BEARER_TOKEN_KIRO") ?? undefined;
|
|
@@ -11,6 +11,8 @@ export interface OpenAICodexResponsesOptions extends StreamOptions {
|
|
|
11
11
|
preferWebsockets?: boolean;
|
|
12
12
|
serviceTier?: ServiceTier;
|
|
13
13
|
}
|
|
14
|
+
/** @internal Exported for tests. */
|
|
15
|
+
export declare function createCodexStreamProgressClassifier(): (event: unknown) => boolean;
|
|
14
16
|
type CodexTransport = "sse" | "websocket";
|
|
15
17
|
export interface OpenAICodexWebSocketDebugStats {
|
|
16
18
|
fullContextRequests: number;
|