@adversarylabs/sdk 0.1.41 → 0.1.42

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/README.md CHANGED
@@ -183,6 +183,21 @@ feedback and retries only the final generation call. With repository tools, it r
183
183
  retrieved evidence and citations. Exhaustion raises a non-retryable `ModelReviewError` with code
184
184
  `model_validation_failed` so hosts do not restart the entire adversary review.
185
185
 
186
+ When `validation` is enabled, schema-invalid output rejected by the broker or the
187
+ SDK client (`invalid_model_output`) uses the same bounded final-generation loop,
188
+ before the semantic callback runs. Repair feedback retains schema-owned field
189
+ locations and numeric length limits while excluding quoted rejected text and
190
+ unknown instance keys. Invalid schemas, malformed broker envelopes, cancellation,
191
+ and other model errors retain their existing failure/recovery behavior. Schema and
192
+ semantic repairs share the configured attempt count and original generation deadline.
193
+
194
+ Reported token usage survives client schema rejection and broker error envelopes with
195
+ an optional `usage` field. Repairs aggregate rejected and accepted completions exactly
196
+ once; 100 input / 50 output tokens followed by 10 / 5 returns 110 / 55. Exhausted
197
+ validation and interrupted repairs expose accumulated counts on
198
+ `ModelReviewError.usage`, retaining the error code, retryability, and diagnostics.
199
+ Missing usage stays unavailable rather than being invented as zero.
200
+
186
201
  For repository-scale reviews, add bounded repository tools instead of placing source bodies in
187
202
  `input`. The SDK asks the model which directories and line ranges it needs, performs those reads
188
203
  inside the rule context's repository boundary, and then makes the final structured review call:
package/dist/model.d.ts CHANGED
@@ -79,10 +79,13 @@ export declare class ModelReviewError extends Error {
79
79
  readonly code?: string;
80
80
  readonly retryable: boolean;
81
81
  readonly diagnostics?: Readonly<Record<string, unknown>>;
82
+ /** Reported usage from completed requests, including rejected output. */
83
+ readonly usage?: ModelReviewUsage;
82
84
  constructor(message: string, options?: {
83
85
  code?: string;
84
86
  retryable?: boolean;
85
87
  diagnostics?: Readonly<Record<string, unknown>>;
88
+ usage?: ModelReviewUsage;
86
89
  });
87
90
  }
88
91
  export declare function createModelFromEnvironment(environment?: ModelEnvironment): ReviewModel;
@@ -94,7 +97,7 @@ export declare class BrokerReviewModel implements ReviewModel {
94
97
  review<T = unknown>(request: ModelReviewRequest<T>): Promise<ModelReviewResult<T>>;
95
98
  }
96
99
  /**
97
- * Run adversary-owned semantic validation with SDK-owned bounded regeneration.
100
+ * Run schema and adversary-owned semantic validation with SDK-owned bounded regeneration.
98
101
  *
99
102
  * Each retry receives the validator failure as trusted SDK feedback while retaining the
100
103
  * original input. The original timeout is shared by all validation attempts, and usage is
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,uBAAuB,EACvB,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC;AAE/B,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAClD,eAAO,MAAM,4BAA4B,6BAA6B,CAAC;AACvE,eAAO,MAAM,yBAAyB,0BAA0B,CAAC;AAwCjE,MAAM,WAAW,iBAAiB;IAChC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,qBAAqB,CAAC,CAAC,GAAG,OAAO;IAChD,+FAA+F;IAC/F,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D,wFAAwF;IACxF,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,kBAAkB,CAAC,CAAC,GAAG,OAAO;IAC7C,2EAA2E;IAC3E,eAAe,CAAC,EAAE,cAAc,GAAG,qBAAqB,CAAC;IACzD,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B,UAAU,CAAC,EA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,GAAE,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC,CAAsB,GACpF,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAwD/B"}
package/dist/model.js CHANGED
@@ -18,6 +18,8 @@ const MAX_BROKER_RETRY_DELAY_MS = 5_000;
18
18
  const DEFAULT_VALIDATION_MAXIMUM_ATTEMPTS = 3;
19
19
  const MAX_VALIDATION_MAXIMUM_ATTEMPTS = 5;
20
20
  const MAX_VALIDATION_FEEDBACK_BYTES = 8 << 10;
21
+ // Internal request metadata survives wrapper spreads but never enters broker JSON.
22
+ const outputRepairRequest = Symbol("sdk.output-repair");
21
23
  // Fetch supplies its own five-minute header timeout, overriding Agent defaults.
22
24
  // Override dispatch options for this review only; its shared AbortSignal remains
23
25
  // the authoritative deadline across connection, headers, body, and retries.
@@ -45,11 +47,14 @@ export class ModelReviewError extends Error {
45
47
  code;
46
48
  retryable;
47
49
  diagnostics;
50
+ /** Reported usage from completed requests, including rejected output. */
51
+ usage;
48
52
  constructor(message, options = {}) {
49
53
  super(message);
50
54
  this.name = "ModelReviewError";
51
55
  this.code = options.code;
52
56
  this.diagnostics = options.diagnostics;
57
+ this.usage = options.usage;
53
58
  this.retryable = options.retryable ?? false;
54
59
  }
55
60
  }
@@ -112,28 +117,38 @@ export class BrokerReviewModel {
112
117
  throw new ModelReviewError("Repository model tools require ctx.model so the SDK can enforce the repository boundary.", { code: "invalid_model_request" });
113
118
  }
114
119
  const normalized = normalizeRequest(request);
120
+ const validationOwnsRetries = request[outputRepairRequest] === true;
115
121
  const diagnostics = modelAttemptDiagnostics(normalized.budget.timeoutMs, request.diagnosticStage === "repository_planning" ? "repository_planning" : "model_review");
116
122
  const controller = new AbortController();
117
123
  const timeout = setTimeout(() => controller.abort(), normalized.budget.timeoutMs);
118
124
  const dispatcher = new ModelBrokerDispatcher(normalized.budget.timeoutMs);
