orchajs 0.27.1 → 0.27.2

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.
@@ -150,15 +150,18 @@ function toProviderResponse(request, response) {
150
150
  toolCalls.length > 0,
151
151
  response.promptBlockReason !== void 0
152
152
  );
153
- const output = request.outputType === "json" && toolCalls.length === 0 && stopReason !== "max_tokens" ? (0, import_structured_output.parseStructuredOutput)(textOutput, request.outputSchema ?? {}) : textOutput;
154
- return {
155
- output,
156
- responseId: response.responseId,
157
- stopReason,
158
- content,
159
- toolCalls,
160
- usage: normalizeUsage(response.usage)
161
- };
153
+ return (0, import_structured_output.resolveProviderStructuredOutput)(
154
+ request,
155
+ {
156
+ output: textOutput,
157
+ responseId: response.responseId,
158
+ stopReason,
159
+ content,
160
+ toolCalls,
161
+ usage: normalizeUsage(response.usage)
162
+ },
163
+ textOutput
164
+ );
162
165
  }
163
166
  function appendGoogleTextPart(content, part) {
164
167
  const text = part.text ?? "";
@@ -88,10 +88,7 @@ async function generateOpenAI(configuration, request) {
88
88
  }
89
89
  );
90
90
  if (!response.ok) {
91
- const errorBody = await response.json();
92
- throw new Error(
93
- errorBody.error?.message ?? `OpenAI request failed with HTTP ${response.status}.`
94
- );
91
+ throw await (0, import_errors.createProviderHttpError)(response, "OpenAI");
95
92
  }
96
93
  const responseBody = response.headers.get("content-type")?.includes("text/event-stream") ? await readOpenAIStream(response, request.publishOutput) : await response.json();
97
94
  return toProviderResponse(request, responseBody);
@@ -280,18 +277,21 @@ function toProviderResponse(request, response) {
280
277
  );
281
278
  const textOutput = response.output_text ?? content.filter((block) => block.type === "text").map((block) => block.text).join("");
282
279
  const stopReason = normalizeStopReason(response, toolCalls, refused);
283
- const output = request.outputType === "json" && toolCalls.length === 0 && stopReason !== "max_tokens" ? (0, import_structured_output.parseStructuredOutput)(textOutput, request.outputSchema ?? {}) : textOutput;
284
280
  if (textOutput) {
285
281
  request.publishOutput?.(textOutput);
286
282
  }
287
- return {
288
- output,
289
- responseId: response.id,
290
- stopReason,
291
- content,
292
- toolCalls,
293
- usage: normalizeUsage(response.usage)
294
- };
283
+ return (0, import_structured_output.resolveProviderStructuredOutput)(
284
+ request,
285
+ {
286
+ output: textOutput,
287
+ responseId: response.id,
288
+ stopReason,
289
+ content,
290
+ toolCalls,
291
+ usage: normalizeUsage(response.usage)
292
+ },
293
+ textOutput
294
+ );
295
295
  }
296
296
  function parseFunctionArguments(argumentsJson, name) {
297
297
  let parsed;
@@ -986,6 +986,59 @@ class RuntimeAgent {
986
986
  output: streamedOutput
987
987
  };
988
988
  }
