orchajs 0.27.1 → 0.27.3

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.
Files changed (37) hide show
  1. package/dist/amarsia/analytics.d.ts +1 -0
  2. package/dist/amarsia/analytics.js +128 -50
  3. package/dist/amarsia/inference.js +4 -9
  4. package/dist/compiler/build-project.js +15 -4
  5. package/dist/compiler/compile.js +53 -11
  6. package/dist/errors.d.ts +2 -0
  7. package/dist/errors.js +128 -9
  8. package/dist/file-content.js +13 -1
  9. package/dist/providers/anthropic.js +6 -12
  10. package/dist/providers/bedrock.js +4 -8
  11. package/dist/providers/deepseek.js +6 -13
  12. package/dist/providers/dependencies.js +15 -4
  13. package/dist/providers/google-gemini.js +4 -9
  14. package/dist/providers/openai.js +6 -13
  15. package/dist/runtime/agent.js +177 -10
  16. package/dist/runtime/create-orcha.js +18 -17
  17. package/dist/runtime/structured-output.d.ts +18 -1
  18. package/dist/runtime/structured-output.js +75 -5
  19. package/dist/testing.js +23 -14
  20. package/dist/types.d.ts +1 -0
  21. package/dist-cjs/amarsia/analytics.js +129 -49
  22. package/dist-cjs/amarsia/inference.js +12 -9
  23. package/dist-cjs/compiler/build-project.js +14 -4
  24. package/dist-cjs/compiler/compile.js +65 -20
  25. package/dist-cjs/errors.js +106 -8
  26. package/dist-cjs/file-content.js +16 -1
  27. package/dist-cjs/providers/anthropic.js +19 -19
  28. package/dist-cjs/providers/bedrock.js +18 -17
  29. package/dist-cjs/providers/deepseek.js +13 -16
  30. package/dist-cjs/providers/dependencies.js +14 -4
  31. package/dist-cjs/providers/google-gemini.js +12 -9
  32. package/dist-cjs/providers/openai.js +13 -13
  33. package/dist-cjs/runtime/agent.js +164 -9
  34. package/dist-cjs/runtime/create-orcha.js +29 -26
  35. package/dist-cjs/runtime/structured-output.js +81 -5
  36. package/dist-cjs/testing.js +30 -16
  37. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { OrchaError } from "./errors.js";
