@myagentroam/agent 0.13.21 → 0.13.23
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/dist/cli/catalog-file.d.ts +3 -2
- package/dist/cli/catalog-file.js +9 -3
- package/dist/cli/main.js +2 -1
- package/dist/extensions/session-messages.d.ts +1 -1
- package/dist/model/anthropic-messages.js +52 -43
- package/dist/model/configuration.d.ts +5 -3
- package/dist/model/configuration.js +16 -2
- package/dist/model/openai-responses.d.ts +2 -2
- package/dist/model/openai-responses.js +35 -26
- package/dist/model/sse.d.ts +3 -0
- package/dist/model/sse.js +19 -11
- package/dist/network/credential-runtime.d.ts +5 -0
- package/dist/network/credential-runtime.js +10 -2
- package/dist/network/http.d.ts +1 -0
- package/dist/network/http.js +24 -4
- package/dist/prompts/core.d.ts +2 -2
- package/dist/prompts/core.js +3 -3
- package/dist/prompts/index.d.ts +1 -1
- package/dist/prompts/index.js +2 -2
- package/dist/prompts/workflow.d.ts +3 -3
- package/dist/prompts/workflow.js +6 -26
- package/dist/runtime/context/contextual-blocks.js +0 -1
- package/dist/runtime/context/instructions.js +23 -2
- package/dist/runtime/context/world-state.d.ts +2 -1
- package/dist/runtime/context/world-state.js +9 -2
- package/dist/sdk/execution-context-coordinator.d.ts +1 -1
- package/dist/sdk/execution-context-coordinator.js +2 -2
- package/dist/sdk/execution-model-context.d.ts +2 -1
- package/dist/sdk/execution-model-context.js +31 -11
- package/dist/sdk/session-execution-factory.d.ts +1 -1
- package/dist/sdk/session-execution-factory.js +3 -2
- package/dist/sdk/session-extension-prompt.d.ts +2 -9
- package/dist/sdk/session-extension-prompt.js +2 -23
- package/dist/sdk/session.js +1 -8
- package/dist/tools/code-mode/cells.js +4 -3
- package/dist/tools/code-mode/index.js +5 -3
- package/dist/tools/local/apply-patch.js +11 -5
- package/dist/tools/local/exec.js +20 -20
- package/dist/tools/local/view-image.js +3 -0
- package/dist/tools/shared/text-input.d.ts +3 -0
- package/dist/tools/shared/text-input.js +13 -0
- package/package.json +3 -1
|
@@ -10,6 +10,7 @@ export declare const modelCatalogPath: (home: string) => string;
|
|
|
10
10
|
export declare function readModelCatalog(home: string): Promise<CliModelCatalog>;
|
|
11
11
|
export declare function writeModelCatalog(home: string, catalog: CliModelCatalog): Promise<void>;
|
|
12
12
|
export declare function serializeModel(model: CliModelConfiguration): {
|
|
13
|
+
socks5Url?: string;
|
|
13
14
|
apiKey: string;
|
|
14
15
|
conversationModel?: boolean;
|
|
15
16
|
subagentModel?: boolean;
|
|
@@ -32,7 +33,7 @@ export declare function serializeModel(model: CliModelConfiguration): {
|
|
|
32
33
|
codeMode: boolean;
|
|
33
34
|
gcEnabled?: boolean | undefined;
|
|
34
35
|
fastMode?: boolean | undefined;
|
|
35
|
-
serviceTier?: "default" | "
|
|
36
|
+
serviceTier?: "default" | "priority" | "auto" | "flex" | "fast" | "ultrafast" | undefined;
|
|
36
37
|
hostedWebSearch: boolean;
|
|
37
38
|
responsesToolNamespace?: string | undefined;
|
|
38
39
|
responsesOptionalParameters?: {
|
|
@@ -68,7 +69,7 @@ export declare function serializeModel(model: CliModelConfiguration): {
|
|
|
68
69
|
codeMode: boolean;
|
|
69
70
|
gcEnabled?: boolean | undefined;
|
|
70
71
|
fastMode?: boolean | undefined;
|
|
71
|
-
serviceTier?: "default" | "
|
|
72
|
+
serviceTier?: "default" | "priority" | "auto" | "flex" | "fast" | "ultrafast" | undefined;
|
|
72
73
|
hostedWebSearch: boolean;
|
|
73
74
|
responsesToolNamespace?: string | undefined;
|
|
74
75
|
responsesOptionalParameters?: {
|
package/dist/cli/catalog-file.js
CHANGED
|
@@ -33,12 +33,18 @@ export async function writeModelCatalog(home, catalog) {
|
|
|
33
33
|
await rename(temporary, path);
|
|
34
34
|
}
|
|
35
35
|
export function serializeModel(model) {
|
|
36
|
-
const { apiKey, credentialProvider, credentialSource, ...configuration } = model;
|
|
36
|
+
const { apiKey, socks5Url, credentialProvider, credentialSource, ...configuration } = model;
|
|
37
37
|
if (apiKey !== undefined) {
|
|
38
38
|
if (credentialProvider !== undefined || credentialSource !== undefined)
|
|
39
39
|
throw new AgentError('MAR_AGENT_MODEL_CONFIG_INVALID', 'Model credential sources are ambiguous.');
|
|
40
|
-
return {
|
|
40
|
+
return {
|
|
41
|
+
...configuration,
|
|
42
|
+
apiKey: apiKey.reveal(),
|
|
43
|
+
...(socks5Url === undefined ? {} : { socks5Url: socks5Url.reveal() })
|
|
44
|
+
};
|
|
41
45
|
}
|
|
46
|
+
if (socks5Url !== undefined)
|
|
47
|
+
throw invalidCatalog();
|
|
42
48
|
if (credentialSource !== undefined)
|
|
43
49
|
return {
|
|
44
50
|
...configuration,
|
|
@@ -73,7 +79,7 @@ function parseCliModelCatalog(input, options = {}) {
|
|
|
73
79
|
credential.type !== 'CODEX_AUTH_FILE' ||
|
|
74
80
|
Object.keys(credential).length !== 1)
|
|
75
81
|
throw invalidCatalog();
|
|
76
|
-
if (Object.hasOwn(model, 'apiKey'))
|
|
82
|
+
if (Object.hasOwn(model, 'apiKey') || model.socks5Url !== undefined)
|
|
77
83
|
throw invalidCatalog();
|
|
78
84
|
externalCredentialModels.add(index);
|
|
79
85
|
const { credential: _credential, ...configuration } = model;
|
package/dist/cli/main.js
CHANGED
|
@@ -157,7 +157,8 @@ async function modelsCommand(home, arguments_, codexAuthFile) {
|
|
|
157
157
|
: {
|
|
158
158
|
apiKey: new SecretValue(readsApiKey
|
|
159
159
|
? await readApiKey()
|
|
160
|
-
: required(existing?.apiKey?.reveal(), '--api-key-stdin'))
|
|
160
|
+
: required(existing?.apiKey?.reveal(), '--api-key-stdin')),
|
|
161
|
+
...(existing?.socks5Url === undefined ? {} : { socks5Url: existing.socks5Url })
|
|
161
162
|
}),
|
|
162
163
|
modelId: required(option('--model', existing?.modelId), '--model'),
|
|
163
164
|
contextWindowTokens: integer('--context', existing?.contextWindowTokens ?? 256_000),
|
|
@@ -29,7 +29,7 @@ export interface ExtensionSessionMessages {
|
|
|
29
29
|
readonly nextCursor?: string;
|
|
30
30
|
}
|
|
31
31
|
export declare function normalizeSessionMessagesInput(input: ExtensionSessionMessagesInput): Readonly<{
|
|
32
|
-
view: "conversation" | "
|
|
32
|
+
view: "conversation" | "request" | "model";
|
|
33
33
|
agentId: string | undefined;
|
|
34
34
|
includeImages: boolean;
|
|
35
35
|
cursor: number;
|
|
@@ -5,9 +5,10 @@ import { modelImageUrl } from './image.js';
|
|
|
5
5
|
import { stableToolSchema } from './tool-schema.js';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import { AgentError } from '../error.js';
|
|
8
|
+
import { acquireModelCredential, modelCredentialSensitiveValues } from '../network/credential-runtime.js';
|
|
8
9
|
import { assertInlineMediaBudget } from './inline-media-budget.js';
|
|
9
10
|
import { resolveModelDefaultReasoningEffort } from './configuration.js';
|
|
10
|
-
import { isRetryableUpstreamOverloadCode, number, parseSse, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
|
|
11
|
+
import { isRetryableUpstreamOverloadCode, number, parseSse, redactResponseHeader, responseRedactor, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
|
|
11
12
|
import { fetchModelResponse, modelRetryMaxAttempts, isRetryableModelRequestError, isRetryableModelTransportError, modelRetryDelay, waitForModelRetry } from './http.js';
|
|
12
13
|
import { anthropicThinkingBlock, assertAnthropicThinkingBudget } from './anthropic-thinking.js';
|
|
13
14
|
import { resolveModelTextBlocks } from './text-blocks.js';
|
|
@@ -99,6 +100,7 @@ export class AnthropicMessagesAdapter {
|
|
|
99
100
|
const apiKey = this.configuration.apiKey;
|
|
100
101
|
if (apiKey === undefined)
|
|
101
102
|
throw new AgentError('MAR_AGENT_MODEL_CONFIG_INVALID', 'Anthropic Messages requires a static API key.');
|
|
103
|
+
const credential = await acquireModelCredential(this.configuration, 'REQUEST', 'Anthropic Messages requires a static API key.', signal);
|
|
102
104
|
const tools = request.allowTools === false
|
|
103
105
|
? []
|
|
104
106
|
: request.tools.map((tool) => ({
|
|
@@ -107,40 +109,44 @@ export class AnthropicMessagesAdapter {
|
|
|
107
109
|
input_schema: stableToolSchema(tool.inputSchema)
|
|
108
110
|
}));
|
|
109
111
|
const response = await fetchModelResponse(`${this.configuration.baseUrl.replace(/\/$/, '')}/v1/messages`, {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
:
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
112
|
+
httpVersion: '1.1',
|
|
113
|
+
...(credential.socks5Url === undefined ? {} : { socks5Url: credential.socks5Url.reveal() }),
|
|
114
|
+
request: {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers: {
|
|
117
|
+
'x-api-key': apiKey.reveal(),
|
|
118
|
+
'anthropic-version': '2023-06-01',
|
|
119
|
+
'content-type': 'application/json',
|
|
120
|
+
'user-agent': productUserAgent(),
|
|
121
|
+
accept: 'text/event-stream'
|
|
122
|
+
},
|
|
123
|
+
body: JSON.stringify({
|
|
124
|
+
model: this.configuration.modelId,
|
|
125
|
+
system: request.systemBlocks !== undefined
|
|
126
|
+
? anthropicTextBlocks(request.system, request.systemBlocks)
|
|
127
|
+
: request.system
|
|
128
|
+
? [
|
|
129
|
+
{
|
|
130
|
+
type: 'text',
|
|
131
|
+
text: request.system,
|
|
132
|
+
cache_control: { type: 'ephemeral' }
|
|
133
|
+
}
|
|
134
|
+
]
|
|
135
|
+
: [],
|
|
136
|
+
messages: anthropicMessages(request.messages, request.images, request.tools, this.configuration.id, request.systemBlocks === undefined &&
|
|
137
|
+
request.messages.every((message) => message.textBlocks === undefined), request.cachePrefixMessages),
|
|
138
|
+
tools,
|
|
139
|
+
...(request.toolChoice === undefined
|
|
140
|
+
? {}
|
|
141
|
+
: { tool_choice: { type: request.toolChoice } }),
|
|
142
|
+
stream: true,
|
|
143
|
+
max_tokens: Math.min(request.outputLimit ?? this.configuration.maxOutputTokens, this.configuration.maxOutputTokens),
|
|
144
|
+
output_config: {
|
|
145
|
+
effort: request.reasoningEffort?.trim() ||
|
|
146
|
+
resolveModelDefaultReasoningEffort(this.configuration)
|
|
147
|
+
}
|
|
148
|
+
})
|
|
149
|
+
}
|
|
144
150
|
}, signal, 1);
|
|
145
151
|
const blocks = new Map();
|
|
146
152
|
const hostedTools = new Map();
|
|
@@ -151,7 +157,7 @@ export class AnthropicMessagesAdapter {
|
|
|
151
157
|
let terminal;
|
|
152
158
|
let latestInputUsage;
|
|
153
159
|
let thinkingBytes = 0;
|
|
154
|
-
for await (const raw of parseAnthropicSse(response, signal,
|
|
160
|
+
for await (const raw of parseAnthropicSse(response, signal, modelCredentialSensitiveValues(credential))) {
|
|
155
161
|
const event = record(raw);
|
|
156
162
|
const type = text(event.type) ?? 'unknown';
|
|
157
163
|
const index = number(event.index) ?? -1;
|
|
@@ -421,12 +427,15 @@ export class AnthropicMessagesAdapter {
|
|
|
421
427
|
}
|
|
422
428
|
else if (type === 'error') {
|
|
423
429
|
const upstream = record(event.error);
|
|
424
|
-
const
|
|
425
|
-
const
|
|
430
|
+
const redact = responseRedactor(modelCredentialSensitiveValues(credential));
|
|
431
|
+
const code = boundedError(redact(text(upstream.code) ?? text(upstream.type) ?? ''), 80);
|
|
432
|
+
const message = boundedError(redact(text(upstream.message) ?? ''), 1_000);
|
|
426
433
|
const retryable = isRetryableUpstreamOverloadCode(code);
|
|
427
434
|
throw new AgentError(code ?? 'MAR_AGENT_MODEL_PROTOCOL_ERROR', message ?? 'Anthropic Messages request failed.', retryable
|
|
428
435
|
? {
|
|
429
|
-
details: {
|
|
436
|
+
details: {
|
|
437
|
+
retryAfter: redactResponseHeader(response.headers.get('retry-after'), modelCredentialSensitiveValues(credential))
|
|
438
|
+
},
|
|
430
439
|
retryable: true
|
|
431
440
|
}
|
|
432
441
|
: {});
|
|
@@ -439,14 +448,14 @@ export class AnthropicMessagesAdapter {
|
|
|
439
448
|
retryable: true,
|
|
440
449
|
details: {
|
|
441
450
|
reason: 'ANTHROPIC_MESSAGES_EARLY_EOF',
|
|
442
|
-
retryAfter: response.headers.get('retry-after')
|
|
451
|
+
retryAfter: redactResponseHeader(response.headers.get('retry-after'), modelCredentialSensitiveValues(credential))
|
|
443
452
|
}
|
|
444
453
|
});
|
|
445
454
|
}
|
|
446
455
|
}
|
|
447
|
-
async function* parseAnthropicSse(response, signal,
|
|
456
|
+
async function* parseAnthropicSse(response, signal, sensitiveValues) {
|
|
448
457
|
try {
|
|
449
|
-
yield* parseSse(response, signal, undefined, undefined,
|
|
458
|
+
yield* parseSse(response, signal, undefined, undefined, sensitiveValues);
|
|
450
459
|
}
|
|
451
460
|
catch (cause) {
|
|
452
461
|
if (response.ok &&
|
|
@@ -457,7 +466,7 @@ async function* parseAnthropicSse(response, signal, apiKey) {
|
|
|
457
466
|
retryable: true,
|
|
458
467
|
details: {
|
|
459
468
|
reason: 'ANTHROPIC_MESSAGES_EARLY_EOF',
|
|
460
|
-
retryAfter: response.headers.get('retry-after')
|
|
469
|
+
retryAfter: redactResponseHeader(response.headers.get('retry-after'), sensitiveValues)
|
|
461
470
|
},
|
|
462
471
|
cause
|
|
463
472
|
});
|
|
@@ -26,6 +26,7 @@ declare const rawModelSchema: z.ZodObject<{
|
|
|
26
26
|
}>;
|
|
27
27
|
baseUrl: z.ZodString;
|
|
28
28
|
apiKey: z.ZodString;
|
|
29
|
+
socks5Url: z.ZodOptional<z.ZodString>;
|
|
29
30
|
credentialProvider: z.ZodOptional<z.ZodNever>;
|
|
30
31
|
credential: z.ZodOptional<z.ZodNever>;
|
|
31
32
|
modelId: z.ZodString;
|
|
@@ -61,9 +62,9 @@ declare const rawModelSchema: z.ZodObject<{
|
|
|
61
62
|
fastMode: z.ZodOptional<z.ZodBoolean>;
|
|
62
63
|
serviceTier: z.ZodOptional<z.ZodEnum<{
|
|
63
64
|
default: "default";
|
|
65
|
+
priority: "priority";
|
|
64
66
|
auto: "auto";
|
|
65
67
|
flex: "flex";
|
|
66
|
-
priority: "priority";
|
|
67
68
|
fast: "fast";
|
|
68
69
|
ultrafast: "ultrafast";
|
|
69
70
|
}>>;
|
|
@@ -71,8 +72,8 @@ declare const rawModelSchema: z.ZodObject<{
|
|
|
71
72
|
responsesTransport: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
72
73
|
transport: z.ZodLiteral<"HTTP">;
|
|
73
74
|
httpVersion: z.ZodEnum<{
|
|
74
|
-
1.1: "1.1";
|
|
75
75
|
2: "2";
|
|
76
|
+
1.1: "1.1";
|
|
76
77
|
}>;
|
|
77
78
|
}, z.core.$strip>, z.ZodObject<{
|
|
78
79
|
transport: z.ZodLiteral<"WEBSOCKET">;
|
|
@@ -89,11 +90,12 @@ declare const rawModelSchema: z.ZodObject<{
|
|
|
89
90
|
}, z.core.$strip>>;
|
|
90
91
|
enabled: z.ZodBoolean;
|
|
91
92
|
}, z.core.$strip>;
|
|
92
|
-
export interface AgentModelConfiguration extends Omit<z.infer<typeof rawModelSchema>, 'apiKey' | 'credential' | 'credentialProvider' | 'responsesPreviousResponseId' | 'responsesTransport' | 'conversationModel' | 'subagentModel' | 'useResourceUrl'> {
|
|
93
|
+
export interface AgentModelConfiguration extends Omit<z.infer<typeof rawModelSchema>, 'apiKey' | 'socks5Url' | 'credential' | 'credentialProvider' | 'responsesPreviousResponseId' | 'responsesTransport' | 'conversationModel' | 'subagentModel' | 'useResourceUrl'> {
|
|
93
94
|
conversationModel?: boolean;
|
|
94
95
|
subagentModel?: boolean;
|
|
95
96
|
useResourceUrl?: boolean;
|
|
96
97
|
apiKey?: SecretValue;
|
|
98
|
+
socks5Url?: SecretValue;
|
|
97
99
|
credentialProvider?: ModelCredentialProvider;
|
|
98
100
|
/** Whether this Responses endpoint accepts native configuration_update input items. */
|
|
99
101
|
responsesConfigurationUpdates?: boolean;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { AgentError } from '../error.js';
|
|
3
|
+
import { isValidSocks5ProxyUrl } from '../network/http.js';
|
|
3
4
|
import { SecretValue } from '../network/credentials.js';
|
|
4
5
|
export { SecretValue } from '../network/credentials.js';
|
|
5
6
|
const rawResponsesTransportSchema = z.discriminatedUnion('transport', [
|
|
@@ -25,6 +26,7 @@ const modelFieldsSchema = z
|
|
|
25
26
|
protocol: z.enum(['OPENAI_RESPONSES', 'ANTHROPIC_MESSAGES']),
|
|
26
27
|
baseUrl: z.string().url(),
|
|
27
28
|
apiKey: z.string().min(1).max(16_384),
|
|
29
|
+
socks5Url: z.string().refine(isValidSocks5ProxyUrl, 'SOCKS5 proxy URL is invalid.').optional(),
|
|
28
30
|
credentialProvider: z.never().optional(),
|
|
29
31
|
credential: z.never().optional(),
|
|
30
32
|
modelId: z.string().min(1).max(256),
|
|
@@ -112,6 +114,10 @@ const runtimeModelSchema = modelFieldsSchema
|
|
|
112
114
|
.extend({
|
|
113
115
|
// The direct SDK API accepts SecretValue or a live provider, not catalog strings.
|
|
114
116
|
apiKey: z.instanceof(SecretValue).optional(),
|
|
117
|
+
socks5Url: z
|
|
118
|
+
.instanceof(SecretValue)
|
|
119
|
+
.refine((value) => isValidSocks5ProxyUrl(value.reveal()), 'SOCKS5 proxy URL is invalid.')
|
|
120
|
+
.optional(),
|
|
115
121
|
credentialProvider: z
|
|
116
122
|
.custom((value) => typeof value === 'object' &&
|
|
117
123
|
value !== null &&
|
|
@@ -129,6 +135,12 @@ const runtimeModelSchema = modelFieldsSchema
|
|
|
129
135
|
code: 'custom',
|
|
130
136
|
message: 'Exactly one model credential source is required.'
|
|
131
137
|
});
|
|
138
|
+
if (value.socks5Url !== undefined && value.apiKey === undefined)
|
|
139
|
+
context.addIssue({
|
|
140
|
+
code: 'custom',
|
|
141
|
+
path: ['socks5Url'],
|
|
142
|
+
message: 'Model proxies require a static API key.'
|
|
143
|
+
});
|
|
132
144
|
});
|
|
133
145
|
export function usesResponsesConfigurationUpdates(model) {
|
|
134
146
|
return model.protocol === 'OPENAI_RESPONSES' && model.responsesConfigurationUpdates === true;
|
|
@@ -140,10 +152,11 @@ export function normalizeRuntimeModelConfiguration(input) {
|
|
|
140
152
|
throw new AgentError('MAR_AGENT_MODEL_CONFIG_INVALID', 'Model configuration is invalid.', {
|
|
141
153
|
details: { issues: parsed.error.issues.map((issue) => issue.message) }
|
|
142
154
|
});
|
|
143
|
-
const { apiKey, credentialProvider, credential: _credential, responsesTransport, responsesConfigurationUpdates, ...model } = parsed.data;
|
|
155
|
+
const { apiKey, socks5Url, credentialProvider, credential: _credential, responsesTransport, responsesConfigurationUpdates, ...model } = parsed.data;
|
|
144
156
|
return {
|
|
145
157
|
...model,
|
|
146
158
|
...(apiKey === undefined ? {} : { apiKey }),
|
|
159
|
+
...(socks5Url === undefined ? {} : { socks5Url }),
|
|
147
160
|
...(credentialProvider === undefined ? {} : { credentialProvider }),
|
|
148
161
|
...(responsesTransport === undefined ? {} : { responsesTransport }),
|
|
149
162
|
...(responsesConfigurationUpdates === undefined ? {} : { responsesConfigurationUpdates })
|
|
@@ -193,9 +206,10 @@ export function parseModelCatalog(input, options = {}) {
|
|
|
193
206
|
...(parsed.data.defaultModelId === undefined
|
|
194
207
|
? {}
|
|
195
208
|
: { defaultModelId: parsed.data.defaultModelId }),
|
|
196
|
-
models: parsed.data.models.map(({ apiKey, responsesTransport, responsesConfigurationUpdates, credentialProvider: _provider, credential: _credential, ...model }) => ({
|
|
209
|
+
models: parsed.data.models.map(({ apiKey, socks5Url, responsesTransport, responsesConfigurationUpdates, credentialProvider: _provider, credential: _credential, ...model }) => ({
|
|
197
210
|
...model,
|
|
198
211
|
apiKey: new SecretValue(apiKey),
|
|
212
|
+
...(socks5Url === undefined ? {} : { socks5Url: new SecretValue(socks5Url) }),
|
|
199
213
|
...(responsesConfigurationUpdates === undefined ? {} : { responsesConfigurationUpdates }),
|
|
200
214
|
...(responsesTransport === undefined ? {} : { responsesTransport })
|
|
201
215
|
}))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { openAiInput } from './responses-request.js';
|
|
2
2
|
import { AgentError } from '../error.js';
|
|
3
|
-
import { type AgentModelConfiguration, type ModelCredentialAcquireReason } from './configuration.js';
|
|
3
|
+
import { type AgentModelConfiguration, type ModelCredential, type ModelCredentialAcquireReason } from './configuration.js';
|
|
4
4
|
import WebSocket from 'ws';
|
|
5
5
|
import type { ModelAdapter, ModelAttemptDiagnostic, ModelEvent, ModelRequest, ModelTurnSession } from './contracts.js';
|
|
6
6
|
import { ResponsesSessionCache, type ResponsesRequestBody, type ResponsesSessionState } from './responses-session-cache.js';
|
|
@@ -53,7 +53,7 @@ declare class OpenAiResponsesTurnSession implements ModelTurnSession {
|
|
|
53
53
|
readonly reason: ModelCredentialAcquireReason;
|
|
54
54
|
readonly signal: AbortSignal;
|
|
55
55
|
readonly continuation: boolean;
|
|
56
|
-
readonly credentialAcquired: (
|
|
56
|
+
readonly credentialAcquired: (credential: ModelCredential) => void;
|
|
57
57
|
}): Promise<WebSocket>;
|
|
58
58
|
private connectWebSocket;
|
|
59
59
|
}
|
|
@@ -8,7 +8,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
8
8
|
import { describeAgentError, AgentError } from '../error.js';
|
|
9
9
|
import { assertInlineMediaBudget } from './inline-media-budget.js';
|
|
10
10
|
import WebSocket from 'ws';
|
|
11
|
-
import { isRetryableUpstreamOverloadCode, number, parseSse, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
|
|
11
|
+
import { isRetryableUpstreamOverloadCode, number, parseSse, parseResponseJson, redactResponseHeader, responseRedactor, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
|
|
12
12
|
import { connectSocks5Target, fetchModelResponse, isRetryableModelHttpStatus, isRetryableModelTransportError, modelRetryMaxAttempts, isRetryableModelRequestError, modelRetryDelay, waitForModelRetry } from './http.js';
|
|
13
13
|
import { acquireModelCredential, appendModelCredentialHeaders, modelCredentialSensitiveValues } from './runtime-credential.js';
|
|
14
14
|
import { reportModelAttempt } from './attempt-diagnostics.js';
|
|
@@ -268,7 +268,10 @@ export class OpenAiResponsesAdapter {
|
|
|
268
268
|
signal,
|
|
269
269
|
continuation,
|
|
270
270
|
turn,
|
|
271
|
-
credentialAcquired: (
|
|
271
|
+
credentialAcquired: (credential) => {
|
|
272
|
+
latestCredentialRevision = credential.revision;
|
|
273
|
+
diagnosticSecrets = modelCredentialSensitiveValues(credential);
|
|
274
|
+
}
|
|
272
275
|
});
|
|
273
276
|
else {
|
|
274
277
|
response = await fetchResponse(body);
|
|
@@ -533,15 +536,18 @@ export class OpenAiResponsesAdapter {
|
|
|
533
536
|
(event.type === undefined && event.error !== undefined)) {
|
|
534
537
|
const topLevel = record(event.error);
|
|
535
538
|
const nested = record(record(event.response).error);
|
|
536
|
-
const
|
|
539
|
+
const redact = responseRedactor(diagnosticSecrets);
|
|
540
|
+
const code = boundedError(redact(text(event.code) ??
|
|
537
541
|
text(topLevel.code) ??
|
|
538
542
|
text(topLevel.type) ??
|
|
539
543
|
text(nested.code) ??
|
|
540
|
-
text(nested.type)
|
|
541
|
-
|
|
544
|
+
text(nested.type) ??
|
|
545
|
+
''), 80);
|
|
546
|
+
const message = boundedError(redact(text(event.message) ??
|
|
542
547
|
text(topLevel.message) ??
|
|
543
548
|
text(nested.message) ??
|
|
544
|
-
text(event.error)
|
|
549
|
+
text(event.error) ??
|
|
550
|
+
''), 1_000);
|
|
545
551
|
const status = upstreamHttpStatus(event.status, topLevel.status, record(event.response).status, nested.status);
|
|
546
552
|
const connectionLimit = this.configuration.responsesTransport?.transport === 'WEBSOCKET' &&
|
|
547
553
|
isWebSocketConnectionLimitCode(code);
|
|
@@ -552,7 +558,11 @@ export class OpenAiResponsesAdapter {
|
|
|
552
558
|
...(connectionLimit
|
|
553
559
|
? { reason: OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON }
|
|
554
560
|
: {}),
|
|
555
|
-
...(retryable
|
|
561
|
+
...(retryable
|
|
562
|
+
? {
|
|
563
|
+
retryAfter: redactResponseHeader(response?.headers.get('retry-after'), diagnosticSecrets)
|
|
564
|
+
}
|
|
565
|
+
: {}),
|
|
556
566
|
continuation,
|
|
557
567
|
...(this.configuration.responsesTransport?.transport === 'WEBSOCKET'
|
|
558
568
|
? { transport: 'WEBSOCKET' }
|
|
@@ -574,7 +584,7 @@ export class OpenAiResponsesAdapter {
|
|
|
574
584
|
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream ended without a terminal event.', {
|
|
575
585
|
details: {
|
|
576
586
|
reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
|
|
577
|
-
retryAfter: response?.headers.get('retry-after')
|
|
587
|
+
retryAfter: redactResponseHeader(response?.headers.get('retry-after'), diagnosticSecrets),
|
|
578
588
|
continuation,
|
|
579
589
|
...(this.configuration.responsesTransport?.transport === 'WEBSOCKET'
|
|
580
590
|
? { transport: 'WEBSOCKET' }
|
|
@@ -585,13 +595,15 @@ export class OpenAiResponsesAdapter {
|
|
|
585
595
|
}
|
|
586
596
|
}
|
|
587
597
|
function sameResponsesAdapterConfiguration(current, next) {
|
|
588
|
-
const { apiKey: currentApiKey, credentialProvider: currentCredentialProvider, ...currentTransport } = current;
|
|
589
|
-
const { apiKey: nextApiKey, credentialProvider: nextCredentialProvider, ...nextTransport } = next;
|
|
598
|
+
const { apiKey: currentApiKey, socks5Url: currentSocks5Url, credentialProvider: currentCredentialProvider, ...currentTransport } = current;
|
|
599
|
+
const { apiKey: nextApiKey, socks5Url: nextSocks5Url, credentialProvider: nextCredentialProvider, ...nextTransport } = next;
|
|
590
600
|
const credentialsAreRebindable = (currentCredentialProvider !== undefined && nextCredentialProvider !== undefined) ||
|
|
591
601
|
(currentApiKey !== undefined &&
|
|
592
602
|
nextApiKey !== undefined &&
|
|
593
603
|
currentApiKey.reveal() === nextApiKey.reveal());
|
|
594
|
-
return credentialsAreRebindable &&
|
|
604
|
+
return (credentialsAreRebindable &&
|
|
605
|
+
currentSocks5Url?.reveal() === nextSocks5Url?.reveal() &&
|
|
606
|
+
isDeepStrictEqual(currentTransport, nextTransport));
|
|
595
607
|
}
|
|
596
608
|
class OpenAiResponsesTurnSession {
|
|
597
609
|
adapter;
|
|
@@ -858,11 +870,11 @@ class OpenAiResponsesTurnSession {
|
|
|
858
870
|
}
|
|
859
871
|
if (this.state.socket === undefined) {
|
|
860
872
|
const handshakeCredential = await acquireResponsesCredential(input.configuration, input.reason, input.signal);
|
|
861
|
-
input.credentialAcquired(handshakeCredential
|
|
873
|
+
input.credentialAcquired(handshakeCredential);
|
|
862
874
|
await this.connectWebSocket(endpoint, handshakeCredential, input.promptCacheKey, input.signal);
|
|
863
875
|
}
|
|
864
876
|
const requestCredential = await acquireResponsesCredential(input.configuration, input.reason, input.signal);
|
|
865
|
-
input.credentialAcquired(requestCredential
|
|
877
|
+
input.credentialAcquired(requestCredential);
|
|
866
878
|
if (requestCredential.revision !== this.state.credentialRevision ||
|
|
867
879
|
responsesCredentialFingerprint(requestCredential) !== this.state.credentialFingerprint) {
|
|
868
880
|
invalidateResponsesWebSocket(this.state, false);
|
|
@@ -915,7 +927,7 @@ class OpenAiResponsesTurnSession {
|
|
|
915
927
|
})
|
|
916
928
|
});
|
|
917
929
|
try {
|
|
918
|
-
await waitForWebSocketOpen(socket, signal);
|
|
930
|
+
await waitForWebSocketOpen(socket, signal, modelCredentialSensitiveValues(credential));
|
|
919
931
|
}
|
|
920
932
|
catch (error) {
|
|
921
933
|
terminateWebSocket(socket);
|
|
@@ -991,7 +1003,7 @@ async function* parseOpenAiResponsesSse(response, signal, continuation, sensitiv
|
|
|
991
1003
|
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream was interrupted.', {
|
|
992
1004
|
details: {
|
|
993
1005
|
reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
|
|
994
|
-
retryAfter: response.headers.get('retry-after'),
|
|
1006
|
+
retryAfter: redactResponseHeader(response.headers.get('retry-after'), sensitiveValues),
|
|
995
1007
|
continuation
|
|
996
1008
|
},
|
|
997
1009
|
retryable: true,
|
|
@@ -1087,7 +1099,7 @@ function webSocketRequestDiagnostic(body, requestBytes) {
|
|
|
1087
1099
|
webSocketPhase: 'CONNECT'
|
|
1088
1100
|
};
|
|
1089
1101
|
}
|
|
1090
|
-
async function waitForWebSocketOpen(socket, signal) {
|
|
1102
|
+
async function waitForWebSocketOpen(socket, signal, sensitiveValues) {
|
|
1091
1103
|
if (signal.aborted) {
|
|
1092
1104
|
terminateWebSocket(socket);
|
|
1093
1105
|
throw signal.reason;
|
|
@@ -1131,7 +1143,9 @@ async function waitForWebSocketOpen(socket, signal) {
|
|
|
1131
1143
|
details: {
|
|
1132
1144
|
status,
|
|
1133
1145
|
transport: 'WEBSOCKET',
|
|
1134
|
-
...(retryAfterValue === undefined
|
|
1146
|
+
...(retryAfterValue === undefined
|
|
1147
|
+
? {}
|
|
1148
|
+
: { retryAfter: redactResponseHeader(retryAfterValue, sensitiveValues) })
|
|
1135
1149
|
},
|
|
1136
1150
|
...(retryable ? { retryable: true } : {})
|
|
1137
1151
|
}));
|
|
@@ -1259,15 +1273,10 @@ function webSocketMessages(socket, signal, closed) {
|
|
|
1259
1273
|
const text = await webSocketMessageText(item.value);
|
|
1260
1274
|
if (Buffer.byteLength(text) > 16 * 1024 * 1024)
|
|
1261
1275
|
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model response exceeded the size limit.');
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
yield observeModelStreamEvent(event, item.observedAt);
|
|
1267
|
-
}
|
|
1268
|
-
catch (cause) {
|
|
1269
|
-
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model WebSocket contained invalid JSON.', { cause });
|
|
1270
|
-
}
|
|
1276
|
+
const event = parseResponseJson(text, 'Model WebSocket contained invalid JSON.');
|
|
1277
|
+
if (!isWebSocketNonProgressEvent(event))
|
|
1278
|
+
idleDeadline = Date.now() + WEBSOCKET_IDLE_TIMEOUT_MS;
|
|
1279
|
+
yield observeModelStreamEvent(event, item.observedAt);
|
|
1271
1280
|
}
|
|
1272
1281
|
}
|
|
1273
1282
|
finally {
|
package/dist/model/sse.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export declare function observeModelStreamEvent<const T>(value: T, observedAt: number | undefined): T;
|
|
2
2
|
export declare function modelStreamEventObservedAt(value: unknown): number | undefined;
|
|
3
3
|
export declare function parseSse(response: Response, signal: AbortSignal, maxBytes?: number, idleTimeoutMs?: number, sensitiveValues?: readonly string[]): AsyncIterable<unknown>;
|
|
4
|
+
export declare function parseResponseJson(value: string, message: string): unknown;
|
|
5
|
+
export declare function redactResponseHeader(value: string | null | undefined, sensitiveValues: readonly string[], limit?: number): string | null;
|
|
6
|
+
export declare function responseRedactor(sensitiveValues: readonly string[]): (value: string) => string;
|
|
4
7
|
export declare function isRetryableUpstreamOverloadCode(code: string | undefined): boolean;
|
|
5
8
|
export declare function record(value: unknown): Record<string, unknown>;
|
|
6
9
|
export declare function text(value: unknown): string | undefined;
|
package/dist/model/sse.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { AgentError } from '../error.js';
|
|
2
2
|
import { isRetryableModelHttpStatus } from './http.js';
|
|
3
|
+
/**
|
|
4
|
+
* Decodes bounded SSE responses and shares safe JSON/header diagnostics with adapters.
|
|
5
|
+
* The parser owns its reader; adapters own credentials, retries, and request cancellation.
|
|
6
|
+
*/
|
|
3
7
|
const DEFAULT_MODEL_STREAM_IDLE_TIMEOUT_MS = 180_000;
|
|
4
8
|
const streamEventObservedAt = new WeakMap();
|
|
5
9
|
export function observeModelStreamEvent(value, observedAt) {
|
|
@@ -14,10 +18,7 @@ export async function* parseSse(response, signal, maxBytes = 16 * 1024 * 1024, i
|
|
|
14
18
|
if (!response.ok) {
|
|
15
19
|
const redact = responseRedactor(sensitiveValues);
|
|
16
20
|
const body = redact(await readResponseText(response, signal, maxBytes, idleTimeoutMs));
|
|
17
|
-
const header = (name, limit) =>
|
|
18
|
-
const value = response.headers.get(name);
|
|
19
|
-
return value === null ? null : redact(value).slice(0, limit);
|
|
20
|
-
};
|
|
21
|
+
const header = (name, limit) => redactResponseHeader(response.headers.get(name), sensitiveValues, limit);
|
|
21
22
|
const upstream = upstreamError(body);
|
|
22
23
|
const code = upstream?.code ??
|
|
23
24
|
(response.status === 401 || response.status === 403
|
|
@@ -122,12 +123,7 @@ export async function* parseSse(response, signal, maxBytes = 16 * 1024 * 1024, i
|
|
|
122
123
|
.join('\n');
|
|
123
124
|
if (data.length === 0 || data === '[DONE]')
|
|
124
125
|
continue;
|
|
125
|
-
|
|
126
|
-
yield observeModelStreamEvent(JSON.parse(data), observedAt);
|
|
127
|
-
}
|
|
128
|
-
catch (cause) {
|
|
129
|
-
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model SSE contained invalid JSON.', { cause });
|
|
130
|
-
}
|
|
126
|
+
yield observeModelStreamEvent(parseResponseJson(data, 'Model SSE contained invalid JSON.'), observedAt);
|
|
131
127
|
}
|
|
132
128
|
}
|
|
133
129
|
buffer += decoder.decode();
|
|
@@ -220,7 +216,19 @@ async function readStreamChunk(reader, signal, idleTimeoutMs) {
|
|
|
220
216
|
});
|
|
221
217
|
});
|
|
222
218
|
}
|
|
223
|
-
function
|
|
219
|
+
export function parseResponseJson(value, message) {
|
|
220
|
+
try {
|
|
221
|
+
return JSON.parse(value);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
// Native parse errors quote truncated input, which cannot be reliably redacted.
|
|
225
|
+
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', message);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
export function redactResponseHeader(value, sensitiveValues, limit = 128) {
|
|
229
|
+
return value == null ? null : responseRedactor(sensitiveValues)(value).slice(0, limit);
|
|
230
|
+
}
|
|
231
|
+
export function responseRedactor(sensitiveValues) {
|
|
224
232
|
const secrets = [
|
|
225
233
|
...new Set(sensitiveValues.flatMap((value) => value ? [value, JSON.stringify(value).slice(1, -1), encodeURIComponent(value)] : []))
|
|
226
234
|
].sort((left, right) => right.length - left.length);
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { SecretValue, type ModelCredentialProvider, type ModelCredential, type ModelCredentialAcquireReason } from './credentials.js';
|
|
2
|
+
/**
|
|
3
|
+
* Acquires and validates one request's credential snapshot. The caller owns the
|
|
4
|
+
* shared provider; this module owns only request-scoped waits and projections.
|
|
5
|
+
*/
|
|
2
6
|
export declare function acquireModelCredential(configuration: {
|
|
3
7
|
readonly apiKey?: SecretValue;
|
|
8
|
+
readonly socks5Url?: SecretValue | undefined;
|
|
4
9
|
readonly credentialProvider?: ModelCredentialProvider;
|
|
5
10
|
}, reason: ModelCredentialAcquireReason, missingCredentialMessage: string, signal?: AbortSignal): Promise<ModelCredential>;
|
|
6
11
|
export declare function appendModelCredentialHeaders(headers: Headers, credential: ModelCredential, reservedHeaders: ReadonlySet<string>): Headers;
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { AgentError } from '../error.js';
|
|
2
|
+
import { isValidSocks5ProxyUrl } from './http.js';
|
|
2
3
|
import { SecretValue } from './credentials.js';
|
|
4
|
+
/**
|
|
5
|
+
* Acquires and validates one request's credential snapshot. The caller owns the
|
|
6
|
+
* shared provider; this module owns only request-scoped waits and projections.
|
|
7
|
+
*/
|
|
3
8
|
export async function acquireModelCredential(configuration, reason, missingCredentialMessage, signal) {
|
|
4
9
|
signal?.throwIfAborted();
|
|
5
10
|
if (configuration.credentialProvider !== undefined) {
|
|
@@ -14,7 +19,9 @@ export async function acquireModelCredential(configuration, reason, missingCrede
|
|
|
14
19
|
credential.headers === null ||
|
|
15
20
|
typeof credential.headers !== 'object' ||
|
|
16
21
|
Array.isArray(credential.headers) ||
|
|
17
|
-
(credential.socks5Url !== undefined &&
|
|
22
|
+
(credential.socks5Url !== undefined &&
|
|
23
|
+
(!(credential.socks5Url instanceof SecretValue) ||
|
|
24
|
+
!isValidSocks5ProxyUrl(credential.socks5Url.reveal()))))
|
|
18
25
|
throw new AgentError('MAR_AGENT_MODEL_CONFIG_INVALID', 'Dynamic model credential is invalid.');
|
|
19
26
|
return credential;
|
|
20
27
|
}
|
|
@@ -24,7 +31,8 @@ export async function acquireModelCredential(configuration, reason, missingCrede
|
|
|
24
31
|
revision: 0,
|
|
25
32
|
expiresAt: Number.MAX_SAFE_INTEGER,
|
|
26
33
|
bearer: configuration.apiKey,
|
|
27
|
-
headers: {}
|
|
34
|
+
headers: {},
|
|
35
|
+
...(configuration.socks5Url === undefined ? {} : { socks5Url: configuration.socks5Url })
|
|
28
36
|
};
|
|
29
37
|
}
|
|
30
38
|
async function waitForModelCredential(provider, reason, signal) {
|
package/dist/network/http.d.ts
CHANGED
|
@@ -16,5 +16,6 @@ export declare function connectSocks5Target(input: {
|
|
|
16
16
|
readonly requiredAlpnProtocol?: string;
|
|
17
17
|
readonly signal?: AbortSignal;
|
|
18
18
|
}): Promise<Socket>;
|
|
19
|
+
export declare function isValidSocks5ProxyUrl(value: string): boolean;
|
|
19
20
|
export declare function isModelHttpAttempt(value: RequestInit | HttpAttempt): value is HttpAttempt;
|
|
20
21
|
export declare function hasErrorCode(error: unknown, code: string): boolean;
|