@myagentroam/agent 0.13.21 → 0.13.22
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/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 +1 -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;
|
package/dist/network/http.js
CHANGED
|
@@ -2,6 +2,10 @@ import { connect as connectTcp } from 'node:net';
|
|
|
2
2
|
import { connect as connectTls } from 'node:tls';
|
|
3
3
|
import { Client, Socks5ProxyAgent, buildConnector, fetch as undiciFetch } from 'undici';
|
|
4
4
|
import { TransportFault } from './transport-error.js';
|
|
5
|
+
/**
|
|
6
|
+
* Runs request-scoped HTTP transports and SOCKS5/TLS connections. Each attempt
|
|
7
|
+
* owns its dispatcher; connection helpers observe cancellation until handing off a socket.
|
|
8
|
+
*/
|
|
5
9
|
const SOCKS5_HANDSHAKE_TIMEOUT_MS = 10_000;
|
|
6
10
|
export async function fetchWithConnectionTimeout(url, attempt, signal, connectionTimeoutMs) {
|
|
7
11
|
if (signal.aborted)
|
|
@@ -36,7 +40,7 @@ async function fetchHttpAttempt(url, attempt, signal) {
|
|
|
36
40
|
const dispatcher = attempt.socks5Url === undefined
|
|
37
41
|
? http2Client(url)
|
|
38
42
|
: attempt.httpVersion === '2'
|
|
39
|
-
? http2SocksClient(url, attempt.socks5Url)
|
|
43
|
+
? http2SocksClient(url, attempt.socks5Url, signal)
|
|
40
44
|
: new Socks5ProxyAgent(attempt.socks5Url);
|
|
41
45
|
try {
|
|
42
46
|
const response = await undiciFetch(url, {
|
|
@@ -59,7 +63,7 @@ function http2Client(url) {
|
|
|
59
63
|
connect: strictHttp2Connector()
|
|
60
64
|
});
|
|
61
65
|
}
|
|
62
|
-
function http2SocksClient(url, socks5Url) {
|
|
66
|
+
function http2SocksClient(url, socks5Url, signal) {
|
|
63
67
|
return new Client(new URL(url).origin, {
|
|
64
68
|
allowH2: true,
|
|
65
69
|
connect: async (options, callback) => {
|
|
@@ -71,7 +75,8 @@ function http2SocksClient(url, socks5Url) {
|
|
|
71
75
|
tls: true,
|
|
72
76
|
servername: options.servername || options.hostname,
|
|
73
77
|
alpnProtocols: ['h2'],
|
|
74
|
-
requiredAlpnProtocol: 'h2'
|
|
78
|
+
requiredAlpnProtocol: 'h2',
|
|
79
|
+
signal
|
|
75
80
|
});
|
|
76
81
|
callback(null, tlsSocket);
|
|
77
82
|
}
|
|
@@ -92,7 +97,11 @@ export async function connectSocks5Target(input) {
|
|
|
92
97
|
input.targetPort < 1 ||
|
|
93
98
|
input.targetPort > 65_535)
|
|
94
99
|
throw invalidSocks5Proxy();
|
|
95
|
-
|
|
100
|
+
// URL hostnames retain IPv6 brackets; TCP expects the bare address literal.
|
|
101
|
+
const socket = connectTcp({
|
|
102
|
+
host: proxy.hostname.startsWith('[') ? proxy.hostname.slice(1, -1) : proxy.hostname,
|
|
103
|
+
port: proxy.port
|
|
104
|
+
});
|
|
96
105
|
const timeoutError = Object.assign(new Error('SOCKS5 connection timed out.'), {
|
|
97
106
|
code: 'ETIMEDOUT'
|
|
98
107
|
});
|
|
@@ -150,6 +159,17 @@ export async function connectSocks5Target(input) {
|
|
|
150
159
|
input.signal?.removeEventListener('abort', abort);
|
|
151
160
|
}
|
|
152
161
|
}
|
|
162
|
+
export function isValidSocks5ProxyUrl(value) {
|
|
163
|
+
try {
|
|
164
|
+
if (value.length > 2048)
|
|
165
|
+
return false;
|
|
166
|
+
parseSocks5Proxy(value);
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
153
173
|
function parseSocks5Proxy(value) {
|
|
154
174
|
try {
|
|
155
175
|
const url = new URL(value);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { permissionStopFromError } from '../permissions.js';
|
|
2
2
|
import { RuntimeResourceHandles } from '../runtime-resource-handles.js';
|
|
3
|
+
import { textToolInputError } from '../shared/text-input.js';
|
|
3
4
|
import { AgentError, describeAgentError } from '../../error.js';
|
|
4
5
|
import { truncateModelText } from '../../runtime/token-budget.js';
|
|
5
6
|
import { TOOL_EXECUTION_LIMITS as limits } from '../execution-limits.js';
|
|
@@ -159,9 +160,9 @@ export class CodeCells {
|
|
|
159
160
|
'code' in value
|
|
160
161
|
? value.code
|
|
161
162
|
: undefined;
|
|
162
|
-
if (typeof source !== 'string'
|
|
163
|
-
|
|
164
|
-
|
|
163
|
+
if (typeof source !== 'string')
|
|
164
|
+
throw textToolInputError('code', value);
|
|
165
|
+
if (!source.trim() || Buffer.byteLength(source) > limits.codeMaxInputBytes)
|
|
165
166
|
throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Code must be a nonempty bounded JavaScript string.');
|
|
166
167
|
let settings = options({}, false);
|
|
167
168
|
const pragma = /^\/\/ @options:\s*([^\r\n]*)(?:\r?\n|$)/u.exec(source);
|
|
@@ -30,7 +30,7 @@ export const codeModeToolDefinition = {
|
|
|
30
30
|
- Observe only evidence needed for the next decision or verification: use observe.result for original results, observe.text for derived values, and observe.image for image values. Preserve source and failure details needed for reasoning; keep other intermediate data in the cell.
|
|
31
31
|
- Single-tool cells are valid. Keep loops and retries bounded, and do not blindly replay operations with side effects.
|
|
32
32
|
- Evaluates source in a fresh restricted ECMAScript runtime with top-level await and Promise.all. It is not Node.js or a browser. JavaScript globals do not survive between cells; bounded JSON state is available through state.
|
|
33
|
-
- Accepts JavaScript source text. When exposed as a freeform tool, send the source directly; when exposed with a JSON input schema, put the source in its code field. Do not add another JSON wrapper, quoted string, or markdown code fence inside the source.
|
|
33
|
+
- Accepts JavaScript source text. When exposed as a freeform tool, send the source directly; when exposed with a JSON input schema, put the source in its code field. JSON input example: \`{"code":"observe.text(1);"}\`. Do not add another JSON wrapper, quoted string, or markdown code fence inside the source.
|
|
34
34
|
- Keep embedded commands, patches and source in JSON-escaped double-quoted strings when they contain backticks or literal \${...}; escape newlines as \\n, never put literal line breaks inside single- or double-quoted JS strings. JavaScript template literals would interpolate their contents before the tool runs. Do not paste Python literals such as None into JavaScript expressions.
|
|
35
35
|
- Use only standard ECMAScript built-ins and the explicitly documented tools, observe, state, catalog and cell namespaces. Do not use Node.js, browser or Web APIs. Module imports, filesystem and network APIs are unavailable. Obtain external capabilities only through available tools. Use tools.exec to start managed processes when permitted; follow exec_wait's calling guidance for process control.
|
|
36
36
|
|
|
@@ -67,13 +67,15 @@ Inspect before a dependent edit; successful await needs no invented success flag
|
|
|
67
67
|
const inspected = await tools.read({ reads: [{ path: "source.txt" }] });
|
|
68
68
|
const sourceText = inspected.data.results[0].text;
|
|
69
69
|
if (!sourceText?.includes("original=1")) throw new Error("Unexpected source");
|
|
70
|
-
const patched = await tools.apply_patch({
|
|
70
|
+
const patched = await tools.apply_patch({ input: "*** Begin Patch\\n*** Update File: source.txt\\n@@\\n original=1\\n+updated=2\\n*** End Patch" });
|
|
71
71
|
observe.result(patched);
|
|
72
72
|
\`\`\``,
|
|
73
73
|
inputMode: 'freeform',
|
|
74
74
|
inputSchema: {
|
|
75
75
|
type: 'object',
|
|
76
|
-
properties: {
|
|
76
|
+
properties: {
|
|
77
|
+
code: { type: 'string', description: 'JavaScript source for orchestrating tool calls.' }
|
|
78
|
+
},
|
|
77
79
|
required: ['code'],
|
|
78
80
|
additionalProperties: false
|
|
79
81
|
},
|
|
@@ -5,13 +5,14 @@ import { TextDecoder } from 'node:util';
|
|
|
5
5
|
import { AgentError } from '../../error.js';
|
|
6
6
|
import { TOOL_EXECUTION_LIMITS } from '../execution-limits.js';
|
|
7
7
|
import { captureFileChange, reserveFileChangePaths } from '../result-extensions.js';
|
|
8
|
+
import { textToolInputError } from '../shared/text-input.js';
|
|
8
9
|
import { parsePatch } from './apply-patch-parser.js';
|
|
9
10
|
export const applyPatchToolDefinition = {
|
|
10
11
|
name: 'apply_patch',
|
|
11
12
|
allowedCallers: ['direct', 'programmatic'],
|
|
12
13
|
codeModeExposure: 'both',
|
|
13
14
|
parallelSafety: 'safe',
|
|
14
|
-
description: `Preferred for precise, reviewable local edits. Do not batch all task files merely to reduce tool calls. Group only a few tightly coupled edits whose combined patch is quick to generate and review; split broad or independent work into successive bounded patches before composing them.
|
|
15
|
+
description: `Preferred for precise, reviewable local edits. Do not batch all task files merely to reduce tool calls. Group only a few tightly coupled edits whose combined patch is quick to generate and review; split broad or independent work into successive bounded patches before composing them. For freeform calls, submit the *** Begin Patch / *** End Patch text directly, each marker on its own line. For JSON calls, put the complete patch text in the input field. JSON input example: {"input":"*** Begin Patch\\n*** Add File: example.txt\\n+text\\n*** End Patch"}. Surrounding marker whitespace and an optional trailing *** are accepted; incomplete markers or extra text are rejected. Add File content lines, including blank lines, must start with +. Syntax errors include line/column and a bounded excerpt of the submitted patch with a caret at the error. Supports Add File, Update File, Delete File, and Move to. Add File may replace an existing regular file, and Move to may replace an existing regular destination; duplicate operations on the same resolved path remain invalid. Update hunks accept @@ or @@ <change context>. Context-only hunks, including trailing hunks, and unchanged file sections are validated in order but are not written or reported as edits. The patch must include a change or move. Context is searched forward with Codex-style exact, whitespace-tolerant, then common Unicode punctuation-tolerant matching. Syntax and resolved paths are validated before writing, then file units are committed in order. Each file unit is atomic, and a Move keeps its source and destination atomic. On MAR_AGENT_PATCH_PARTIAL, earlier files remain applied; the error lists applied, failed, and pending paths, so retry only failed and pending paths. Existing file permissions, line endings, and final-newline state are preserved. Returns changed file paths and operations with per-file and total line counts when all units succeed. In Code Mode, the Promise resolves on success and rejects with code/message on failure; the returned envelope has data.files and data.totals, not an ok or success flag. Oversized patches are rejected without advertising defensive limits as recommended patch sizes. A first-unit MAR_AGENT_PATCH_CONFLICT applies nothing; hunk match conflicts identify the affected path and hunk so you can reread only that file before retrying.`,
|
|
15
16
|
inputMode: 'freeform',
|
|
16
17
|
outputSchema: {
|
|
17
18
|
type: 'object',
|
|
@@ -51,15 +52,20 @@ export const applyPatchToolDefinition = {
|
|
|
51
52
|
},
|
|
52
53
|
inputSchema: {
|
|
53
54
|
type: 'object',
|
|
54
|
-
properties: {
|
|
55
|
-
|
|
55
|
+
properties: {
|
|
56
|
+
input: {
|
|
57
|
+
type: 'string',
|
|
58
|
+
description: 'Complete patch text, including the *** Begin Patch and *** End Patch markers.'
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
required: ['input'],
|
|
56
62
|
additionalProperties: false
|
|
57
63
|
}
|
|
58
64
|
};
|
|
59
65
|
export function applyPatchToolInput(input) {
|
|
60
|
-
const patch = typeof input === 'string' ? input : input?.
|
|
66
|
+
const patch = typeof input === 'string' ? input : input?.input;
|
|
61
67
|
if (typeof patch !== 'string')
|
|
62
|
-
throw
|
|
68
|
+
throw textToolInputError('input', input);
|
|
63
69
|
return patch;
|
|
64
70
|
}
|
|
65
71
|
const defaultFileOperations = { rename, rm };
|
package/dist/tools/local/exec.js
CHANGED
|
@@ -136,38 +136,38 @@ export const execWaitToolDefinition = {
|
|
|
136
136
|
/** Validate the public entry points before delegating to the single process manager. */
|
|
137
137
|
export function execToolInput(name, value) {
|
|
138
138
|
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
139
|
-
return invalidExecInput();
|
|
139
|
+
return invalidExecInput('Expected an object containing tool arguments.');
|
|
140
140
|
const input = value;
|
|
141
141
|
const allowed = name === 'exec'
|
|
142
142
|
? ['command', 'cwd', 'login', 'timeoutMs', 'yieldMs']
|
|
143
143
|
: ['processId', 'action', 'yieldMs', 'data'];
|
|
144
144
|
if (Object.keys(input).some((key) => !allowed.includes(key)))
|
|
145
|
-
return invalidExecInput();
|
|
145
|
+
return invalidExecInput(`Unexpected fields; expected only: ${allowed.join(', ')}.`);
|
|
146
146
|
if (name === 'exec')
|
|
147
147
|
return parseExecInput(input);
|
|
148
148
|
const action = input.action ?? 'poll';
|
|
149
|
-
if (!['poll', 'write', 'cancel'].includes(
|
|
150
|
-
return invalidExecInput();
|
|
149
|
+
if (typeof action !== 'string' || !['poll', 'write', 'cancel'].includes(action))
|
|
150
|
+
return invalidExecInput("Field 'action' must be one of: poll, write, cancel.");
|
|
151
151
|
return parseExecInput({ ...input, action });
|
|
152
152
|
}
|
|
153
153
|
export function parseExecInput(value) {
|
|
154
|
-
if (!value || typeof value !== 'object')
|
|
155
|
-
return invalidExecInput();
|
|
154
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
155
|
+
return invalidExecInput('Expected an object containing tool arguments.');
|
|
156
156
|
const input = value;
|
|
157
|
-
const action = input.action
|
|
158
|
-
if (!['start', 'poll', 'write', 'cancel'].includes(
|
|
159
|
-
return invalidExecInput();
|
|
160
|
-
const yieldMs = optionalBoundedInteger(input.yieldMs, 0, action === 'poll'
|
|
157
|
+
const action = input.action ?? 'start';
|
|
158
|
+
if (typeof action !== 'string' || !['start', 'poll', 'write', 'cancel'].includes(action))
|
|
159
|
+
return invalidExecInput("Field 'action' must be one of: start, poll, write, cancel.");
|
|
160
|
+
const yieldMs = optionalBoundedInteger('yieldMs', input.yieldMs, 0, action === 'poll'
|
|
161
161
|
? TOOL_EXECUTION_LIMITS.execMaxPollYieldMs
|
|
162
162
|
: TOOL_EXECUTION_LIMITS.execMaxYieldMs);
|
|
163
163
|
if (action === 'start') {
|
|
164
164
|
if (typeof input.command !== 'string' || input.command.trim() === '')
|
|
165
|
-
return invalidExecInput();
|
|
165
|
+
return invalidExecInput("Field 'command' must be a nonblank string.");
|
|
166
166
|
if (input.cwd !== undefined && input.cwd !== null && typeof input.cwd !== 'string')
|
|
167
|
-
return invalidExecInput();
|
|
167
|
+
return invalidExecInput("Field 'cwd' must be a string.");
|
|
168
168
|
if (input.login !== undefined && input.login !== null && typeof input.login !== 'boolean')
|
|
169
|
-
return invalidExecInput();
|
|
170
|
-
const timeoutMs = optionalBoundedInteger(input.timeoutMs, 1, TOOL_EXECUTION_LIMITS.execMaxTimeoutMs);
|
|
169
|
+
return invalidExecInput("Field 'login' must be a boolean.");
|
|
170
|
+
const timeoutMs = optionalBoundedInteger('timeoutMs', input.timeoutMs, 1, TOOL_EXECUTION_LIMITS.execMaxTimeoutMs);
|
|
171
171
|
return {
|
|
172
172
|
...(input.action === 'start' ? { action: 'start' } : {}),
|
|
173
173
|
command: input.command,
|
|
@@ -178,7 +178,7 @@ export function parseExecInput(value) {
|
|
|
178
178
|
};
|
|
179
179
|
}
|
|
180
180
|
if (typeof input.processId !== 'string' || input.processId === '')
|
|
181
|
-
return invalidExecInput();
|
|
181
|
+
return invalidExecInput("Field 'processId' must be a nonempty string.");
|
|
182
182
|
if (action === 'poll')
|
|
183
183
|
return {
|
|
184
184
|
action,
|
|
@@ -187,18 +187,18 @@ export function parseExecInput(value) {
|
|
|
187
187
|
};
|
|
188
188
|
if (action === 'write') {
|
|
189
189
|
if (typeof input.data !== 'string')
|
|
190
|
-
return invalidExecInput();
|
|
190
|
+
return invalidExecInput("Field 'data' must be a string for action 'write'.");
|
|
191
191
|
return { action, processId: input.processId, data: input.data };
|
|
192
192
|
}
|
|
193
193
|
return { action: 'cancel', processId: input.processId };
|
|
194
194
|
}
|
|
195
|
-
function optionalBoundedInteger(value, minimum, maximum) {
|
|
195
|
+
function optionalBoundedInteger(field, value, minimum, maximum) {
|
|
196
196
|
if (value === undefined || value === null)
|
|
197
197
|
return undefined;
|
|
198
198
|
if (!Number.isInteger(value) || value < minimum)
|
|
199
|
-
invalidExecInput();
|
|
199
|
+
invalidExecInput(`Field '${field}' must be an integer at least ${minimum}.`);
|
|
200
200
|
return Math.min(value, maximum);
|
|
201
201
|
}
|
|
202
|
-
function invalidExecInput() {
|
|
203
|
-
throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID',
|
|
202
|
+
function invalidExecInput(message) {
|
|
203
|
+
throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', message);
|
|
204
204
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { open } from 'node:fs/promises';
|
|
3
|
+
import { crc32 } from 'node:zlib';
|
|
3
4
|
import { AgentError } from '../../error.js';
|
|
4
5
|
import { TOOL_EXECUTION_LIMITS } from '../execution-limits.js';
|
|
5
6
|
import { processImage, readImageMetadata } from './image-processing.js';
|
|
@@ -291,6 +292,8 @@ function validateImageContainer(data, mimeType) {
|
|
|
291
292
|
const next = offset + 12 + length;
|
|
292
293
|
if (next > data.length)
|
|
293
294
|
incompleteImage();
|
|
295
|
+
if (crc32(data.subarray(offset + 4, next - 4)) !== data.readUInt32BE(next - 4))
|
|
296
|
+
throw new AgentError('MAR_AGENT_IMAGE_INCOMPLETE', 'PNG chunk checksum is invalid. Repair or recreate the image and read it again.');
|
|
294
297
|
const type = data.toString('ascii', offset + 4, offset + 8);
|
|
295
298
|
if (offset === 8) {
|
|
296
299
|
if (type !== 'IHDR' ||
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { AgentError } from '../../error.js';
|
|
2
|
+
/** Report missing or mistyped text input using only the expected field and actual value type. */
|
|
3
|
+
export function textToolInputError(field, value) {
|
|
4
|
+
const object = value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
5
|
+
const item = object ? value[field] : value;
|
|
6
|
+
const type = item === null ? 'null' : Array.isArray(item) ? 'array' : typeof item;
|
|
7
|
+
const message = object
|
|
8
|
+
? type === 'undefined'
|
|
9
|
+
? `Missing required string field "${field}".`
|
|
10
|
+
: `Expected string field "${field}"; received ${type}.`
|
|
11
|
+
: `Expected a string or an object with string field "${field}"; received ${type}.`;
|
|
12
|
+
return new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', message);
|
|
13
|
+
}
|