125
+ let usage = {};
119
126
  try {
120
127
  for (let attempt = 1; attempt <= this.#maximumAttempts; attempt += 1) {
121
128
  const outcome = await this.#reviewAttempt(normalized, controller.signal, dispatcher, diagnostics, attempt);
122
129
  if (outcome.ok)
123
- return outcome.result;
130
+ return withAccumulatedResultUsage(outcome.result, usage);
124
131
  const error = outcome.error;
125
- if (!(error instanceof ModelReviewError) || !error.retryable)
132
+ if (!(error instanceof ModelReviewError))
126
133
  throw error;
127
- if (controller.signal.aborted) {
134
+ // Only an opted-in validation loop takes ownership of schema retries.
135
+ // Other callers retain the broker's existing retryable-error behavior.
136
+ if (!error.retryable || (validationOwnsRetries && error.code === "invalid_model_output"))
137
+ throw error;
138
+ usage = addModelUsage(usage, error.usage);
139
+ if (controller.signal.aborted)
128
140
  throw exhaustedModelRecovery(attempt, "deadline");
129
- }
130
- if (attempt === this.#maximumAttempts) {
141
+ if (attempt === this.#maximumAttempts)
131
142
  throw exhaustedModelRecovery(attempt, "attempt_limit");
132
- }
133
143
  await this.#waitForRetry(attempt, controller.signal, normalized.budget.timeoutMs, diagnostics);
134
144
  }
135
145
  throw exhaustedModelRecovery(this.#maximumAttempts, "attempt_limit");
136
146
  }
147
+ catch (error) {
148
+ if (!(error instanceof ModelReviewError))
149
+ throw error;
150
+ throw withAccumulatedUsage(error, usage);
151
+ }
137
152
  finally {
138
153
  clearTimeout(timeout);
139
154
  // Cleanup must not replace the typed request error or a successful response.
@@ -219,13 +234,16 @@ export class BrokerReviewModel {
219
234
  }
220
235
  if (!response.ok) {
221
236
  const failure = decoded;
237
+ if (failure.usage !== undefined)
238
+ validateUsage(failure.usage);
222
239
  throw new ModelReviewError(failure.error?.message ?? `Model broker returned HTTP ${response.status}.`, {
223
240
  code: failure.error?.code ?? "model_review_failed",
224
241
  retryable: failure.error?.retryable ?? response.status >= 500,
242
+ ...(failure.usage === undefined ? {} : { usage: failure.usage }),
225
243
  });
226
244
  }
227
245
  const envelope = requireBrokerResponse(decoded);
228
- validateModelOutput(normalized.schema, envelope.output);
246
+ validateModelOutput(normalized.schema, envelope.output, envelope.usage);
229
247
  return {
230
248
  output: envelope.output,
231
249
  provider: envelope.provider,
@@ -235,7 +253,7 @@ export class BrokerReviewModel {
235
253
  }
236
254
  }
237
255
  /**
238
- * Run adversary-owned semantic validation with SDK-owned bounded regeneration.
256
+ * Run schema and adversary-owned semantic validation with SDK-owned bounded regeneration.
239
257
  *
240
258
  * Each retry receives the validator failure as trusted SDK feedback while retaining the
241
259
  * original input. The original timeout is shared by all validation attempts, and usage is
@@ -257,37 +275,148 @@ export async function reviewWithValidation(model, request, decorate = (result) =
257
275
  const elapsed = Date.now() - startedAt;
258
276
  const remainingTimeoutMs = timeoutMs - elapsed;
259
277
  if (remainingTimeoutMs <= 0)
260
- throw exhaustedModelRecovery(attempt - 1, "deadline");
261
- const result = decorate(await model.review({
262
- ...baseRequest,
263
- prompt: feedback === undefined
264
- ? baseRequest.prompt
265
- : `${baseRequest.prompt}\n\nSDK VALIDATION FEEDBACK:\nThe previous response failed adversary-defined validation. Correct the response using this trusted validation result and return the complete response again.\n${JSON.stringify({ attempt, error: feedback })}`,
266
- budget: {
267
- ...baseRequest.budget,
268
- timeoutMs: remainingTimeoutMs,
269
- },
270
- }));
271
- usage = addModelUsage(usage, result.usage);
278
+ throw withAccumulatedUsage(exhaustedModelRecovery(attempt - 1, "deadline"), usage);
279
+ let outcome;
272
280
  try {
273
- await validation.validate(result);
281
+ outcome = await reviewValidationAttempt(model, {
282
+ ...baseRequest,
283
+ prompt: feedback === undefined
284
+ ? baseRequest.prompt
285
+ : `${baseRequest.prompt}\n\nSDK VALIDATION FEEDBACK:\nThe previous response failed output validation. Correct the response using this trusted validation result and return the complete response again.\n${JSON.stringify({ attempt, error: feedback })}`,
286
+ budget: { ...baseRequest.budget, timeoutMs: remainingTimeoutMs },
287
+ }, validation, decorate);
288
+ }
289
+ catch (error) {
290
+ if (!(error instanceof ModelReviewError))
291
+ throw error;
292
+ throw withAccumulatedUsage(error, usage);
293
+ }
294
+ usage = addModelUsage(usage, outcome.ok ? outcome.result.usage : outcome.usage);
295
+ if (outcome.ok) {
274
296
  return {
275
- ...result,
297
+ ...outcome.result,
276
298
  ...(usage.inputTokens === undefined && usage.outputTokens === undefined ? {} : { usage }),
277
299
  };
278
300
  }
279
- catch (error) {
280
- feedback = boundedValidationFeedback(error);
281
- if (attempt === maximumAttempts) {
282
- throw new ModelReviewError(`Model output failed adversary validation after ${maximumAttempts} attempts: ${feedback}`, { code: "model_validation_failed", retryable: false });
283
- }
284
- }
301
+ feedback = outcome.feedback;
302
+ if (attempt === maximumAttempts)
303
+ throw exhaustedOutputValidation(maximumAttempts, feedback, usage);
285
304
  }
286
305
  throw new ModelReviewError("Model validation retry loop exhausted unexpectedly.", {
287
306
  code: "model_validation_failed",
288
307
  retryable: false,
289
308
  });
290
309
  }
310
+ // Keep generation and semantic validation failures together for one prepared
311
+ // request. Neither kind of rejection repeats repository evidence gathering.
312
+ async function reviewValidationAttempt(model, request, validation, decorate) {
313
+ let result;
314
+ try {
315
+ const prepared = { ...request, [outputRepairRequest]: true };
316
+ result = decorate(await model.review(prepared));
317
+ }
318
+ catch (error) {
319
+ if (!(error instanceof ModelReviewError) || error.code !== "invalid_model_output")
320
+ throw error;
321
+ return {
322
+ ok: false,
323
+ feedback: schemaValidationFeedback(error, request.schema),
324
+ usage: error.usage,
325
+ };
326
+ }
327
+ try {
328
+ await validation.validate(result);
329
+ return { ok: true, result };
330
+ }
331
+ catch (error) {
332
+ return { ok: false, feedback: boundedValidationFeedback(error), usage: result.usage };
333
+ }
334
+ }
335
+ function withAccumulatedResultUsage(result, accumulated) {
336
+ const usage = addModelUsage(accumulated, result.usage);
337
+ return {
338
+ ...result,
339
+ ...(usage.inputTokens === undefined && usage.outputTokens === undefined ? {} : { usage }),
340
+ };
341
+ }
342
+ // Keep interruption classification and metadata intact without mutating an error
343
+ // that a model implementation may reuse. Current-error usage is counted once.
344
+ function withAccumulatedUsage(error, usage) {
345
+ if (usage.inputTokens === undefined && usage.outputTokens === undefined)
346
+ return error;
347
+ return new ModelReviewError(error.message, {
348
+ code: error.code,
349
+ retryable: error.retryable,
350
+ diagnostics: error.diagnostics,
351
+ usage: addModelUsage(usage, error.usage),
352
+ });
353
+ }
354
+ function exhaustedOutputValidation(attempts, feedback, usage) {
355
+ return new ModelReviewError(`Model output failed adversary validation after ${attempts} attempts: ${feedback}`, {
356
+ code: "model_validation_failed",
357
+ retryable: false,
358
+ ...(usage.inputTokens === undefined && usage.outputTokens === undefined ? {} : { usage }),
359
+ });
360
+ }
361
+ // Broker pattern/enum errors can quote rejected model text. Retain only schema-owned
362
+ // locations, fixed keywords, numeric limits, and trusted schema descriptions as feedback.
363
+ function schemaValidationFeedback(error, schema) {
364
+ const goLocations = [...error.message.matchAll(/- at '([^'\n]*)': ([^\n]*)/g)];
365
+ const locations = goLocations.length > 0
366
+ ? goLocations
367
+ : [...error.message.matchAll(/data((?:\/[^\s;:]*)*) (must [^;\n]*)/g)];
368
+ const messages = locations.length === 0
369
+ ? [schemaFailureFeedback(undefined, "", schema)]
370
+ : locations
371
+ .slice(0, 32)
372
+ .map((location) => schemaFailureFeedback(location[1], location[2], schema));
373
+ return boundedValidationFeedback(new Error([...new Set(messages)].join("\n")));
374
+ }
375
+ function schemaFailureFeedback(rawPath, detail, schema) {
376
+ let node = schema;
377
+ const safePath = [];
378
+ for (const token of (rawPath ?? "").split("/").filter(Boolean).slice(0, 32)) {
379
+ const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
380
+ const properties = node.properties;
381
+ if (properties && Object.hasOwn(properties, key)) {
382
+ safePath.push(token.slice(0, 128));
383
+ node = properties[key];
384
+ }
385
+ else if (node.type === "array" &&
386
+ /^\d{1,8}$/.test(key) &&
387
+ node.items &&
388
+ typeof node.items === "object") {
389
+ safePath.push(key);
390
+ node = node.items;
391
+ }
392
+ else {
393
+ safePath.push("*");
394
+ node = {};
395
+ }
396
+ }
397
+ const at = rawPath !== undefined ? ` at /${safePath.join("/")}` : "";
398
+ const length = /^(minLength|maxLength): got (\d{1,8}), want (\d{1,8})$/.exec(detail);
399
+ let reason = "Return a complete response that satisfies the supplied schema.";
400
+ if (length) {
401
+ reason = `${length[1]}: got ${length[2]} characters; required ${length[3]}.`;
402
+ }
403
+ else if (/^must NOT have (more|fewer) than \d+ characters$/.test(detail)) {
404
+ reason = detail;
405
+ }
406
+ else if (/^(?:'not' failed|must NOT be valid)$/.test(detail) &&
407
+ typeof node.not === "object" &&
408
+ node.not !== null) {
409
+ const description = node.not.description;
410
+ reason =
411
+ typeof description === "string"
412
+ ? description
413
+ : "The value violates a 'not' schema constraint.";
414
+ }
415
+ else if (/pattern/.test(detail)) {
416
+ reason = "The value does not satisfy its schema pattern.";
417
+ }
418
+ return `Model output does not match the requested schema${at}. ${reason}`;
419
+ }
291
420
  function boundedValidationFeedback(error) {
292
421
  const message = error instanceof Error ? error.message : String(error);
293
422
  const encoded = Buffer.from(message, "utf8");
@@ -479,7 +608,7 @@ function validateUsage(value) {
479
608
  }
480
609
  }
481
610
  }
482
- function validateModelOutput(schema, output) {
611
+ function validateModelOutput(schema, output, usage) {
483
612
  const ajv = new Ajv2020({ allErrors: true, strict: true });
484
613
  let validate;
485
614
  try {
@@ -492,6 +621,7 @@ function validateModelOutput(schema, output) {
492
621
  const detail = ajv.errorsText(validate.errors, { separator: "; " });
493
622
  throw new ModelReviewError(`Model output does not match the requested schema: ${detail}`, {
494
623
  code: "invalid_model_output",
624
+ ...(usage === undefined ? {} : { usage }),
495
625
  });
496
626
  }
497
627
  }
package/dist/model.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAmB,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAOjE,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAA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KAAK,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC;YACnE,MAAM,IAAI,gBAAgB,CACxB,+BAA+B,KAAK,kCAAkC,EACtE;gBACE,IAAI,EAAE,yBAAyB;aAChC,CACF,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,MAA+B,EAAE,MAAe;IAC3E,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3D,IAAI,QAAwC,CAAC;IAC7C,IAAI,CAAC;QACH,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,gBAAgB,CACxB,mCAAmC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAC3F,EAAE,IAAI,EAAE,sBAAsB,EAAE,CACjC,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACtB,MAAM,MAAM,GAAG,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACpE,MAAM,IAAI,gBAAgB,CAAC,qDAAqD,MAAM,EAAE,EAAE;YACxF,IAAI,EAAE,sBAAsB;SAC7B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { Ajv2020 } from \"ajv/dist/2020.js\";\nimport { Agent, type Dispatcher } from \"undici\";\nimport { modelAttemptDiagnostics } from \"./model-diagnostics.js\";\nimport type {\n ModelRepositoryCitation,\n ModelRepositoryRetrieval,\n ModelRepositoryToolOptions,\n} from \"./repository-model.js\";\n\nexport const ADVERSARY_MODEL_PROTOCOL_VERSION = 1;\nexport const ADVERSARY_MODEL_ENDPOINT_ENV = \"ADVERSARY_MODEL_ENDPOINT\";\nexport const ADVERSARY_MODEL_TOKEN_ENV = \"ADVERSARY_MODEL_TOKEN\";\n\nconst DEFAULT_MODEL_TIMEOUT_MS = 600_000;\nconst MAX_MODEL_TIMEOUT_MS = 600_000;\nconst DEFAULT_MAXIMUM_OUTPUT_TOKENS = 8_192;\nconst MAX_MAXIMUM_OUTPUT_TOKENS = 65_536;\nconst MAX_PROMPT_BYTES = 256 << 10;\nconst MAX_INPUT_BYTES = 4 << 20;\nconst MAX_SCHEMA_BYTES = 512 << 10;\nconst MAX_RESPONSE_BYTES = 4 << 20;\nconst DEFAULT_BROKER_MAXIMUM_ATTEMPTS = 3;\nconst DEFAULT_BROKER_RETRY_DELAY_MS = 250;\nconst MAX_BROKER_RETRY_DELAY_MS = 5_000;\nconst DEFAULT_VALIDATION_MAXIMUM_ATTEMPTS = 3;\nconst MAX_VALIDATION_MAXIMUM_ATTEMPTS = 5;\nconst MAX_VALIDATION_FEEDBACK_BYTES = 8 << 10;\n\n// Fetch supplies its own five-minute header timeout, overriding Agent defaults.\n// Override dispatch options for this review only; its shared AbortSignal remains\n// the authoritative deadline across connection, headers, body, and retries.\nclass ModelBrokerDispatcher extends Agent {\n constructor(private readonly deadlineMs: number) {\n super({ connectTimeout: deadlineMs });\n }\n\n override dispatch(\n options: Dispatcher.DispatchOptions,\n handler: Dispatcher.DispatchHandlers,\n ): boolean {\n return super.dispatch(\n {\n ...options,\n headersTimeout: this.deadlineMs,\n bodyTimeout: this.deadlineMs,\n },\n handler,\n );\n }\n}\n\nexport interface ModelReviewBudget {\n maximumOutputTokens?: number;\n timeoutMs?: number;\n}\n\nexport interface ModelReviewValidation<T = unknown> {\n /** Validate a completed model result. Throw to retry generation with the error as feedback. */\n validate(result: ModelReviewResult<T>): void | Promise<void>;\n /** Total generation attempts, including the first. Defaults to 3 and is capped at 5. */\n maximumAttempts?: number;\n}\n\nexport interface ModelReviewRequest<T = unknown> {\n /** Local timing classification only; never sent to the broker or model. */\n diagnosticStage?: \"model_review\" | \"repository_planning\";\n prompt: string;\n input: unknown;\n schema: Record<string, unknown>;\n budget?: ModelReviewBudget;\n validation?: ModelReviewValidation<T>;\n tools?: {\n repository: ModelRepositoryToolOptions;\n };\n}\n\nexport interface ModelReviewUsage {\n inputTokens?: number;\n outputTokens?: number;\n}\n\nexport interface ModelReviewResult<T = unknown> {\n output: T;\n provider: string;\n model: string;\n usage?: ModelReviewUsage;\n citations?: readonly ModelRepositoryCitation[];\n retrieval?: ModelRepositoryRetrieval;\n}\n\nexport interface ReviewModel {\n review<T = unknown>(request: ModelReviewRequest<T>): Promise<ModelReviewResult<T>>;\n}\n\nexport interface BrokerReviewModelOptions {\n maximumAttempts?: number;\n initialRetryDelayMs?: number;\n random?: () => number;\n}\n\n/**\n * Request a short noun-phrase concern suitable after \"I would address …\".\n * Implemented by the SDK via {@link ReviewModel.review} (CLI broker pass-through).\n */\nexport interface ModelConcernRequest {\n /** Free-form title, clause, or draft concern to rewrite. */\n text: string;\n budget?: ModelReviewBudget;\n /**\n * Extra attempts when the model returns a phrase that fails noun-phrase validation.\n * Defaults to 1 retry (2 total attempts).\n */\n maxAttempts?: number;\n}\n\nexport interface ModelConcernResult {\n /** Validated noun phrase (see requireOpinionConcern). */\n concern: string;\n /** False when `text` was already a valid noun phrase (no broker call). */\n rewritten: boolean;\n provider: string;\n model: string;\n usage?: ModelReviewUsage;\n}\n\n/** Rule-context model: broker review plus opinion-concern rewrite. */\nexport type ContextualReviewModel = ReviewModel & {\n concern(request: ModelConcernRequest): Promise<ModelConcernResult>;\n};\n\nexport type ModelEnvironment = Readonly<Record<string, string | undefined>>;\n\ninterface ModelBrokerRequest\n extends Omit<ModelReviewRequest, \"validation\" | \"tools\" | \"diagnosticStage\"> {\n protocolVersion: typeof ADVERSARY_MODEL_PROTOCOL_VERSION;\n}\n\ninterface ModelBrokerResponse {\n protocolVersion: typeof ADVERSARY_MODEL_PROTOCOL_VERSION;\n output: unknown;\n provider: string;\n model: string;\n usage?: ModelReviewUsage;\n}\n\ninterface ModelBrokerErrorResponse {\n error?: {\n code?: string;\n message?: string;\n retryable?: boolean;\n };\n}\n\ntype NormalizedModelReviewRequest = Omit<\n ModelReviewRequest,\n \"budget\" | \"validation\" | \"tools\" | \"diagnosticStage\"\n> & {\n budget: Required<ModelReviewBudget>;\n};\n\nexport class ModelUnavailableError extends Error {\n constructor(message = \"Model review is unavailable for this adversary execution.\") {\n super(message);\n this.name = \"ModelUnavailableError\";\n }\n}\n\nexport class ModelReviewError extends Error {\n readonly code?: string;\n readonly retryable: boolean;\n readonly diagnostics?: Readonly<Record<string, unknown>>;\n\n constructor(\n message: string,\n options: {\n code?: string;\n retryable?: boolean;\n diagnostics?: Readonly<Record<string, unknown>>;\n } = {},\n ) {\n super(message);\n this.name = \"ModelReviewError\";\n this.code = options.code;\n this.diagnostics = options.diagnostics;\n this.retryable = options.retryable ?? false;\n }\n}\n\n// The message carries the code because subprocess runners may only retain stderr.\n// Never include an upstream error body, prompt, or validator feedback here.\nfunction exhaustedModelRecovery(\n attempts: number,\n reason: \"deadline\" | \"attempt_limit\",\n): ModelReviewError {\n return new ModelReviewError(\n `model_request_recovery_exhausted: Model request recovery exhausted after ${attempts} attempt(s) (${reason}).`,\n {\n code: \"model_request_recovery_exhausted\",\n retryable: false,\n diagnostics: Object.freeze({ attempts, reason }),\n },\n );\n}\n\nexport function createModelFromEnvironment(\n environment: ModelEnvironment = process.env,\n): ReviewModel {\n const endpoint = environment[ADVERSARY_MODEL_ENDPOINT_ENV]?.trim();\n const token = environment[ADVERSARY_MODEL_TOKEN_ENV]?.trim();\n if (endpoint === undefined || endpoint === \"\" || token === undefined || token === \"\") {\n return unavailableModel();\n }\n return new BrokerReviewModel(endpoint, token);\n}\n\nexport function unavailableModel(): ReviewModel {\n return Object.freeze({\n async review(): Promise<never> {\n throw new ModelUnavailableError();\n },\n });\n}\n\nexport class BrokerReviewModel implements ReviewModel {\n readonly endpoint: string;\n readonly #token: string;\n readonly #maximumAttempts: number;\n readonly #initialRetryDelayMs: number;\n readonly #random: () => number;\n\n constructor(endpoint: string, token: string, options: BrokerReviewModelOptions = {}) {\n const parsed = new URL(endpoint);\n if (\n parsed.protocol !== \"http:\" ||\n (parsed.hostname !== \"127.0.0.1\" &&\n parsed.hostname !== \"::1\" &&\n parsed.hostname !== \"[::1]\" &&\n parsed.hostname !== \"localhost\")\n ) {\n throw new ModelReviewError(\n \"The model broker endpoint must use HTTP on the local loopback interface.\",\n { code: \"invalid_broker_endpoint\" },\n );\n }\n if (token.trim() === \"\") {\n throw new ModelReviewError(\"The model broker token must not be empty.\", {\n code: \"invalid_broker_token\",\n });\n }\n this.endpoint = parsed.toString();\n this.#token = token;\n const maximumAttempts = options.maximumAttempts ?? DEFAULT_BROKER_MAXIMUM_ATTEMPTS;\n const initialRetryDelayMs = options.initialRetryDelayMs ?? DEFAULT_BROKER_RETRY_DELAY_MS;\n requireIntegerRange(maximumAttempts, \"maximumAttempts\", 1, 5);\n requireIntegerRange(initialRetryDelayMs, \"initialRetryDelayMs\", 0, MAX_BROKER_RETRY_DELAY_MS);\n this.#maximumAttempts = maximumAttempts;\n this.#initialRetryDelayMs = initialRetryDelayMs;\n this.#random = options.random ?? Math.random;\n }\n\n async review<T = unknown>(request: ModelReviewRequest<T>): Promise<ModelReviewResult<T>> {\n if (request.tools?.repository !== undefined) {\n throw new ModelReviewError(\n \"Repository model tools require ctx.model so the SDK can enforce the repository boundary.\",\n { code: \"invalid_model_request\" },\n );\n }\n const normalized = normalizeRequest(request);\n const diagnostics = modelAttemptDiagnostics(\n normalized.budget.timeoutMs,\n request.diagnosticStage === \"repository_planning\" ? \"repository_planning\" : \"model_review\",\n );\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), normalized.budget.timeoutMs);\n const dispatcher = new ModelBrokerDispatcher(normalized.budget.timeoutMs);\n try {\n for (let attempt = 1; attempt <= this.#maximumAttempts; attempt += 1) {\n const outcome = await this.#reviewAttempt<T>(\n normalized,\n controller.signal,\n dispatcher,\n diagnostics,\n attempt,\n );\n if (outcome.ok) return outcome.result;\n const error = outcome.error;\n if (!(error instanceof ModelReviewError) || !error.retryable) throw error;\n if (controller.signal.aborted) {\n throw exhaustedModelRecovery(attempt, \"deadline\");\n }\n if (attempt === this.#maximumAttempts) {\n throw exhaustedModelRecovery(attempt, \"attempt_limit\");\n }\n await this.#waitForRetry(\n attempt,\n controller.signal,\n normalized.budget.timeoutMs,\n diagnostics,\n );\n }\n throw exhaustedModelRecovery(this.#maximumAttempts, \"attempt_limit\");\n } finally {\n clearTimeout(timeout);\n // Cleanup must not replace the typed request error or a successful response.\n try {\n await dispatcher.destroy();\n } catch {\n // The dispatcher is no longer used after this request.\n }\n }\n }\n\n // One attempt owns its timing and error outcome; retry decisions belong to review().\n async #reviewAttempt<T>(\n normalized: NormalizedModelReviewRequest,\n signal: AbortSignal,\n dispatcher: ModelBrokerDispatcher,\n diagnostics: ReturnType<typeof modelAttemptDiagnostics>,\n attempt: number,\n ): Promise<{ ok: true; result: ModelReviewResult<T> } | { ok: false; error: unknown }> {\n const finish = diagnostics.start(attempt);\n try {\n const result = await this.#reviewOnce<T>(normalized, signal, dispatcher);\n finish(\"succeeded\", result.provider, result.model);\n return { ok: true, result };\n } catch (error) {\n finish(\n \"failed\",\n undefined,\n undefined,\n error instanceof ModelReviewError ? error.code : \"broker_unavailable\",\n );\n return { ok: false, error };\n }\n }\n\n // Keep backoff, timeout diagnostics, and error translation together.\n async #waitForRetry(\n attempt: number,\n signal: AbortSignal,\n timeoutMs: number,\n diagnostics: ReturnType<typeof modelAttemptDiagnostics>,\n ): Promise<void> {\n const exponential = Math.min(\n MAX_BROKER_RETRY_DELAY_MS,\n this.#initialRetryDelayMs * 2 ** (attempt - 1),\n );\n const jittered = Math.round(exponential * (0.75 + 0.5 * this.#random()));\n const retryDelayFailed = diagnostics.startRetryDelay(attempt);\n try {\n await waitForRetry(jittered, signal, timeoutMs);\n } catch (error) {\n retryDelayFailed(\n error instanceof ModelReviewError\n ? (error.code ?? \"model_review_failed\")\n : \"model_review_failed\",\n );\n if (error instanceof ModelReviewError && error.retryable) {\n throw exhaustedModelRecovery(attempt, \"deadline\");\n }\n throw error;\n }\n }\n\n async #reviewOnce<T>(\n normalized: NormalizedModelReviewRequest,\n signal: AbortSignal,\n dispatcher: ModelBrokerDispatcher,\n ): Promise<ModelReviewResult<T>> {\n let response: Response;\n try {\n response = await fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${this.#token}`,\n \"content-type\": \"application/json\",\n \"x-adversary-model-protocol\": String(ADVERSARY_MODEL_PROTOCOL_VERSION),\n },\n body: JSON.stringify({\n protocolVersion: ADVERSARY_MODEL_PROTOCOL_VERSION,\n prompt: normalized.prompt,\n input: normalized.input,\n schema: normalized.schema,\n budget: normalized.budget,\n } satisfies ModelBrokerRequest),\n signal,\n dispatcher,\n } as RequestInit & { dispatcher: Dispatcher });\n } catch (error) {\n throw brokerTransportError(error, signal, normalized.budget.timeoutMs);\n }\n\n let body: string;\n try {\n body = await readBoundedResponse(response);\n } catch (error) {\n throw brokerTransportError(error, signal, normalized.budget.timeoutMs);\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(body);\n } catch {\n throw new ModelReviewError(\"Model broker returned malformed JSON.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (!response.ok) {\n const failure = decoded as ModelBrokerErrorResponse;\n throw new ModelReviewError(\n failure.error?.message ?? `Model broker returned HTTP ${response.status}.`,\n {\n code: failure.error?.code ?? \"model_review_failed\",\n retryable: failure.error?.retryable ?? response.status >= 500,\n },\n );\n }\n\n const envelope = requireBrokerResponse(decoded);\n validateModelOutput(normalized.schema, envelope.output);\n return {\n output: envelope.output as T,\n provider: envelope.provider,\n model: envelope.model,\n ...(envelope.usage === undefined ? {} : { usage: envelope.usage }),\n };\n }\n}\n\n/**\n * Run adversary-owned semantic validation with SDK-owned bounded regeneration.\n *\n * Each retry receives the validator failure as trusted SDK feedback while retaining the\n * original input. The original timeout is shared by all validation attempts, and usage is\n * aggregated across them. Repository callers may decorate the raw result with citations before\n * validation without repeating repository retrieval.\n */\nexport async function reviewWithValidation<T>(\n model: ReviewModel,\n request: ModelReviewRequest<T>,\n decorate: (result: ModelReviewResult<T>) => ModelReviewResult<T> = (result) => result,\n): Promise<ModelReviewResult<T>> {\n const validation = request.validation;\n const { validation: _validation, tools: _tools, ...baseRequest } = request;\n if (validation === undefined) return decorate(await model.review<T>(baseRequest));\n\n const maximumAttempts = validation.maximumAttempts ?? DEFAULT_VALIDATION_MAXIMUM_ATTEMPTS;\n requireIntegerRange(\n maximumAttempts,\n \"validation.maximumAttempts\",\n 1,\n MAX_VALIDATION_MAXIMUM_ATTEMPTS,\n );\n const timeoutMs = request.budget?.timeoutMs ?? DEFAULT_MODEL_TIMEOUT_MS;\n const startedAt = Date.now();\n let usage: ModelReviewUsage = {};\n let feedback: string | undefined;\n\n for (let attempt = 1; attempt <= maximumAttempts; attempt += 1) {\n const elapsed = Date.now() - startedAt;\n const remainingTimeoutMs = timeoutMs - elapsed;\n if (remainingTimeoutMs <= 0) throw exhaustedModelRecovery(attempt - 1, \"deadline\");\n const result = decorate(\n await model.review<T>({\n ...baseRequest,\n prompt:\n feedback === undefined\n ? baseRequest.prompt\n : `${baseRequest.prompt}\\n\\nSDK VALIDATION FEEDBACK:\\nThe previous response failed adversary-defined validation. Correct the response using this trusted validation result and return the complete response again.\\n${JSON.stringify({ attempt, error: feedback })}`,\n budget: {\n ...baseRequest.budget,\n timeoutMs: remainingTimeoutMs,\n },\n }),\n );\n usage = addModelUsage(usage, result.usage);\n try {\n await validation.validate(result);\n return {\n ...result,\n ...(usage.inputTokens === undefined && usage.outputTokens === undefined ? {} : { usage }),\n };\n } catch (error) {\n feedback = boundedValidationFeedback(error);\n if (attempt === maximumAttempts) {\n throw new ModelReviewError(\n `Model output failed adversary validation after ${maximumAttempts} attempts: ${feedback}`,\n { code: \"model_validation_failed\", retryable: false },\n );\n }\n }\n }\n throw new ModelReviewError(\"Model validation retry loop exhausted unexpectedly.\", {\n code: \"model_validation_failed\",\n retryable: false,\n });\n}\n\nfunction boundedValidationFeedback(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n const encoded = Buffer.from(message, \"utf8\");\n return encoded.byteLength <= MAX_VALIDATION_FEEDBACK_BYTES\n ? message\n : `${encoded.subarray(0, MAX_VALIDATION_FEEDBACK_BYTES).toString(\"utf8\")}…`;\n}\n\nfunction addModelUsage(\n total: ModelReviewUsage,\n next: ModelReviewUsage | undefined,\n): ModelReviewUsage {\n if (next === undefined) return total;\n return {\n ...(total.inputTokens === undefined && next.inputTokens === undefined\n ? {}\n : { inputTokens: (total.inputTokens ?? 0) + (next.inputTokens ?? 0) }),\n ...(total.outputTokens === undefined && next.outputTokens === undefined\n ? {}\n : { outputTokens: (total.outputTokens ?? 0) + (next.outputTokens ?? 0) }),\n };\n}\n\nasync function waitForRetry(\n delayMs: number,\n signal: AbortSignal,\n timeoutMs: number,\n): Promise<void> {\n if (signal.aborted) {\n throw modelTimeoutError(timeoutMs);\n }\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(modelTimeoutError(timeoutMs));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, delayMs);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nfunction modelTimeoutError(timeoutMs: number): ModelReviewError {\n return new ModelReviewError(`Model review exceeded its ${timeoutMs}ms timeout.`, {\n code: \"model_timeout\",\n retryable: true,\n });\n}\n\nfunction normalizeRequest(request: ModelReviewRequest): NormalizedModelReviewRequest {\n if (typeof request !== \"object\" || request === null) {\n throw new ModelReviewError(\"Model review request must be an object.\", {\n code: \"invalid_model_request\",\n });\n }\n if (typeof request.prompt !== \"string\" || request.prompt.trim() === \"\") {\n throw new ModelReviewError(\"Model review prompt must be a non-empty string.\", {\n code: \"invalid_model_request\",\n });\n }\n const promptBytes = Buffer.byteLength(request.prompt, \"utf8\");\n if (promptBytes > MAX_PROMPT_BYTES) {\n throw new ModelReviewError(`Model review prompt exceeds ${MAX_PROMPT_BYTES} bytes.`, {\n code: \"model_request_too_large\",\n });\n }\n requireJsonSize(request.input, \"input\", MAX_INPUT_BYTES);\n if (\n typeof request.schema !== \"object\" ||\n request.schema === null ||\n Array.isArray(request.schema)\n ) {\n throw new ModelReviewError(\"Model review schema must be a JSON Schema object.\", {\n code: \"invalid_model_schema\",\n });\n }\n requireJsonSize(request.schema, \"schema\", MAX_SCHEMA_BYTES);\n\n const maximumOutputTokens = request.budget?.maximumOutputTokens ?? DEFAULT_MAXIMUM_OUTPUT_TOKENS;\n const timeoutMs = request.budget?.timeoutMs ?? DEFAULT_MODEL_TIMEOUT_MS;\n requireIntegerRange(\n maximumOutputTokens,\n \"budget.maximumOutputTokens\",\n 1,\n MAX_MAXIMUM_OUTPUT_TOKENS,\n );\n requireIntegerRange(timeoutMs, \"budget.timeoutMs\", 1, MAX_MODEL_TIMEOUT_MS);\n return {\n prompt: request.prompt,\n input: request.input,\n schema: request.schema,\n budget: { maximumOutputTokens, timeoutMs },\n };\n}\n\nfunction requireJsonSize(value: unknown, name: string, maximum: number): void {\n let encoded: string | undefined;\n try {\n encoded = JSON.stringify(value);\n } catch (error) {\n throw new ModelReviewError(\n `Model review ${name} must be JSON-serializable: ${error instanceof Error ? error.message : String(error)}`,\n { code: \"invalid_model_request\" },\n );\n }\n if (encoded === undefined) {\n throw new ModelReviewError(`Model review ${name} must be JSON-serializable.`, {\n code: \"invalid_model_request\",\n });\n }\n if (Buffer.byteLength(encoded, \"utf8\") > maximum) {\n throw new ModelReviewError(`Model review ${name} exceeds ${maximum} bytes.`, {\n code: \"model_request_too_large\",\n });\n }\n}\n\nfunction requireIntegerRange(value: number, name: string, minimum: number, maximum: number): void {\n if (!Number.isInteger(value) || value < minimum || value > maximum) {\n throw new ModelReviewError(`${name} must be an integer from ${minimum} through ${maximum}.`, {\n code: \"invalid_model_budget\",\n });\n }\n}\n\nfunction brokerTransportError(\n error: unknown,\n signal: AbortSignal,\n timeoutMs: number,\n): ModelReviewError {\n if (signal.aborted) return modelTimeoutError(timeoutMs);\n if (error instanceof ModelReviewError) return error;\n return new ModelReviewError(\n `Model broker request failed: ${error instanceof Error ? error.message : String(error)}`,\n { code: \"broker_unavailable\", retryable: true },\n );\n}\n\nasync function readBoundedResponse(response: Response): Promise<string> {\n const declared = response.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > MAX_RESPONSE_BYTES) {\n throw new ModelReviewError(`Model broker response exceeds ${MAX_RESPONSE_BYTES} bytes.`, {\n code: \"model_response_too_large\",\n });\n }\n if (response.body === null) {\n return \"\";\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n size += value.byteLength;\n if (size > MAX_RESPONSE_BYTES) {\n await reader.cancel();\n throw new ModelReviewError(`Model broker response exceeds ${MAX_RESPONSE_BYTES} bytes.`, {\n code: \"model_response_too_large\",\n });\n }\n chunks.push(value);\n }\n const joined = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n joined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(joined);\n}\n\nfunction requireBrokerResponse(value: unknown): ModelBrokerResponse {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ModelReviewError(\"Model broker response must be an object.\", {\n code: \"invalid_broker_response\",\n });\n }\n const response = value as Partial<ModelBrokerResponse>;\n if (response.protocolVersion !== ADVERSARY_MODEL_PROTOCOL_VERSION) {\n throw new ModelReviewError(\n `Model broker protocol version must be ${ADVERSARY_MODEL_PROTOCOL_VERSION}.`,\n { code: \"unsupported_model_protocol\" },\n );\n }\n if (typeof response.provider !== \"string\" || response.provider.trim() === \"\") {\n throw new ModelReviewError(\"Model broker response provider must be a non-empty string.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (typeof response.model !== \"string\" || response.model.trim() === \"\") {\n throw new ModelReviewError(\"Model broker response model must be a non-empty string.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (!Object.hasOwn(response, \"output\")) {\n throw new ModelReviewError(\"Model broker response is missing output.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (response.usage !== undefined) {\n validateUsage(response.usage);\n }\n return response as ModelBrokerResponse;\n}\n\nfunction validateUsage(value: unknown): asserts value is ModelReviewUsage {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ModelReviewError(\"Model broker response usage must be an object.\", {\n code: \"invalid_broker_response\",\n });\n }\n for (const field of [\"inputTokens\", \"outputTokens\"] as const) {\n const count = (value as ModelReviewUsage)[field];\n if (count !== undefined && (!Number.isInteger(count) || count < 0)) {\n throw new ModelReviewError(\n `Model broker response usage.${field} must be a non-negative integer.`,\n {\n code: \"invalid_broker_response\",\n },\n );\n }\n }\n}\n\nfunction validateModelOutput(schema: Record<string, unknown>, output: unknown): void {\n const ajv = new Ajv2020({ allErrors: true, strict: true });\n let validate: ReturnType<Ajv2020[\"compile\"]>;\n try {\n validate = ajv.compile(schema);\n } catch (error) {\n throw new ModelReviewError(\n `Model review schema is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { code: \"invalid_model_schema\" },\n );\n }\n if (!validate(output)) {\n const detail = ajv.errorsText(validate.errors, { separator: \"; \" });\n throw new ModelReviewError(`Model output does not match the requested schema: ${detail}`, {\n code: \"invalid_model_output\",\n });\n }\n}\n"]}
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAmB,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,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ent":["import { Ajv2020 } from \"ajv/dist/2020.js\";\nimport { Agent, type Dispatcher } from \"undici\";\nimport { modelAttemptDiagnostics } from \"./model-diagnostics.js\";\nimport type {\n ModelRepositoryCitation,\n ModelRepositoryRetrieval,\n ModelRepositoryToolOptions,\n} from \"./repository-model.js\";\n\nexport const ADVERSARY_MODEL_PROTOCOL_VERSION = 1;\nexport const ADVERSARY_MODEL_ENDPOINT_ENV = \"ADVERSARY_MODEL_ENDPOINT\";\nexport const ADVERSARY_MODEL_TOKEN_ENV = \"ADVERSARY_MODEL_TOKEN\";\n\nconst DEFAULT_MODEL_TIMEOUT_MS = 600_000;\nconst MAX_MODEL_TIMEOUT_MS = 600_000;\nconst DEFAULT_MAXIMUM_OUTPUT_TOKENS = 8_192;\nconst MAX_MAXIMUM_OUTPUT_TOKENS = 65_536;\nconst MAX_PROMPT_BYTES = 256 << 10;\nconst MAX_INPUT_BYTES = 4 << 20;\nconst MAX_SCHEMA_BYTES = 512 << 10;\nconst MAX_RESPONSE_BYTES = 4 << 20;\nconst DEFAULT_BROKER_MAXIMUM_ATTEMPTS = 3;\nconst DEFAULT_BROKER_RETRY_DELAY_MS = 250;\nconst MAX_BROKER_RETRY_DELAY_MS = 5_000;\nconst DEFAULT_VALIDATION_MAXIMUM_ATTEMPTS = 3;\nconst MAX_VALIDATION_MAXIMUM_ATTEMPTS = 5;\nconst MAX_VALIDATION_FEEDBACK_BYTES = 8 << 10;\n// Internal request metadata survives wrapper spreads but never enters broker JSON.\nconst outputRepairRequest = Symbol(\"sdk.output-repair\");\ntype OutputRepairRequest = ModelReviewRequest & { [outputRepairRequest]?: true };\n\n// Fetch supplies its own five-minute header timeout, overriding Agent defaults.\n// Override dispatch options for this review only; its shared AbortSignal remains\n// the authoritative deadline across connection, headers, body, and retries.\nclass ModelBrokerDispatcher extends Agent {\n constructor(private readonly deadlineMs: number) {\n super({ connectTimeout: deadlineMs });\n }\n\n override dispatch(\n options: Dispatcher.DispatchOptions,\n handler: Dispatcher.DispatchHandlers,\n ): boolean {\n return super.dispatch(\n {\n ...options,\n headersTimeout: this.deadlineMs,\n bodyTimeout: this.deadlineMs,\n },\n handler,\n );\n }\n}\n\nexport interface ModelReviewBudget {\n maximumOutputTokens?: number;\n timeoutMs?: number;\n}\n\nexport interface ModelReviewValidation<T = unknown> {\n /** Validate a completed model result. Throw to retry generation with the error as feedback. */\n validate(result: ModelReviewResult<T>): void | Promise<void>;\n /** Total generation attempts, including the first. Defaults to 3 and is capped at 5. */\n maximumAttempts?: number;\n}\n\nexport interface ModelReviewRequest<T = unknown> {\n /** Local timing classification only; never sent to the broker or model. */\n diagnosticStage?: \"model_review\" | \"repository_planning\";\n prompt: string;\n input: unknown;\n schema: Record<string, unknown>;\n budget?: ModelReviewBudget;\n validation?: ModelReviewValidation<T>;\n tools?: {\n repository: ModelRepositoryToolOptions;\n };\n}\n\nexport interface ModelReviewUsage {\n inputTokens?: number;\n outputTokens?: number;\n}\n\nexport interface ModelReviewResult<T = unknown> {\n output: T;\n provider: string;\n model: string;\n usage?: ModelReviewUsage;\n citations?: readonly ModelRepositoryCitation[];\n retrieval?: ModelRepositoryRetrieval;\n}\n\nexport interface ReviewModel {\n review<T = unknown>(request: ModelReviewRequest<T>): Promise<ModelReviewResult<T>>;\n}\n\nexport interface BrokerReviewModelOptions {\n maximumAttempts?: number;\n initialRetryDelayMs?: number;\n random?: () => number;\n}\n\n/**\n * Request a short noun-phrase concern suitable after \"I would address …\".\n * Implemented by the SDK via {@link ReviewModel.review} (CLI broker pass-through).\n */\nexport interface ModelConcernRequest {\n /** Free-form title, clause, or draft concern to rewrite. */\n text: string;\n budget?: ModelReviewBudget;\n /**\n * Extra attempts when the model returns a phrase that fails noun-phrase validation.\n * Defaults to 1 retry (2 total attempts).\n */\n maxAttempts?: number;\n}\n\nexport interface ModelConcernResult {\n /** Validated noun phrase (see requireOpinionConcern). */\n concern: string;\n /** False when `text` was already a valid noun phrase (no broker call). */\n rewritten: boolean;\n provider: string;\n model: string;\n usage?: ModelReviewUsage;\n}\n\n/** Rule-context model: broker review plus opinion-concern rewrite. */\nexport type ContextualReviewModel = ReviewModel & {\n concern(request: ModelConcernRequest): Promise<ModelConcernResult>;\n};\n\nexport type ModelEnvironment = Readonly<Record<string, string | undefined>>;\n\ninterface ModelBrokerRequest\n extends Omit<ModelReviewRequest, \"validation\" | \"tools\" | \"diagnosticStage\"> {\n protocolVersion: typeof ADVERSARY_MODEL_PROTOCOL_VERSION;\n}\n\ninterface ModelBrokerResponse {\n protocolVersion: typeof ADVERSARY_MODEL_PROTOCOL_VERSION;\n output: unknown;\n provider: string;\n model: string;\n usage?: ModelReviewUsage;\n}\n\ninterface ModelBrokerErrorResponse {\n usage?: ModelReviewUsage;\n error?: {\n code?: string;\n message?: string;\n retryable?: boolean;\n };\n}\n\ntype NormalizedModelReviewRequest = Omit<\n ModelReviewRequest,\n \"budget\" | \"validation\" | \"tools\" | \"diagnosticStage\"\n> & {\n budget: Required<ModelReviewBudget>;\n};\n\nexport class ModelUnavailableError extends Error {\n constructor(message = \"Model review is unavailable for this adversary execution.\") {\n super(message);\n this.name = \"ModelUnavailableError\";\n }\n}\n\nexport class ModelReviewError extends Error {\n readonly code?: string;\n readonly retryable: boolean;\n readonly diagnostics?: Readonly<Record<string, unknown>>;\n /** Reported usage from completed requests, including rejected output. */\n readonly usage?: ModelReviewUsage;\n\n constructor(\n message: string,\n options: {\n code?: string;\n retryable?: boolean;\n diagnostics?: Readonly<Record<string, unknown>>;\n usage?: ModelReviewUsage;\n } = {},\n ) {\n super(message);\n this.name = \"ModelReviewError\";\n this.code = options.code;\n this.diagnostics = options.diagnostics;\n this.usage = options.usage;\n this.retryable = options.retryable ?? false;\n }\n}\n\n// The message carries the code because subprocess runners may only retain stderr.\n// Never include an upstream error body, prompt, or validator feedback here.\nfunction exhaustedModelRecovery(\n attempts: number,\n reason: \"deadline\" | \"attempt_limit\",\n): ModelReviewError {\n return new ModelReviewError(\n `model_request_recovery_exhausted: Model request recovery exhausted after ${attempts} attempt(s) (${reason}).`,\n {\n code: \"model_request_recovery_exhausted\",\n retryable: false,\n diagnostics: Object.freeze({ attempts, reason }),\n },\n );\n}\n\nexport function createModelFromEnvironment(\n environment: ModelEnvironment = process.env,\n): ReviewModel {\n const endpoint = environment[ADVERSARY_MODEL_ENDPOINT_ENV]?.trim();\n const token = environment[ADVERSARY_MODEL_TOKEN_ENV]?.trim();\n if (endpoint === undefined || endpoint === \"\" || token === undefined || token === \"\") {\n return unavailableModel();\n }\n return new BrokerReviewModel(endpoint, token);\n}\n\nexport function unavailableModel(): ReviewModel {\n return Object.freeze({\n async review(): Promise<never> {\n throw new ModelUnavailableError();\n },\n });\n}\n\nexport class BrokerReviewModel implements ReviewModel {\n readonly endpoint: string;\n readonly #token: string;\n readonly #maximumAttempts: number;\n readonly #initialRetryDelayMs: number;\n readonly #random: () => number;\n\n constructor(endpoint: string, token: string, options: BrokerReviewModelOptions = {}) {\n const parsed = new URL(endpoint);\n if (\n parsed.protocol !== \"http:\" ||\n (parsed.hostname !== \"127.0.0.1\" &&\n parsed.hostname !== \"::1\" &&\n parsed.hostname !== \"[::1]\" &&\n parsed.hostname !== \"localhost\")\n ) {\n throw new ModelReviewError(\n \"The model broker endpoint must use HTTP on the local loopback interface.\",\n { code: \"invalid_broker_endpoint\" },\n );\n }\n if (token.trim() === \"\") {\n throw new ModelReviewError(\"The model broker token must not be empty.\", {\n code: \"invalid_broker_token\",\n });\n }\n this.endpoint = parsed.toString();\n this.#token = token;\n const maximumAttempts = options.maximumAttempts ?? DEFAULT_BROKER_MAXIMUM_ATTEMPTS;\n const initialRetryDelayMs = options.initialRetryDelayMs ?? DEFAULT_BROKER_RETRY_DELAY_MS;\n requireIntegerRange(maximumAttempts, \"maximumAttempts\", 1, 5);\n requireIntegerRange(initialRetryDelayMs, \"initialRetryDelayMs\", 0, MAX_BROKER_RETRY_DELAY_MS);\n this.#maximumAttempts = maximumAttempts;\n this.#initialRetryDelayMs = initialRetryDelayMs;\n this.#random = options.random ?? Math.random;\n }\n\n async review<T = unknown>(request: ModelReviewRequest<T>): Promise<ModelReviewResult<T>> {\n if (request.tools?.repository !== undefined) {\n throw new ModelReviewError(\n \"Repository model tools require ctx.model so the SDK can enforce the repository boundary.\",\n { code: \"invalid_model_request\" },\n );\n }\n const normalized = normalizeRequest(request);\n const validationOwnsRetries = (request as OutputRepairRequest)[outputRepairRequest] === true;\n const diagnostics = modelAttemptDiagnostics(\n normalized.budget.timeoutMs,\n request.diagnosticStage === \"repository_planning\" ? \"repository_planning\" : \"model_review\",\n );\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), normalized.budget.timeoutMs);\n const dispatcher = new ModelBrokerDispatcher(normalized.budget.timeoutMs);\n let usage: ModelReviewUsage = {};\n try {\n for (let attempt = 1; attempt <= this.#maximumAttempts; attempt += 1) {\n const outcome = await this.#reviewAttempt<T>(\n normalized,\n controller.signal,\n dispatcher,\n diagnostics,\n attempt,\n );\n if (outcome.ok) return withAccumulatedResultUsage(outcome.result, usage);\n const error = outcome.error;\n if (!(error instanceof ModelReviewError)) throw error;\n // Only an opted-in validation loop takes ownership of schema retries.\n // Other callers retain the broker's existing retryable-error behavior.\n if (!error.retryable || (validationOwnsRetries && error.code === \"invalid_model_output\"))\n throw error;\n usage = addModelUsage(usage, error.usage);\n if (controller.signal.aborted) throw exhaustedModelRecovery(attempt, \"deadline\");\n if (attempt === this.#maximumAttempts)\n throw exhaustedModelRecovery(attempt, \"attempt_limit\");\n await this.#waitForRetry(\n attempt,\n controller.signal,\n normalized.budget.timeoutMs,\n diagnostics,\n );\n }\n throw exhaustedModelRecovery(this.#maximumAttempts, \"attempt_limit\");\n } catch (error) {\n if (!(error instanceof ModelReviewError)) throw error;\n throw withAccumulatedUsage(error, usage);\n } finally {\n clearTimeout(timeout);\n // Cleanup must not replace the typed request error or a successful response.\n try {\n await dispatcher.destroy();\n } catch {\n // The dispatcher is no longer used after this request.\n }\n }\n }\n\n // One attempt owns its timing and error outcome; retry decisions belong to review().\n async #reviewAttempt<T>(\n normalized: NormalizedModelReviewRequest,\n signal: AbortSignal,\n dispatcher: ModelBrokerDispatcher,\n diagnostics: ReturnType<typeof modelAttemptDiagnostics>,\n attempt: number,\n ): Promise<{ ok: true; result: ModelReviewResult<T> } | { ok: false; error: unknown }> {\n const finish = diagnostics.start(attempt);\n try {\n const result = await this.#reviewOnce<T>(normalized, signal, dispatcher);\n finish(\"succeeded\", result.provider, result.model);\n return { ok: true, result };\n } catch (error) {\n finish(\n \"failed\",\n undefined,\n undefined,\n error instanceof ModelReviewError ? error.code : \"broker_unavailable\",\n );\n return { ok: false, error };\n }\n }\n\n // Keep backoff, timeout diagnostics, and error translation together.\n async #waitForRetry(\n attempt: number,\n signal: AbortSignal,\n timeoutMs: number,\n diagnostics: ReturnType<typeof modelAttemptDiagnostics>,\n ): Promise<void> {\n const exponential = Math.min(\n MAX_BROKER_RETRY_DELAY_MS,\n this.#initialRetryDelayMs * 2 ** (attempt - 1),\n );\n const jittered = Math.round(exponential * (0.75 + 0.5 * this.#random()));\n const retryDelayFailed = diagnostics.startRetryDelay(attempt);\n try {\n await waitForRetry(jittered, signal, timeoutMs);\n } catch (error) {\n retryDelayFailed(\n error instanceof ModelReviewError\n ? (error.code ?? \"model_review_failed\")\n : \"model_review_failed\",\n );\n if (error instanceof ModelReviewError && error.retryable) {\n throw exhaustedModelRecovery(attempt, \"deadline\");\n }\n throw error;\n }\n }\n\n async #reviewOnce<T>(\n normalized: NormalizedModelReviewRequest,\n signal: AbortSignal,\n dispatcher: ModelBrokerDispatcher,\n ): Promise<ModelReviewResult<T>> {\n let response: Response;\n try {\n response = await fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${this.#token}`,\n \"content-type\": \"application/json\",\n \"x-adversary-model-protocol\": String(ADVERSARY_MODEL_PROTOCOL_VERSION),\n },\n body: JSON.stringify({\n protocolVersion: ADVERSARY_MODEL_PROTOCOL_VERSION,\n prompt: normalized.prompt,\n input: normalized.input,\n schema: normalized.schema,\n budget: normalized.budget,\n } satisfies ModelBrokerRequest),\n signal,\n dispatcher,\n } as RequestInit & { dispatcher: Dispatcher });\n } catch (error) {\n throw brokerTransportError(error, signal, normalized.budget.timeoutMs);\n }\n\n let body: string;\n try {\n body = await readBoundedResponse(response);\n } catch (error) {\n throw brokerTransportError(error, signal, normalized.budget.timeoutMs);\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(body);\n } catch {\n throw new ModelReviewError(\"Model broker returned malformed JSON.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (!response.ok) {\n const failure = decoded as ModelBrokerErrorResponse;\n if (failure.usage !== undefined) validateUsage(failure.usage);\n throw new ModelReviewError(\n failure.error?.message ?? `Model broker returned HTTP ${response.status}.`,\n {\n code: failure.error?.code ?? \"model_review_failed\",\n retryable: failure.error?.retryable ?? response.status >= 500,\n ...(failure.usage === undefined ? {} : { usage: failure.usage }),\n },\n );\n }\n\n const envelope = requireBrokerResponse(decoded);\n validateModelOutput(normalized.schema, envelope.output, envelope.usage);\n return {\n output: envelope.output as T,\n provider: envelope.provider,\n model: envelope.model,\n ...(envelope.usage === undefined ? {} : { usage: envelope.usage }),\n };\n }\n}\n\n/**\n * Run schema and adversary-owned semantic validation with SDK-owned bounded regeneration.\n *\n * Each retry receives the validator failure as trusted SDK feedback while retaining the\n * original input. The original timeout is shared by all validation attempts, and usage is\n * aggregated across them. Repository callers may decorate the raw result with citations before\n * validation without repeating repository retrieval.\n */\nexport async function reviewWithValidation<T>(\n model: ReviewModel,\n request: ModelReviewRequest<T>,\n decorate: (result: ModelReviewResult<T>) => ModelReviewResult<T> = (result) => result,\n): Promise<ModelReviewResult<T>> {\n const validation = request.validation;\n const { validation: _validation, tools: _tools, ...baseRequest } = request;\n if (validation === undefined) return decorate(await model.review<T>(baseRequest));\n\n const maximumAttempts = validation.maximumAttempts ?? DEFAULT_VALIDATION_MAXIMUM_ATTEMPTS;\n requireIntegerRange(\n maximumAttempts,\n \"validation.maximumAttempts\",\n 1,\n MAX_VALIDATION_MAXIMUM_ATTEMPTS,\n );\n const timeoutMs = request.budget?.timeoutMs ?? DEFAULT_MODEL_TIMEOUT_MS;\n const startedAt = Date.now();\n let usage: ModelReviewUsage = {};\n let feedback: string | undefined;\n\n for (let attempt = 1; attempt <= maximumAttempts; attempt += 1) {\n const elapsed = Date.now() - startedAt;\n const remainingTimeoutMs = timeoutMs - elapsed;\n if (remainingTimeoutMs <= 0)\n throw withAccumulatedUsage(exhaustedModelRecovery(attempt - 1, \"deadline\"), usage);\n let outcome: OutputValidationAttempt<T>;\n try {\n outcome = await reviewValidationAttempt(\n model,\n {\n ...baseRequest,\n prompt:\n feedback === undefined\n ? baseRequest.prompt\n : `${baseRequest.prompt}\\n\\nSDK VALIDATION FEEDBACK:\\nThe previous response failed output validation. Correct the response using this trusted validation result and return the complete response again.\\n${JSON.stringify({ attempt, error: feedback })}`,\n budget: { ...baseRequest.budget, timeoutMs: remainingTimeoutMs },\n },\n validation,\n decorate,\n );\n } catch (error) {\n if (!(error instanceof ModelReviewError)) throw error;\n throw withAccumulatedUsage(error, usage);\n }\n usage = addModelUsage(usage, outcome.ok ? outcome.result.usage : outcome.usage);\n if (outcome.ok) {\n return {\n ...outcome.result,\n ...(usage.inputTokens === undefined && usage.outputTokens === undefined ? {} : { usage }),\n };\n }\n feedback = outcome.feedback;\n if (attempt === maximumAttempts)\n throw exhaustedOutputValidation(maximumAttempts, feedback, usage);\n }\n throw new ModelReviewError(\"Model validation retry loop exhausted unexpectedly.\", {\n code: \"model_validation_failed\",\n retryable: false,\n });\n}\n\ntype OutputValidationAttempt<T> =\n | { ok: true; result: ModelReviewResult<T> }\n | { ok: false; feedback: string; usage?: ModelReviewUsage };\n\n// Keep generation and semantic validation failures together for one prepared\n// request. Neither kind of rejection repeats repository evidence gathering.\nasync function reviewValidationAttempt<T>(\n model: ReviewModel,\n request: ModelReviewRequest<T>,\n validation: ModelReviewValidation<T>,\n decorate: (result: ModelReviewResult<T>) => ModelReviewResult<T>,\n): Promise<OutputValidationAttempt<T>> {\n let result: ModelReviewResult<T>;\n try {\n const prepared: OutputRepairRequest = { ...request, [outputRepairRequest]: true };\n result = decorate(await model.review<T>(prepared));\n } catch (error) {\n if (!(error instanceof ModelReviewError) || error.code !== \"invalid_model_output\") throw error;\n return {\n ok: false,\n feedback: schemaValidationFeedback(error, request.schema),\n usage: error.usage,\n };\n }\n try {\n await validation.validate(result);\n return { ok: true, result };\n } catch (error) {\n return { ok: false, feedback: boundedValidationFeedback(error), usage: result.usage };\n }\n}\n\nfunction withAccumulatedResultUsage<T>(\n result: ModelReviewResult<T>,\n accumulated: ModelReviewUsage,\n): ModelReviewResult<T> {\n const usage = addModelUsage(accumulated, result.usage);\n return {\n ...result,\n ...(usage.inputTokens === undefined && usage.outputTokens === undefined ? {} : { usage }),\n };\n}\n\n// Keep interruption classification and metadata intact without mutating an error\n// that a model implementation may reuse. Current-error usage is counted once.\nfunction withAccumulatedUsage(error: ModelReviewError, usage: ModelReviewUsage): ModelReviewError {\n if (usage.inputTokens === undefined && usage.outputTokens === undefined) return error;\n return new ModelReviewError(error.message, {\n code: error.code,\n retryable: error.retryable,\n diagnostics: error.diagnostics,\n usage: addModelUsage(usage, error.usage),\n });\n}\n\nfunction exhaustedOutputValidation(\n attempts: number,\n feedback: string,\n usage: ModelReviewUsage,\n): ModelReviewError {\n return new ModelReviewError(\n `Model output failed adversary validation after ${attempts} attempts: ${feedback}`,\n {\n code: \"model_validation_failed\",\n retryable: false,\n ...(usage.inputTokens === undefined && usage.outputTokens === undefined ? {} : { usage }),\n },\n );\n}\n\n// Broker pattern/enum errors can quote rejected model text. Retain only schema-owned\n// locations, fixed keywords, numeric limits, and trusted schema descriptions as feedback.\nfunction schemaValidationFeedback(\n error: ModelReviewError,\n schema: Record<string, unknown>,\n): string {\n const goLocations = [...error.message.matchAll(/- at '([^'\\n]*)': ([^\\n]*)/g)];\n const locations =\n goLocations.length > 0\n ? goLocations\n : [...error.message.matchAll(/data((?:\\/[^\\s;:]*)*) (must [^;\\n]*)/g)];\n const messages =\n locations.length === 0\n ? [schemaFailureFeedback(undefined, \"\", schema)]\n : locations\n .slice(0, 32)\n .map((location) => schemaFailureFeedback(location[1], location[2], schema));\n return boundedValidationFeedback(new Error([...new Set(messages)].join(\"\\n\")));\n}\n\nfunction schemaFailureFeedback(\n rawPath: string | undefined,\n detail: string,\n schema: Record<string, unknown>,\n): string {\n let node = schema;\n const safePath: string[] = [];\n for (const token of (rawPath ?? \"\").split(\"/\").filter(Boolean).slice(0, 32)) {\n const key = token.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n const properties = node.properties as Record<string, Record<string, unknown>> | undefined;\n if (properties && Object.hasOwn(properties, key)) {\n safePath.push(token.slice(0, 128));\n node = properties[key];\n } else if (\n node.type === \"array\" &&\n /^\\d{1,8}$/.test(key) &&\n node.items &&\n typeof node.items === \"object\"\n ) {\n safePath.push(key);\n node = node.items as Record<string, unknown>;\n } else {\n safePath.push(\"*\");\n node = {};\n }\n }\n const at = rawPath !== undefined ? ` at /${safePath.join(\"/\")}` : \"\";\n const length = /^(minLength|maxLength): got (\\d{1,8}), want (\\d{1,8})$/.exec(detail);\n let reason = \"Return a complete response that satisfies the supplied schema.\";\n if (length) {\n reason = `${length[1]}: got ${length[2]} characters; required ${length[3]}.`;\n } else if (/^must NOT have (more|fewer) than \\d+ characters$/.test(detail)) {\n reason = detail;\n } else if (\n /^(?:'not' failed|must NOT be valid)$/.test(detail) &&\n typeof node.not === \"object\" &&\n node.not !== null\n ) {\n const description = (node.not as Record<string, unknown>).description;\n reason =\n typeof description === \"string\"\n ? description\n : \"The value violates a 'not' schema constraint.\";\n } else if (/pattern/.test(detail)) {\n reason = \"The value does not satisfy its schema pattern.\";\n }\n return `Model output does not match the requested schema${at}. ${reason}`;\n}\n\nfunction boundedValidationFeedback(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n const encoded = Buffer.from(message, \"utf8\");\n return encoded.byteLength <= MAX_VALIDATION_FEEDBACK_BYTES\n ? message\n : `${encoded.subarray(0, MAX_VALIDATION_FEEDBACK_BYTES).toString(\"utf8\")}…`;\n}\n\nfunction addModelUsage(\n total: ModelReviewUsage,\n next: ModelReviewUsage | undefined,\n): ModelReviewUsage {\n if (next === undefined) return total;\n return {\n ...(total.inputTokens === undefined && next.inputTokens === undefined\n ? {}\n : { inputTokens: (total.inputTokens ?? 0) + (next.inputTokens ?? 0) }),\n ...(total.outputTokens === undefined && next.outputTokens === undefined\n ? {}\n : { outputTokens: (total.outputTokens ?? 0) + (next.outputTokens ?? 0) }),\n };\n}\n\nasync function waitForRetry(\n delayMs: number,\n signal: AbortSignal,\n timeoutMs: number,\n): Promise<void> {\n if (signal.aborted) {\n throw modelTimeoutError(timeoutMs);\n }\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(modelTimeoutError(timeoutMs));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, delayMs);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nfunction modelTimeoutError(timeoutMs: number): ModelReviewError {\n return new ModelReviewError(`Model review exceeded its ${timeoutMs}ms timeout.`, {\n code: \"model_timeout\",\n retryable: true,\n });\n}\n\nfunction normalizeRequest(request: ModelReviewRequest): NormalizedModelReviewRequest {\n if (typeof request !== \"object\" || request === null) {\n throw new ModelReviewError(\"Model review request must be an object.\", {\n code: \"invalid_model_request\",\n });\n }\n if (typeof request.prompt !== \"string\" || request.prompt.trim() === \"\") {\n throw new ModelReviewError(\"Model review prompt must be a non-empty string.\", {\n code: \"invalid_model_request\",\n });\n }\n const promptBytes = Buffer.byteLength(request.prompt, \"utf8\");\n if (promptBytes > MAX_PROMPT_BYTES) {\n throw new ModelReviewError(`Model review prompt exceeds ${MAX_PROMPT_BYTES} bytes.`, {\n code: \"model_request_too_large\",\n });\n }\n requireJsonSize(request.input, \"input\", MAX_INPUT_BYTES);\n if (\n typeof request.schema !== \"object\" ||\n request.schema === null ||\n Array.isArray(request.schema)\n ) {\n throw new ModelReviewError(\"Model review schema must be a JSON Schema object.\", {\n code: \"invalid_model_schema\",\n });\n }\n requireJsonSize(request.schema, \"schema\", MAX_SCHEMA_BYTES);\n\n const maximumOutputTokens = request.budget?.maximumOutputTokens ?? DEFAULT_MAXIMUM_OUTPUT_TOKENS;\n const timeoutMs = request.budget?.timeoutMs ?? DEFAULT_MODEL_TIMEOUT_MS;\n requireIntegerRange(\n maximumOutputTokens,\n \"budget.maximumOutputTokens\",\n 1,\n MAX_MAXIMUM_OUTPUT_TOKENS,\n );\n requireIntegerRange(timeoutMs, \"budget.timeoutMs\", 1, MAX_MODEL_TIMEOUT_MS);\n return {\n prompt: request.prompt,\n input: request.input,\n schema: request.schema,\n budget: { maximumOutputTokens, timeoutMs },\n };\n}\n\nfunction requireJsonSize(value: unknown, name: string, maximum: number): void {\n let encoded: string | undefined;\n try {\n encoded = JSON.stringify(value);\n } catch (error) {\n throw new ModelReviewError(\n `Model review ${name} must be JSON-serializable: ${error instanceof Error ? error.message : String(error)}`,\n { code: \"invalid_model_request\" },\n );\n }\n if (encoded === undefined) {\n throw new ModelReviewError(`Model review ${name} must be JSON-serializable.`, {\n code: \"invalid_model_request\",\n });\n }\n if (Buffer.byteLength(encoded, \"utf8\") > maximum) {\n throw new ModelReviewError(`Model review ${name} exceeds ${maximum} bytes.`, {\n code: \"model_request_too_large\",\n });\n }\n}\n\nfunction requireIntegerRange(value: number, name: string, minimum: number, maximum: number): void {\n if (!Number.isInteger(value) || value < minimum || value > maximum) {\n throw new ModelReviewError(`${name} must be an integer from ${minimum} through ${maximum}.`, {\n code: \"invalid_model_budget\",\n });\n }\n}\n\nfunction brokerTransportError(\n error: unknown,\n signal: AbortSignal,\n timeoutMs: number,\n): ModelReviewError {\n if (signal.aborted) return modelTimeoutError(timeoutMs);\n if (error instanceof ModelReviewError) return error;\n return new ModelReviewError(\n `Model broker request failed: ${error instanceof Error ? error.message : String(error)}`,\n { code: \"broker_unavailable\", retryable: true },\n );\n}\n\nasync function readBoundedResponse(response: Response): Promise<string> {\n const declared = response.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > MAX_RESPONSE_BYTES) {\n throw new ModelReviewError(`Model broker response exceeds ${MAX_RESPONSE_BYTES} bytes.`, {\n code: \"model_response_too_large\",\n });\n }\n if (response.body === null) {\n return \"\";\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n size += value.byteLength;\n if (size > MAX_RESPONSE_BYTES) {\n await reader.cancel();\n throw new ModelReviewError(`Model broker response exceeds ${MAX_RESPONSE_BYTES} bytes.`, {\n code: \"model_response_too_large\",\n });\n }\n chunks.push(value);\n }\n const joined = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n joined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(joined);\n}\n\nfunction requireBrokerResponse(value: unknown): ModelBrokerResponse {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ModelReviewError(\"Model broker response must be an object.\", {\n code: \"invalid_broker_response\",\n });\n }\n const response = value as Partial<ModelBrokerResponse>;\n if (response.protocolVersion !== ADVERSARY_MODEL_PROTOCOL_VERSION) {\n throw new ModelReviewError(\n `Model broker protocol version must be ${ADVERSARY_MODEL_PROTOCOL_VERSION}.`,\n { code: \"unsupported_model_protocol\" },\n );\n }\n if (typeof response.provider !== \"string\" || response.provider.trim() === \"\") {\n throw new ModelReviewError(\"Model broker response provider must be a non-empty string.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (typeof response.model !== \"string\" || response.model.trim() === \"\") {\n throw new ModelReviewError(\"Model broker response model must be a non-empty string.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (!Object.hasOwn(response, \"output\")) {\n throw new ModelReviewError(\"Model broker response is missing output.\", {\n code: \"invalid_broker_response\",\n });\n }\n if (response.usage !== undefined) {\n validateUsage(response.usage);\n }\n return response as ModelBrokerResponse;\n}\n\nfunction validateUsage(value: unknown): asserts value is ModelReviewUsage {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ModelReviewError(\"Model broker response usage must be an object.\", {\n code: \"invalid_broker_response\",\n });\n }\n for (const field of [\"inputTokens\", \"outputTokens\"] as const) {\n const count = (value as ModelReviewUsage)[field];\n if (count !== undefined && (!Number.isInteger(count) || count < 0)) {\n throw new ModelReviewError(\n `Model broker response usage.${field} must be a non-negative integer.`,\n {\n code: \"invalid_broker_response\",\n },\n );\n }\n }\n}\n\nfunction validateModelOutput(\n schema: Record<string, unknown>,\n output: unknown,\n usage?: ModelReviewUsage,\n): void {\n const ajv = new Ajv2020({ allErrors: true, strict: true });\n let validate: ReturnType<Ajv2020[\"compile\"]>;\n try {\n validate = ajv.compile(schema);\n } catch (error) {\n throw new ModelReviewError(\n `Model review schema is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { code: \"invalid_model_schema\" },\n );\n }\n if (!validate(output)) {\n const detail = ajv.errorsText(validate.errors, { separator: \"; \" });\n throw new ModelReviewError(`Model output does not match the requested schema: ${detail}`, {\n code: \"invalid_model_output\",\n ...(usage === undefined ? {} : { usage }),\n });\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adversarylabs/sdk",
3
- "version": "0.1.41",
3
+ "version": "0.1.42",
4
4
  "description": "Small TypeScript SDK for authoring Adversaries.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",