1
2
  const MIME_TYPES = {
2
3
  ".csv": "text/csv",
3
4
  ".doc": "application/msword",
@@ -47,7 +48,18 @@ export function normalizeUrlContent(url, mimeType) {
47
48
  export async function readLocalFileContent(content) {
48
49
  const fsModule = "node:fs/promises";
49
50
  const { readFile } = await import(fsModule);
50
- const bytes = await readFile(content.filePath);
51
+ let bytes;
52
+ try {
53
+ bytes = await readFile(content.filePath);
54
+ }
55
+ catch (error) {
56
+ const reason = error instanceof Error ? error.message : String(error);
57
+ throw new OrchaError("invalid_input", `Failed to read local file "${content.filePath}": ${reason}`, {
58
+ retryable: false,
59
+ cause: error,
60
+ details: { filePath: content.filePath },
61
+ });
62
+ }
51
63
  const base64 = bytes.toString("base64");
52
64
  return {
53
65
  bytes,
@@ -1,6 +1,6 @@
1
- import { OrchaError } from "../errors.js";
1
+ import { createProviderHttpError, OrchaError } from "../errors.js";
2
2
  import { readLocalFileContent } from "../file-content.js";
3
- import { parseStructuredOutput } from "../runtime/structured-output.js";
3
+ import { resolveProviderStructuredOutput } from "../runtime/structured-output.js";
4
4
  import { readServerSentEvents } from "./sse.js";
5
5
  export const anthropicProvider = {
6
6
  name: "anthropic",
@@ -49,8 +49,7 @@ async function generateAnthropic(provider, request) {
49
49
  signal: request.signal,
50
50
  });
51
51
  if (!response.ok) {
52
- const body = (await response.json());
53
- throw new Error(body.error?.message ?? `Anthropic request failed with HTTP ${response.status}.`);
52
+ throw await createProviderHttpError(response, "Anthropic");
54
53
  }
55
54
  const body = response.headers
56
55
  .get("content-type")
@@ -67,16 +66,11 @@ function toProviderResponse(request, body) {
67
66
  .join("");
68
67
  const toolCalls = content.filter((item) => item.type === "tool_call");
69
68
  const stopReason = normalizeStopReason(body.stop_reason);
70
- const output = request.outputType === "json" &&
71
- toolCalls.length === 0 &&
72
- stopReason !== "max_tokens"
73
- ? parseStructuredOutput(textOutput, request.outputSchema ?? {})
74
- : textOutput;
75
69
  if (textOutput && request.publishOutput) {
76
70
  request.publishOutput(textOutput);
77
71
  }
78
- return {
79
- output,
72
+ return resolveProviderStructuredOutput(request, {
73
+ output: textOutput,
80
74
  responseId: body.id,
81
75
  stopReason,
82
76
  content,
@@ -88,7 +82,7 @@ function toProviderResponse(request, body) {
88
82
  cacheReadTokens: body.usage?.cache_read_input_tokens ?? 0,
89
83
  cacheWriteTokens: body.usage?.cache_creation_input_tokens ?? 0,
90
84
  },
91
- };
85
+ }, textOutput);
92
86
  }
93
87
  function normalizeStopReason(reason) {
94
88
  if (reason === undefined || reason === null) {
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
3
3
  import { basename, extname } from "node:path";
4
4
  import { OrchaError } from "../errors.js";
5
5
  import { readLocalFileContent } from "../file-content.js";
6
- import { parseStructuredOutput } from "../runtime/structured-output.js";
6
+ import { resolveProviderStructuredOutput } from "../runtime/structured-output.js";
7
7
  export const bedrockProvider = {
8
8
  name: "bedrock",
9
9
  generate: generateBedrock,
@@ -455,12 +455,8 @@ function toProviderResponse(request, response) {
455
455
  .join("");
456
456
  const toolCalls = response.blocks.filter((block) => block.type === "tool_call");
457
457
  const stopReason = normalizeStopReason(response.stopReason);
458
- return {
459
- output: request.outputType === "json" &&
460
- toolCalls.length === 0 &&
461
- stopReason !== "max_tokens"
462
- ? parseStructuredOutput(textOutput, request.outputSchema ?? {})
463
- : textOutput,
458
+ return resolveProviderStructuredOutput(request, {
459
+ output: textOutput,
464
460
  responseId: response.requestId,
465
461
  stopReason,
466
462
  content: response.blocks,
@@ -472,7 +468,7 @@ function toProviderResponse(request, response) {
472
468
  cacheReadTokens: response.usage?.cacheReadInputTokens ?? 0,
473
469
  cacheWriteTokens: response.usage?.cacheWriteInputTokens ?? 0,
474
470
  },
475
- };
471
+ }, textOutput);
476
472
  }
477
473
  function normalizeStopReason(reason) {
478
474
  if (!reason) {
@@ -1,5 +1,5 @@
1
- import { OrchaError } from "../errors.js";
2
- import { parseStructuredOutput } from "../runtime/structured-output.js";
1
+ import { createProviderHttpError, OrchaError } from "../errors.js";
2
+ import { resolveProviderStructuredOutput } from "../runtime/structured-output.js";
3
3
  import { readServerSentEvents } from "./sse.js";
4
4
  export const deepSeekProvider = {
5
5
  name: "deepseek",
@@ -54,9 +54,7 @@ async function generateDeepSeek(configuration, request) {
54
54
  signal: request.signal,
55
55
  });
56
56
  if (!response.ok) {
57
- const error = (await response.json());
58
- throw new Error(error.error?.message ??
59
- `DeepSeek request failed with HTTP ${response.status}.`);
57
+ throw await createProviderHttpError(response, "DeepSeek");
60
58
  }
61
59
  const collected = await collectDeepSeekStream(response, request.publishOutput);
62
60
  return toProviderResponse(request, collected);
@@ -214,19 +212,14 @@ function toProviderResponse(request, response) {
214
212
  }
215
213
  const toolCalls = content.filter((block) => block.type === "tool_call");
216
214
  const stopReason = normalizeStopReason(response.finishReason, toolCalls);
217
- const output = request.outputType === "json" &&
218
- toolCalls.length === 0 &&
219
- stopReason !== "max_tokens"
220
- ? parseStructuredOutput(response.content, request.outputSchema ?? {})
221
- : response.content;
222
- return {
223
- output,
215
+ return resolveProviderStructuredOutput(request, {
216
+ output: response.content,
224
217
  responseId: response.id,
225
218
  stopReason,
226
219
  content,
227
220
  toolCalls,
228
221
  usage: normalizeUsage(response.usage),
229
- };
222
+ }, response.content);
230
223
  }
231
224
  function parseToolArguments(value, toolName) {
232
225
  let parsed;
@@ -99,10 +99,21 @@ async function readDeclaredPackages(projectRoot) {
99
99
  return declared;
100
100
  }
101
101
  function allCompiledAgents(agents) {
102
- return Object.values(agents).flatMap((agent) => [
103
- agent,
104
- ...Object.values(agent.subagents ?? {}),
105
- ]);
102
+ const collected = [];
103
+ const visited = new Set();
104
+ const visit = (agent) => {
105
+ if (visited.has(agent))
106
+ return;
107
+ visited.add(agent);
108
+ collected.push(agent);
109
+ for (const child of Object.values(agent.subagents ?? {})) {
110
+ visit(child);
111
+ }
112
+ };
113
+ for (const agent of Object.values(agents)) {
114
+ visit(agent);
115
+ }
116
+ return collected;
106
117
  }
107
118
  function isInstalled(packageName, projectRoot) {
108
119
  try {
@@ -1,6 +1,6 @@
1
1
  import { OrchaError } from "../errors.js";
2
2
  import { readLocalFileContent } from "../file-content.js";
3
- import { parseStructuredOutput } from "../runtime/structured-output.js";
3
+ import { resolveProviderStructuredOutput } from "../runtime/structured-output.js";
4
4
  export function toGoogleContentClient(client) {
5
5
  if (typeof client !== "object" ||
6
6
  client === null ||
@@ -131,19 +131,14 @@ function toProviderResponse(request, response) {
131
131
  .map((block) => block.text)
132
132
  .join("");
133
133
  const stopReason = normalizeStopReason(response.finishReason, toolCalls.length > 0, response.promptBlockReason !== undefined);
134
- const output = request.outputType === "json" &&
135
- toolCalls.length === 0 &&
136
- stopReason !== "max_tokens"
137
- ? parseStructuredOutput(textOutput, request.outputSchema ?? {})
138
- : textOutput;
139
- return {
140
- output,
134
+ return resolveProviderStructuredOutput(request, {
135
+ output: textOutput,
141
136
  responseId: response.responseId,
142
137
  stopReason,
143
138
  content,
144
139
  toolCalls,
145
140
  usage: normalizeUsage(response.usage),
146
- };
141
+ }, textOutput);
147
142
  }
148
143
  function appendGoogleTextPart(content, part) {
149
144
  const text = part.text ?? "";
@@ -1,6 +1,6 @@
1
- import { OrchaError } from "../errors.js";
1
+ import { createProviderHttpError, OrchaError } from "../errors.js";
2
2
  import { readLocalFileContent } from "../file-content.js";
3
- import { parseStructuredOutput } from "../runtime/structured-output.js";
3
+ import { resolveProviderStructuredOutput } from "../runtime/structured-output.js";
4
4
  import { readServerSentEvents } from "./sse.js";
5
5
  export const openAIProvider = {
6
6
  name: "openai",
@@ -58,9 +58,7 @@ async function generateOpenAI(configuration, request) {
58
58
  signal: request.signal,
59
59
  });
60
60
  if (!response.ok) {
61
- const errorBody = (await response.json());
62
- throw new Error(errorBody.error?.message ??
63
- `OpenAI request failed with HTTP ${response.status}.`);
61
+ throw await createProviderHttpError(response, "OpenAI");
64
62
  }
65
63
  const responseBody = response.headers
66
64
  .get("content-type")
@@ -264,22 +262,17 @@ function toProviderResponse(request, response) {
264
262
  .map((block) => block.text)
265
263
  .join("");
266
264
  const stopReason = normalizeStopReason(response, toolCalls, refused);
267
- const output = request.outputType === "json" &&
268
- toolCalls.length === 0 &&
269
- stopReason !== "max_tokens"
270
- ? parseStructuredOutput(textOutput, request.outputSchema ?? {})
271
- : textOutput;
272
265
  if (textOutput) {
273
266
  request.publishOutput?.(textOutput);
274
267
  }
275
- return {
276
- output,
268
+ return resolveProviderStructuredOutput(request, {
269
+ output: textOutput,
277
270
  responseId: response.id,
278
271
  stopReason,
279
272
  content,
280
273
  toolCalls,
281
274
  usage: normalizeUsage(response.usage),
282
- };
275
+ }, textOutput);
283
276
  }
284
277
  function parseFunctionArguments(argumentsJson, name) {
285
278
  let parsed;
@@ -2,7 +2,7 @@ import { describeProviderError, isRetryableProviderConnectionError, OrchaError,
2
2
  import { sanitizeErrorMessage } from "../amarsia/analytics.js";
3
3
  import { normalizeLocalFile, normalizeUrlContent, } from "../file-content.js";
4
4
  import { messagesFromEvents, normalizePersistedToolResults, SessionEventWriter, } from "./session-events.js";
5
- import { validateStructuredValue } from "./structured-output.js";
5
+ import { StructuredOutputError, validateStructuredValue, } from "./structured-output.js";
6
6
  import { executeLocalAction } from "./actions/execute.js";
7
7
  import { createExecution, } from "./execution.js";
8
8
  import { McpClientPool, } from "./mcp/client.js";
@@ -337,7 +337,8 @@ export class RuntimeAgent {
337
337
  await this.#store.append(sessionId, pauseEvents);
338
338
  return projectSessionSnapshot([...events, ...pauseEvents]);
339
339
  }
340
- async #ownedChild(parentSessionId, childSessionId) {
340
+ async #ownedChild(parentSessionId, childSessionId, visited = new Set()) {
341
+ visited.add(this);
341
342
  for (const child of Object.values(this.#subagents)) {
342
343
  const events = await child.#readSession(childSessionId);
343
344
  const lineage = sessionLineage(events);
@@ -348,6 +349,18 @@ export class RuntimeAgent {
348
349
  return child;
349
350
  }
350
351
  }
352
+ if (parentSessionId === undefined) {
353
+ for (const child of Object.values(this.#subagents)) {
354
+ if (visited.has(child))
355
+ continue;
356
+ try {
357
+ return await child.#ownedChild(undefined, childSessionId, visited);
358
+ }
359
+ catch {
360
+ // Continue searching sibling subtrees.
361
+ }
362
+ }
363
+ }
351
364
  throw new OrchaError("session_not_found", `Child session "${childSessionId}" was not found for agent "${this.#agentKey}".`);
352
365
  }
353
366
  async update(sessionId, update) {
@@ -738,12 +751,64 @@ export class RuntimeAgent {
738
751
  output: streamedOutput,
739
752
  };
740
753
  }
754
+ if (error instanceof StructuredOutputError && error.response) {
755
+ const modelDurationMs = Math.round(performance.now() - modelStartedAt);
756
+ const usage = aggregateUsage(previousEvents, writer.run, error.response.usage);
757
+ const assistantEvent = writer.create("message.created", {
758
+ status: "completed",
759
+ provider: this.#manifest.provider,
760
+ model: this.#manifest.model,
761
+ responseId: error.response.responseId,
762
+ stopReason: error.response.stopReason,
763
+ role: "assistant",
764
+ content: error.response.content,
765
+ usage: error.response.usage,
766
+ durationMs: modelDurationMs,
767
+ });
768
+ const failedContext = summarizeRunToolFailures(previousEvents, writer.run);
769
+ const message = failedContext.summary
770
+ ? `After ${failedContext.summary}: ${error.message}`
771
+ : error.message;
772
+ const details = {
773
+ reason: error.kind,
774
+ outputType: this.#manifest.outputType,
775
+ provider: this.#manifest.provider,
776
+ model: this.#manifest.model,
777
+ ...(error.responsePreview
778
+ ? { responsePreview: error.responsePreview }
779
+ : {}),
780
+ ...(error.schemaErrors
781
+ ? { schemaErrors: error.schemaErrors }
782
+ : {}),
783
+ ...(failedContext.failures.length > 0
784
+ ? { failedActions: failedContext.failures }
785
+ : {}),
786
+ };
787
+ await this.#store.append(sessionId, [
788
+ assistantEvent,
789
+ writer.create("run.failed", {
790
+ status: "failed",
791
+ durationMs: elapsedRunDuration(previousEvents, writer.run),
792
+ usage,
793
+ error: {
794
+ code: "provider_error",
795
+ message,
796
+ retryable: true,
797
+ details,
798
+ },
799
+ }),
800
+ ]);
801
+ return failure(sessionId, "provider_error", message, {
802
+ retryable: true,
803
+ details,
804
+ });
805
+ }
741
806
  if (error instanceof OrchaError) {
742
807
  throw error;
743
808
  }
744
809
  const providerError = describeProviderError(error);
745
810
  throw new OrchaError("provider_error", providerError.message, {
746
- retryable: true,
811
+ retryable: providerError.retryable,
747
812
  cause: error,
748
813
  details: {
749
814
  provider: this.#manifest.provider,
@@ -755,7 +820,8 @@ export class RuntimeAgent {
755
820
  const modelDurationMs = Math.round(performance.now() - modelStartedAt);
756
821
  const usage = aggregateUsage(previousEvents, writer.run, response.usage);
757
822
  const assistantEvent = writer.create("message.created", {
758
- status: response.stopReason === "max_tokens"
823
+ status: response.stopReason === "max_tokens" ||
824
+ response.stopReason === "content_filter"
759
825
  ? "incomplete"
760
826
  : "completed",
761
827
  provider: this.#manifest.provider,
@@ -766,7 +832,8 @@ export class RuntimeAgent {
766
832
  content: response.content,
767
833
  ...(this.#manifest.outputType === "json" &&
768
834
  response.toolCalls.length === 0 &&
769
- response.stopReason !== "max_tokens"
835
+ response.stopReason !== "max_tokens" &&
836
+ response.stopReason !== "content_filter"
770
837
  ? { parsedOutput: response.output }
771
838
  : {}),
772
839
  usage: response.usage,
@@ -797,6 +864,37 @@ export class RuntimeAgent {
797
864
  ]);
798
865
  return failure(sessionId, "provider_error", message, { details });
799
866
  }
867
+ if (response.stopReason === "content_filter") {
868
+ const preview = typeof response.output === "string" && response.output.trim()
869
+ ? response.output.trim().slice(0, 240)
870
+ : undefined;
871
+ const message = preview
872
+ ? `The model response was blocked by the provider's content filter: ${JSON.stringify(preview)}`
873
+ : "The model response was blocked by the provider's content filter.";
874
+ const details = {
875
+ reason: "content_filter",
876
+ outputType: this.#manifest.outputType,
877
+ ...(preview ? { responsePreview: preview } : {}),
878
+ };
879
+ await this.#store.append(sessionId, [
880
+ assistantEvent,
881
+ writer.create("run.failed", {
882
+ status: "failed",
883
+ durationMs: elapsedRunDuration(previousEvents, writer.run),
884
+ usage,
885
+ error: {
886
+ code: "provider_error",
887
+ message,
888
+ retryable: false,
889
+ details,
890
+ },
891
+ }),
892
+ ]);
893
+ return failure(sessionId, "provider_error", message, {
894
+ retryable: false,
895
+ details,
896
+ });
897
+ }
800
898
  if (response.toolCalls.length > 0) {
801
899
  await this.#store.append(sessionId, [assistantEvent]);
802
900
  const eventsAfterAssistant = [...previousEvents, assistantEvent];
@@ -1093,7 +1191,7 @@ export class RuntimeAgent {
1093
1191
  events.push(requested);
1094
1192
  const startedAt = performance.now();
1095
1193
  try {
1096
- validateStructuredValue(call.arguments, action.parameters);
1194
+ validateStructuredValue(call.arguments, action.parameters, `action "${action.name}" parameters`);
1097
1195
  const rawOutput = await executeLocalAction({
1098
1196
  action,
1099
1197
  parameters: call.arguments,
@@ -1105,7 +1203,7 @@ export class RuntimeAgent {
1105
1203
  const serializedOutput = ensureJsonSerializable(rawOutput);
1106
1204
  const { output, contents } = extractActionOutputAndContents(serializedOutput, this.#projectRoot);
1107
1205
  if (action.outputSchema) {
1108
- validateStructuredValue(output, action.outputSchema);
1206
+ validateStructuredValue(output, action.outputSchema, `action "${action.name}" outputSchema`);
1109
1207
  }
1110
1208
  const completed = writer.create("action.completed", {
1111
1209
  callId: call.callId,
@@ -1187,10 +1285,11 @@ export class RuntimeAgent {
1187
1285
  events.push(requested);
1188
1286
  const startedAt = performance.now();
1189
1287
  try {
1190
- validateStructuredValue(call.arguments, tool.parameters);
1288
+ validateStructuredValue(call.arguments, tool.parameters, `MCP tool "${call.name}" parameters`);
1191
1289
  const result = await this.#mcp.callTool(call.name, call.arguments, signal);
1192
1290
  const serializedOutput = ensureJsonSerializable(result.output);
1193
1291
  if (result.isError) {
1292
+ const errorDetail = extractMcpErrorDetail(serializedOutput);
1194
1293
  const failed = writer.create("action.failed", {
1195
1294
  callId: call.callId,
1196
1295
  name: call.name,
@@ -1201,7 +1300,9 @@ export class RuntimeAgent {
1201
1300
  durationMs: Math.round(performance.now() - startedAt),
1202
1301
  error: {
1203
1302
  code: "mcp_tool_error",
1204
- message: `MCP tool "${call.name}" returned an error.`,
1303
+ message: errorDetail
1304
+ ? `MCP tool "${call.name}" returned an error: ${errorDetail}`
1305
+ : `MCP tool "${call.name}" returned an error.`,
1205
1306
  },
1206
1307
  });
1207
1308
  await this.#store.append(sessionId, [failed]);
@@ -1582,7 +1683,10 @@ export class RuntimeAgent {
1582
1683
  const normalized = error instanceof OrchaError
1583
1684
  ? error
1584
1685
  : new OrchaError("storage_error", error instanceof Error ? error.message : String(error), { retryable: true, cause: error });
1585
- return failure(sessionId, normalized.code, normalized.message);
1686
+ return failure(sessionId, normalized.code, normalized.message, {
1687
+ retryable: normalized.retryable,
1688
+ details: normalized.details,
1689
+ });
1586
1690
  }
1587
1691
  finally {
1588
1692
  this.#sessionControls.delete(sessionId);
@@ -3046,6 +3150,69 @@ async function withProviderConnectionRetry(operation, signal) {
3046
3150
  return operation();
3047
3151
  }
3048
3152
  }
3153
+ function summarizeRunToolFailures(events, run) {
3154
+ const failures = [];
3155
+ for (const event of events) {
3156
+ if (event.run !== run)
3157
+ continue;
3158
+ if (event.type === "action.failed") {
3159
+ const name = typeof event.data.name === "string" ? event.data.name : "action";
3160
+ const errorRecord = isRecord(event.data.error)
3161
+ ? event.data.error
3162
+ : undefined;
3163
+ const message = typeof errorRecord?.message === "string" && errorRecord.message.trim()
3164
+ ? errorRecord.message.trim()
3165
+ : "action execution failed";
3166
+ failures.push({ kind: "action", name, message });
3167
+ }
3168
+ else if (event.type === "subagent.failed") {
3169
+ const name = typeof event.data.agent === "string" ? event.data.agent : "subagent";
3170
+ const errorRecord = isRecord(event.data.error)
3171
+ ? event.data.error
3172
+ : undefined;
3173
+ const message = typeof errorRecord?.message === "string" && errorRecord.message.trim()
3174
+ ? errorRecord.message.trim()
3175
+ : "subagent execution failed";
3176
+ failures.push({ kind: "subagent", name, message });
3177
+ }
3178
+ }
3179
+ if (failures.length === 0) {
3180
+ return { failures };
3181
+ }
3182
+ const last = failures.at(-1);
3183
+ const label = `${last.kind} "${last.name}" failed (${last.message})`;
3184
+ return {
3185
+ summary: failures.length === 1
3186
+ ? label
3187
+ : `${label} (+${failures.length - 1} earlier tool failure${failures.length > 2 ? "s" : ""})`,
3188
+ failures,
3189
+ };
3190
+ }
3191
+ function extractMcpErrorDetail(output) {
3192
+ if (typeof output === "string" && output.trim()) {
3193
+ return output.trim();
3194
+ }
3195
+ if (!isRecord(output)) {
3196
+ return undefined;
3197
+ }
3198
+ if (typeof output.error === "string" && output.error.trim()) {
3199
+ return output.error.trim();
3200
+ }
3201
+ if (typeof output.message === "string" && output.message.trim()) {
3202
+ return output.message.trim();
3203
+ }
3204
+ if (Array.isArray(output.content)) {
3205
+ const texts = output.content
3206
+ .map((item) => isRecord(item) && typeof item.text === "string"
3207
+ ? item.text.trim()
3208
+ : "")
3209
+ .filter(Boolean);
3210
+ if (texts.length > 0) {
3211
+ return texts.join(" ");
3212
+ }
3213
+ }
3214
+ return undefined;
3215
+ }
3049
3216
  function failure(sessionId, code, message, options = {}) {
3050
3217
  const retryable = options.retryable ??
3051
3218
  (code === "session_busy" ||
@@ -93,22 +93,19 @@ class OrchaRuntimeCore {
93
93
  return runtimeStore;
94
94
  };
95
95
  const agents = new Map();
96
- for (const [name, manifest] of Object.entries(bundle.agents)) {
97
- const subagents = Object.fromEntries(Object.entries(manifest.subagents ?? {}).map(([subagentName, subagentManifest]) => [
98
- subagentName,
99
- new RuntimeAgent({
100
- manifest: subagentManifest,
101
- configuration: runtimeConfiguration,
102
- store: createRuntimeStore(subagentManifest),
103
- activeSessions: this.#activeSessions,
104
- sessionControls: this.#sessionControls,
105
- generateProviderResponse,
106
- delegatedOnly: true,
107
- projectRoot,
108
- randomUUID: this.#platform.randomUUID,
109
- }),
110
- ]));
111
- agents.set(name, new RuntimeAgent({
96
+ const createRuntimeAgent = (manifest, delegatedOnly, ancestry) => {
97
+ const subagents = Object.fromEntries(Object.entries(manifest.subagents ?? {}).map(([subagentName, subagentManifest]) => {
98
+ if (ancestry.has(subagentName)) {
99
+ throw new Error(`Circular subagent registration detected: ${[...ancestry, subagentName].join(" -> ")}.`);
100
+ }
101
+ const nextAncestry = new Set(ancestry);
102
+ nextAncestry.add(subagentName);
103
+ return [
104
+ subagentName,
105
+ createRuntimeAgent(subagentManifest, true, nextAncestry),
106
+ ];
107
+ }));
108
+ return new RuntimeAgent({
112
109
  manifest,
113
110
  configuration: runtimeConfiguration,
114
111
  store: createRuntimeStore(manifest),
@@ -116,9 +113,13 @@ class OrchaRuntimeCore {
116
113
  sessionControls: this.#sessionControls,
117
114
  generateProviderResponse,
118
115
  subagents,
116
+ delegatedOnly,
119
117
  projectRoot,
120
118
  randomUUID: this.#platform.randomUUID,
121
- }));
119
+ });
120
+ };
121
+ for (const [name, manifest] of Object.entries(bundle.agents)) {
122
+ agents.set(name, createRuntimeAgent(manifest, false, new Set([name])));
122
123
  }
123
124
  this.#bundle = bundle;
124
125
  this.#inferenceEnabled = inferenceEnabled;
@@ -1,2 +1,19 @@
1
+ import type { ProviderRequest, ProviderResponse } from "../providers/types.js";
2
+ export type StructuredOutputFailureKind = "missing_json" | "invalid_json" | "schema_mismatch";
3
+ export declare class StructuredOutputError extends Error {
4
+ readonly kind: StructuredOutputFailureKind;
5
+ readonly rawText: string;
6
+ readonly responsePreview?: string;
7
+ readonly schemaErrors?: string[];
8
+ response?: ProviderResponse;
9
+ constructor(message: string, options: {
10
+ kind: StructuredOutputFailureKind;
11
+ rawText: string;
12
+ responsePreview?: string;
13
+ schemaErrors?: string[];
14
+ cause?: unknown;
15
+ });
16
+ }
17
+ export declare function resolveProviderStructuredOutput(request: ProviderRequest, baseResponse: ProviderResponse, textOutput: string): ProviderResponse;
1
18
  export declare function parseStructuredOutput(text: string, schema: Record<string, unknown>): unknown;
2
- export declare function validateStructuredValue(value: unknown, schema: Record<string, unknown>): void;
19
+ export declare function validateStructuredValue(value: unknown, schema: Record<string, unknown>, label?: string): void;