989
+ if (error instanceof import_structured_output.StructuredOutputError && error.response) {
990
+ const modelDurationMs2 = Math.round(
991
+ performance.now() - modelStartedAt
992
+ );
993
+ const usage2 = aggregateUsage(
994
+ previousEvents,
995
+ writer.run,
996
+ error.response.usage
997
+ );
998
+ const assistantEvent2 = writer.create("message.created", {
999
+ status: "completed",
1000
+ provider: this.#manifest.provider,
1001
+ model: this.#manifest.model,
1002
+ responseId: error.response.responseId,
1003
+ stopReason: error.response.stopReason,
1004
+ role: "assistant",
1005
+ content: error.response.content,
1006
+ usage: error.response.usage,
1007
+ durationMs: modelDurationMs2
1008
+ });
1009
+ const failedContext = summarizeRunToolFailures(
1010
+ previousEvents,
1011
+ writer.run
1012
+ );
1013
+ const message = failedContext.summary ? `After ${failedContext.summary}: ${error.message}` : error.message;
1014
+ const details = {
1015
+ reason: error.kind,
1016
+ outputType: this.#manifest.outputType,
1017
+ provider: this.#manifest.provider,
1018
+ model: this.#manifest.model,
1019
+ ...error.responsePreview ? { responsePreview: error.responsePreview } : {},
1020
+ ...error.schemaErrors ? { schemaErrors: error.schemaErrors } : {},
1021
+ ...failedContext.failures.length > 0 ? { failedActions: failedContext.failures } : {}
1022
+ };
1023
+ await this.#store.append(sessionId, [
1024
+ assistantEvent2,
1025
+ writer.create("run.failed", {
1026
+ status: "failed",
1027
+ durationMs: elapsedRunDuration(previousEvents, writer.run),
1028
+ usage: usage2,
1029
+ error: {
1030
+ code: "provider_error",
1031
+ message,
1032
+ retryable: true,
1033
+ details
1034
+ }
1035
+ })
1036
+ ]);
1037
+ return failure(sessionId, "provider_error", message, {
1038
+ retryable: true,
1039
+ details
1040
+ });
1041
+ }
989
1042
  if (error instanceof import_errors.OrchaError) {
990
1043
  throw error;
991
1044
  }
@@ -994,7 +1047,7 @@ class RuntimeAgent {
994
1047
  "provider_error",
995
1048
  providerError.message,
996
1049
  {
997
- retryable: true,
1050
+ retryable: providerError.retryable,
998
1051
  cause: error,
999
1052
  details: {
1000
1053
  provider: this.#manifest.provider,
@@ -1007,14 +1060,14 @@ class RuntimeAgent {
1007
1060
  const modelDurationMs = Math.round(performance.now() - modelStartedAt);
1008
1061
  const usage = aggregateUsage(previousEvents, writer.run, response.usage);
1009
1062
  const assistantEvent = writer.create("message.created", {
1010
- status: response.stopReason === "max_tokens" ? "incomplete" : "completed",
1063
+ status: response.stopReason === "max_tokens" || response.stopReason === "content_filter" ? "incomplete" : "completed",
1011
1064
  provider: this.#manifest.provider,
1012
1065
  model: this.#manifest.model,
1013
1066
  responseId: response.responseId,
1014
1067
  stopReason: response.stopReason,
1015
1068
  role: "assistant",
1016
1069
  content: response.content,
1017
- ...this.#manifest.outputType === "json" && response.toolCalls.length === 0 && response.stopReason !== "max_tokens" ? { parsedOutput: response.output } : {},
1070
+ ...this.#manifest.outputType === "json" && response.toolCalls.length === 0 && response.stopReason !== "max_tokens" && response.stopReason !== "content_filter" ? { parsedOutput: response.output } : {},
1018
1071
  usage: response.usage,
1019
1072
  durationMs: modelDurationMs
1020
1073
  });
@@ -1042,6 +1095,33 @@ class RuntimeAgent {
1042
1095
  ]);
1043
1096
  return failure(sessionId, "provider_error", message, { details });
1044
1097
  }
1098
+ if (response.stopReason === "content_filter") {
1099
+ const preview = typeof response.output === "string" && response.output.trim() ? response.output.trim().slice(0, 240) : void 0;
1100
+ const message = preview ? `The model response was blocked by the provider's content filter: ${JSON.stringify(preview)}` : "The model response was blocked by the provider's content filter.";
1101
+ const details = {
1102
+ reason: "content_filter",
1103
+ outputType: this.#manifest.outputType,
1104
+ ...preview ? { responsePreview: preview } : {}
1105
+ };
1106
+ await this.#store.append(sessionId, [
1107
+ assistantEvent,
1108
+ writer.create("run.failed", {
1109
+ status: "failed",
1110
+ durationMs: elapsedRunDuration(previousEvents, writer.run),
1111
+ usage,
1112
+ error: {
1113
+ code: "provider_error",
1114
+ message,
1115
+ retryable: false,
1116
+ details
1117
+ }
1118
+ })
1119
+ ]);
1120
+ return failure(sessionId, "provider_error", message, {
1121
+ retryable: false,
1122
+ details
1123
+ });
1124
+ }
1045
1125
  if (response.toolCalls.length > 0) {
1046
1126
  await this.#store.append(sessionId, [assistantEvent]);
1047
1127
  const eventsAfterAssistant = [...previousEvents, assistantEvent];
@@ -1427,7 +1507,11 @@ class RuntimeAgent {
1427
1507
  events.push(requested);
1428
1508
  const startedAt = performance.now();
1429
1509
  try {
1430
- (0, import_structured_output.validateStructuredValue)(call.arguments, action.parameters);
1510
+ (0, import_structured_output.validateStructuredValue)(
1511
+ call.arguments,
1512
+ action.parameters,
1513
+ `action "${action.name}" parameters`
1514
+ );
1431
1515
  const rawOutput = await (0, import_execute.executeLocalAction)({
1432
1516
  action,
1433
1517
  parameters: call.arguments,
@@ -1442,7 +1526,11 @@ class RuntimeAgent {
1442
1526
  this.#projectRoot
1443
1527
  );
1444
1528
  if (action.outputSchema) {
1445
- (0, import_structured_output.validateStructuredValue)(output, action.outputSchema);
1529
+ (0, import_structured_output.validateStructuredValue)(
1530
+ output,
1531
+ action.outputSchema,
1532
+ `action "${action.name}" outputSchema`
1533
+ );
1446
1534
  }
1447
1535
  const completed = writer.create("action.completed", {
1448
1536
  callId: call.callId,
@@ -1520,7 +1608,11 @@ class RuntimeAgent {
1520
1608
  events.push(requested);
1521
1609
  const startedAt = performance.now();
1522
1610
  try {
1523
- (0, import_structured_output.validateStructuredValue)(call.arguments, tool.parameters);
1611
+ (0, import_structured_output.validateStructuredValue)(
1612
+ call.arguments,
1613
+ tool.parameters,
1614
+ `MCP tool "${call.name}" parameters`
1615
+ );
1524
1616
  const result = await this.#mcp.callTool(
1525
1617
  call.name,
1526
1618
  call.arguments,
@@ -1528,6 +1620,7 @@ class RuntimeAgent {
1528
1620
  );
1529
1621
  const serializedOutput = ensureJsonSerializable(result.output);
1530
1622
  if (result.isError) {
1623
+ const errorDetail = extractMcpErrorDetail(serializedOutput);
1531
1624
  const failed = writer.create("action.failed", {
1532
1625
  callId: call.callId,
1533
1626
  name: call.name,
@@ -1538,7 +1631,7 @@ class RuntimeAgent {
1538
1631
  durationMs: Math.round(performance.now() - startedAt),
1539
1632
  error: {
1540
1633
  code: "mcp_tool_error",
1541
- message: `MCP tool "${call.name}" returned an error.`
1634
+ message: errorDetail ? `MCP tool "${call.name}" returned an error: ${errorDetail}` : `MCP tool "${call.name}" returned an error.`
1542
1635
  }
1543
1636
  });
1544
1637
  await this.#store.append(sessionId, [failed]);
@@ -1948,7 +2041,10 @@ class RuntimeAgent {
1948
2041
  error instanceof Error ? error.message : String(error),
1949
2042
  { retryable: true, cause: error }
1950
2043
  );
1951
- return failure(sessionId, normalized.code, normalized.message);
2044
+ return failure(sessionId, normalized.code, normalized.message, {
2045
+ retryable: normalized.retryable,
2046
+ details: normalized.details
2047
+ });
1952
2048
  } finally {
1953
2049
  this.#sessionControls.delete(sessionId);
1954
2050
  this.#releaseSessionLock(sessionId);
@@ -3309,6 +3405,55 @@ async function withProviderConnectionRetry(operation, signal) {
3309
3405
  return operation();
3310
3406
  }
3311
3407
  }
3408
+ function summarizeRunToolFailures(events, run) {
3409
+ const failures = [];
3410
+ for (const event of events) {
3411
+ if (event.run !== run) continue;
3412
+ if (event.type === "action.failed") {
3413
+ const name = typeof event.data.name === "string" ? event.data.name : "action";
3414
+ const errorRecord = isRecord(event.data.error) ? event.data.error : void 0;
3415
+ const message = typeof errorRecord?.message === "string" && errorRecord.message.trim() ? errorRecord.message.trim() : "action execution failed";
3416
+ failures.push({ kind: "action", name, message });
3417
+ } else if (event.type === "subagent.failed") {
3418
+ const name = typeof event.data.agent === "string" ? event.data.agent : "subagent";
3419
+ const errorRecord = isRecord(event.data.error) ? event.data.error : void 0;
3420
+ const message = typeof errorRecord?.message === "string" && errorRecord.message.trim() ? errorRecord.message.trim() : "subagent execution failed";
3421
+ failures.push({ kind: "subagent", name, message });
3422
+ }
3423
+ }
3424
+ if (failures.length === 0) {
3425
+ return { failures };
3426
+ }
3427
+ const last = failures.at(-1);
3428
+ const label = `${last.kind} "${last.name}" failed (${last.message})`;
3429
+ return {
3430
+ summary: failures.length === 1 ? label : `${label} (+${failures.length - 1} earlier tool failure${failures.length > 2 ? "s" : ""})`,
3431
+ failures
3432
+ };
3433
+ }
3434
+ function extractMcpErrorDetail(output) {
3435
+ if (typeof output === "string" && output.trim()) {
3436
+ return output.trim();
3437
+ }
3438
+ if (!isRecord(output)) {
3439
+ return void 0;
3440
+ }
3441
+ if (typeof output.error === "string" && output.error.trim()) {
3442
+ return output.error.trim();
3443
+ }
3444
+ if (typeof output.message === "string" && output.message.trim()) {
3445
+ return output.message.trim();
3446
+ }
3447
+ if (Array.isArray(output.content)) {
3448
+ const texts = output.content.map(
3449
+ (item) => isRecord(item) && typeof item.text === "string" ? item.text.trim() : ""
3450
+ ).filter(Boolean);
3451
+ if (texts.length > 0) {
3452
+ return texts.join(" ");
3453
+ }
3454
+ }
3455
+ return void 0;
3456
+ }
3312
3457
  function failure(sessionId, code, message, options = {}) {
3313
3458
  const retryable = options.retryable ?? (code === "session_busy" || code === "provider_error" || code === "storage_error");
3314
3459
  return {
@@ -19,30 +19,104 @@ var __copyProps = (to, from, except, desc) => {
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
20
  var structured_output_exports = {};
21
21
  __export(structured_output_exports, {
22
+ StructuredOutputError: () => StructuredOutputError,
22
23
  parseStructuredOutput: () => parseStructuredOutput,
24
+ resolveProviderStructuredOutput: () => resolveProviderStructuredOutput,
23
25
  validateStructuredValue: () => validateStructuredValue
24
26
  });
25
27
  module.exports = __toCommonJS(structured_output_exports);
28
+ class StructuredOutputError extends Error {
29
+ kind;
30
+ rawText;
31
+ responsePreview;
32
+ schemaErrors;
33
+ response;
34
+ constructor(message, options) {
35
+ super(message, { cause: options.cause });
36
+ this.name = "StructuredOutputError";
37
+ this.kind = options.kind;
38
+ this.rawText = options.rawText;
39
+ this.responsePreview = options.responsePreview;
40
+ this.schemaErrors = options.schemaErrors;
41
+ }
42
+ }
43
+ function resolveProviderStructuredOutput(request, baseResponse, textOutput) {
44
+ if (request.outputType !== "json" || baseResponse.toolCalls.length > 0 || baseResponse.stopReason === "max_tokens" || baseResponse.stopReason === "content_filter") {
45
+ return baseResponse;
46
+ }
47
+ try {
48
+ return {
49
+ ...baseResponse,
50
+ output: parseStructuredOutput(
51
+ textOutput,
52
+ request.outputSchema ?? {}
53
+ )
54
+ };
55
+ } catch (error) {
56
+ if (error instanceof StructuredOutputError) {
57
+ error.response = baseResponse;
58
+ }
59
+ throw error;
60
+ }
61
+ }
26
62
  function parseStructuredOutput(text, schema) {
63
+ const preview = previewText(text);
27
64
  const candidate = extractJsonCandidate(text);
28
65
  if (!candidate) {
29
- throw new Error("Model response did not contain a JSON object or array.");
66
+ const suffix = preview ? ` Model returned plain text: ${JSON.stringify(preview)}` : " Model returned an empty response.";
67
+ throw new StructuredOutputError(
68
+ `Model response did not contain a JSON object or array.${suffix}`,
69
+ {
70
+ kind: "missing_json",
71
+ rawText: text,
72
+ responsePreview: preview
73
+ }
74
+ );
30
75
  }
31
76
  let value;
32
77
  try {
33
78
  value = JSON.parse(candidate);
34
79
  } catch (error) {
35
- throw new Error("Model response contained invalid JSON.", { cause: error });
80
+ const detail = error instanceof Error ? error.message : "Invalid JSON";
81
+ const suffix = preview ? ` Model returned: ${JSON.stringify(preview)}` : "";
82
+ throw new StructuredOutputError(
83
+ `Model response contained invalid JSON (${detail}).${suffix}`,
84
+ {
85
+ kind: "invalid_json",
86
+ rawText: text,
87
+ responsePreview: preview,
88
+ cause: error
89
+ }
90
+ );
91
+ }
92
+ const errors = [];
93
+ validateSchemaValue(value, schema, "$", errors);
94
+ if (errors.length > 0) {
95
+ throw new StructuredOutputError(
96
+ `Value failed outputSchema: ${errors.join("; ")}`,
97
+ {
98
+ kind: "schema_mismatch",
99
+ rawText: text,
100
+ responsePreview: preview,
101
+ schemaErrors: errors
102
+ }
103
+ );
36
104
  }
37
- validateStructuredValue(value, schema);
38
105
  return value;
39
106
  }
40
- function validateStructuredValue(value, schema) {
107
+ function validateStructuredValue(value, schema, label = "outputSchema") {
41
108
  const errors = [];
42
109
  validateSchemaValue(value, schema, "$", errors);
43
110
  if (errors.length > 0) {
44
- throw new Error(`Value failed outputSchema: ${errors.join("; ")}`);
111
+ throw new Error(`Value failed ${label}: ${errors.join("; ")}`);
112
+ }
113
+ }
114
+ function previewText(text, maxLength = 240) {
115
+ const compact = text.replace(/\s+/g, " ").trim();
116
+ if (!compact) {
117
+ return void 0;
45
118
  }
119
+ return compact.length > maxLength ? `${compact.slice(0, maxLength)}...` : compact;
46
120
  }
47
121
  function extractJsonCandidate(text) {
48
122
  const trimmed = text.trim();
@@ -140,6 +214,8 @@ function isObject(value) {
140
214
  }
141
215
  // Annotate the CommonJS export names for ESM import in node:
142
216
  0 && (module.exports = {
217
+ StructuredOutputError,
143
218
  parseStructuredOutput,
219
+ resolveProviderStructuredOutput,
144
220
  validateStructuredValue
145
221
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orchajs",
3
- "version": "0.27.1",
3
+ "version": "0.27.2",
4
4
  "description": "A filesystem-convention, stateful agent framework for JavaScript.",
5
5
  "license": "MIT",
6
6
  "repository": {