orchajs 0.27.0 → 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.
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var analytics_exports = {};
21
21
  __export(analytics_exports, {
22
22
  AmarsiaTelemetryClient: () => AmarsiaTelemetryClient,
23
+ sanitizeErrorMessage: () => sanitizeErrorMessage,
23
24
  withAmarsiaTelemetry: () => withAmarsiaTelemetry
24
25
  });
25
26
  module.exports = __toCommonJS(analytics_exports);
@@ -32,20 +33,28 @@ const RELEVANT_EVENTS = /* @__PURE__ */ new Set([
32
33
  "evaluation.completed",
33
34
  "evaluation.failed"
34
35
  ]);
36
+ const PROGRESS_EVENTS = /* @__PURE__ */ new Set([
37
+ "message.created",
38
+ "action.completed",
39
+ "action.failed",
40
+ "subagent.completed",
41
+ "subagent.failed"
42
+ ]);
35
43
  const MAX_BATCH_RUNS = 100;
36
44
  const MAX_KEEPALIVE_BYTES = 48 * 1024;
37
45
  const HEARTBEAT_INTERVAL_MS = 3e4;
38
- const EVALUATION_FLUSH_TIMEOUT_MS = 5e3;
46
+ const MAX_CONCURRENT_FLUSHES = 2;
39
47
  class AmarsiaTelemetryClient {
40
48
  #key;
41
49
  #baseUrl;
42
50
  #queue = /* @__PURE__ */ new Map();
43
51
  #activeRuns = /* @__PURE__ */ new Map();
52
+ #terminalRuns = /* @__PURE__ */ new Set();
44
53
  #pendingProjections = /* @__PURE__ */ new Set();
54
+ #inFlightFlushes = /* @__PURE__ */ new Set();
45
55
  #timer;
46
56
  #heartbeatTimer;
47
57
  #attempt = 0;
48
- #flushPromise;
49
58
  constructor(options) {
50
59
  this.#key = options.key;
51
60
  this.#baseUrl = (0, import_endpoint.resolveAmarsiaEndpoint)(options.endpoint);
@@ -53,24 +62,38 @@ class AmarsiaTelemetryClient {
53
62
  enqueue(fact) {
54
63
  this.#queue.set(fact.event_id, fact);
55
64
  if (fact.status === "running") {
65
+ this.#terminalRuns.delete(fact.event_id);
56
66
  this.#activeRuns.set(fact.event_id, fact);
57
67
  this.#scheduleHeartbeat();
58
- } else {
59
- this.#activeRuns.delete(fact.event_id);
60
- if (this.#activeRuns.size === 0 && this.#heartbeatTimer) {
61
- clearTimeout(this.#heartbeatTimer);
62
- this.#heartbeatTimer = void 0;
68
+ if (this.#queue.size >= 20) {
69
+ void this.#flush();
70
+ return;
63
71
  }
64
- }
65
- if (fact.status !== "running") {
66
- this.#scheduleTerminal();
72
+ this.#schedule(250);
67
73
  return;
68
74
  }
69
- if (this.#queue.size >= 20) {
70
- void this.#flush();
75
+ this.#terminalRuns.add(fact.event_id);
76
+ this.#activeRuns.delete(fact.event_id);
77
+ if (this.#activeRuns.size === 0 && this.#heartbeatTimer) {
78
+ clearTimeout(this.#heartbeatTimer);
79
+ this.#heartbeatTimer = void 0;
80
+ }
81
+ if (this.#timer) {
82
+ clearTimeout(this.#timer);
83
+ this.#timer = void 0;
84
+ }
85
+ void this.#flush();
86
+ }
87
+ updateActiveRun(fact) {
88
+ if (fact.status !== "running" || this.#terminalRuns.has(fact.event_id)) {
71
89
  return;
72
90
  }
73
- this.#schedule(250);
91
+ if (this.#activeRuns.has(fact.event_id)) {
92
+ this.#activeRuns.set(fact.event_id, fact);
93
+ }
94
+ if (this.#queue.has(fact.event_id)) {
95
+ this.#queue.set(fact.event_id, fact);
96
+ }
74
97
  }
75
98
  #schedule(delay) {
76
99
  if (this.#timer) return;
@@ -88,19 +111,14 @@ class AmarsiaTelemetryClient {
88
111
  this.#pendingProjections.delete(projection);
89
112
  });
90
113
  }
91
- #scheduleTerminal() {
92
- if (this.#timer) clearTimeout(this.#timer);
93
- this.#timer = setTimeout(() => {
94
- this.#timer = void 0;
95
- void this.#flush();
96
- }, 0);
97
- }
98
114
  #scheduleHeartbeat() {
99
115
  if (this.#heartbeatTimer || this.#activeRuns.size === 0) return;
100
116
  this.#heartbeatTimer = setTimeout(() => {
101
117
  this.#heartbeatTimer = void 0;
102
118
  for (const fact of this.#activeRuns.values()) {
103
- this.#queue.set(fact.event_id, fact);
119
+ if (!this.#terminalRuns.has(fact.event_id)) {
120
+ this.#queue.set(fact.event_id, fact);
121
+ }
104
122
  }
105
123
  void this.#flush();
106
124
  this.#scheduleHeartbeat();
@@ -111,7 +129,7 @@ class AmarsiaTelemetryClient {
111
129
  async drain(options = {}) {
112
130
  const timeoutMs = Math.max(0, options.timeoutMs ?? 2e3);
113
131
  const deadline = Date.now() + timeoutMs;
114
- while (this.#pendingProjections.size > 0 || this.#queue.size > 0 || this.#flushPromise) {
132
+ while (this.#pendingProjections.size > 0 || this.#queue.size > 0 || this.#inFlightFlushes.size > 0) {
115
133
  const remaining = deadline - Date.now();
116
134
  if (remaining <= 0) return;
117
135
  if (this.#pendingProjections.size > 0) {
@@ -125,10 +143,19 @@ class AmarsiaTelemetryClient {
125
143
  clearTimeout(this.#timer);
126
144
  this.#timer = void 0;
127
145
  }
128
- await Promise.race([
129
- this.#flush(),
130
- new Promise((resolve) => setTimeout(resolve, remaining))
131
- ]);
146
+ if (this.#queue.size > 0) {
147
+ await Promise.race([
148
+ this.#flush(),
149
+ new Promise((resolve) => setTimeout(resolve, remaining))
150
+ ]);
151
+ continue;
152
+ }
153
+ if (this.#inFlightFlushes.size > 0) {
154
+ await Promise.race([
155
+ Promise.allSettled([...this.#inFlightFlushes]).then(() => void 0),
156
+ new Promise((resolve) => setTimeout(resolve, remaining))
157
+ ]);
158
+ }
132
159
  }
133
160
  }
134
161
  async close(options = {}) {
@@ -145,20 +172,33 @@ class AmarsiaTelemetryClient {
145
172
  this.#activeRuns.clear();
146
173
  }
147
174
  async #flush() {
148
- if (this.#flushPromise) return this.#flushPromise;
149
- if (this.#queue.size === 0) return;
150
- this.#flushPromise = this.#performFlush();
175
+ if (this.#queue.size === 0) {
176
+ if (this.#inFlightFlushes.size > 0) {
177
+ await Promise.allSettled([...this.#inFlightFlushes]);
178
+ }
179
+ return;
180
+ }
181
+ const hasTerminalFact = [...this.#queue.values()].some(
182
+ (fact) => fact.status !== "running"
183
+ );
184
+ const maxConcurrent = hasTerminalFact ? MAX_CONCURRENT_FLUSHES : 1;
185
+ if (this.#inFlightFlushes.size >= maxConcurrent) {
186
+ await Promise.allSettled([...this.#inFlightFlushes]);
187
+ return;
188
+ }
189
+ const flushPromise = this.#performFlush();
190
+ this.#inFlightFlushes.add(flushPromise);
151
191
  try {
152
- await this.#flushPromise;
192
+ await flushPromise;
153
193
  } finally {
154
- this.#flushPromise = void 0;
194
+ this.#inFlightFlushes.delete(flushPromise);
155
195
  if (this.#queue.size > 0 && !this.#timer) {
156
- const hasTerminalFact = [...this.#queue.values()].some(
196
+ const remainingHasTerminal = [...this.#queue.values()].some(
157
197
  (fact) => fact.status !== "running"
158
198
  );
159
- if (hasTerminalFact) {
199
+ if (remainingHasTerminal) {
160
200
  void this.#flush();
161
- } else {
201
+ } else if (this.#inFlightFlushes.size === 0) {
162
202
  this.#schedule(250);
163
203
  }
164
204
  }
@@ -193,6 +233,9 @@ class AmarsiaTelemetryClient {
193
233
  this.#attempt += 1;
194
234
  if (this.#attempt <= 6) {
195
235
  for (const fact of batch) {
236
+ if (fact.status === "running" && this.#terminalRuns.has(fact.event_id)) {
237
+ continue;
238
+ }
196
239
  if (!this.#queue.has(fact.event_id)) {
197
240
  this.#queue.set(fact.event_id, fact);
198
241
  }
@@ -232,19 +275,48 @@ function withAmarsiaTelemetry(options) {
232
275
  async append(sessionId, events) {
233
276
  await store.append(sessionId, events);
234
277
  const runs = relevantRuns(events);
235
- if (runs.size === 0 && !projections.has(sessionId) && !pending.has(sessionId)) {
278
+ const progressRuns = progressOnlyRuns(events, runs);
279
+ const hasSessionCreated = events.some(
280
+ (event) => event.type === "session.created"
281
+ );
282
+ if (runs.size === 0 && progressRuns.size === 0 && !hasSessionCreated && !projections.has(sessionId) && !pending.has(sessionId)) {
236
283
  return;
237
284
  }
285
+ if (!pending.has(sessionId)) {
286
+ let projection = projections.get(sessionId);
287
+ let hasNewEvents = false;
288
+ if (!projection && hasSessionCreated) {
289
+ projection = createProjection(events);
290
+ projections.set(sessionId, projection);
291
+ hasNewEvents = projection.seenSequences.size > 0;
292
+ } else if (projection) {
293
+ hasNewEvents = appendToProjection(projection, events);
294
+ }
295
+ if (projection) {
296
+ if (projection.isTest || !hasNewEvents) return;
297
+ for (const run of runs) {
298
+ const fact = projectRunFact(manifest, sessionId, run, projection);
299
+ if (fact) client.enqueue(fact);
300
+ }
301
+ for (const run of progressRuns) {
302
+ const fact = projectRunFact(manifest, sessionId, run, projection);
303
+ if (fact) client.updateActiveRun(fact);
304
+ }
305
+ return;
306
+ }
307
+ }
238
308
  const previous = pending.get(sessionId) ?? Promise.resolve();
239
309
  const processing = previous.then(async () => {
240
310
  let projection = projections.get(sessionId);
311
+ let hasNewEvents = false;
241
312
  if (!projection) {
242
313
  projection = createProjection(await store.read(sessionId));
243
314
  projections.set(sessionId, projection);
315
+ hasNewEvents = projection.seenSequences.size > 0;
244
316
  } else {
245
- appendToProjection(projection, events);
317
+ hasNewEvents = appendToProjection(projection, events);
246
318
  }
247
- if (projection.isTest) return;
319
+ if (projection.isTest || !hasNewEvents) return;
248
320
  for (const run of runs) {
249
321
  const fact = projectRunFact(
250
322
  manifest,
@@ -254,6 +326,15 @@ function withAmarsiaTelemetry(options) {
254
326
  );
255
327
  if (fact) client.enqueue(fact);
256
328
  }
329
+ for (const run of progressRuns) {
330
+ const fact = projectRunFact(
331
+ manifest,
332
+ sessionId,
333
+ run,
334
+ projection
335
+ );
336
+ if (fact) client.updateActiveRun(fact);
337
+ }
257
338
  }).catch(() => void 0);
258
339
  pending.set(sessionId, processing);
259
340
  client.trackProjection(processing);
@@ -262,18 +343,6 @@ function withAmarsiaTelemetry(options) {
262
343
  pending.delete(sessionId);
263
344
  }
264
345
  });
265
- const hasTerminalRunEvent = events.some(
266
- (event) => event.type === "run.completed" || event.type === "run.failed" || event.type === "run.paused"
267
- );
268
- const hasEvaluationResult = events.some(
269
- (event) => event.type === "evaluation.completed" || event.type === "evaluation.failed"
270
- );
271
- if (hasTerminalRunEvent || hasEvaluationResult) {
272
- await processing;
273
- }
274
- if (hasEvaluationResult) {
275
- await client.drain({ timeoutMs: EVALUATION_FLUSH_TIMEOUT_MS });
276
- }
277
346
  }
278
347
  };
279
348
  }
@@ -287,9 +356,11 @@ function createProjection(events) {
287
356
  return projection;
288
357
  }
289
358
  function appendToProjection(projection, events) {
359
+ let added = false;
290
360
  for (const event of events) {
291
361
  if (projection.seenSequences.has(event.sequence)) continue;
292
362
  projection.seenSequences.add(event.sequence);
363
+ added = true;
293
364
  if (event.type === "session.created") {
294
365
  projection.sessionCreated = event;
295
366
  const metadata = asRecord(event.data.metadata);
@@ -303,6 +374,7 @@ function appendToProjection(projection, events) {
303
374
  projection.runs.set(event.run, [event]);
304
375
  }
305
376
  }
377
+ return added;
306
378
  }
307
379
  function relevantRuns(events) {
308
380
  const runs = /* @__PURE__ */ new Set();
@@ -313,6 +385,15 @@ function relevantRuns(events) {
313
385
  }
314
386
  return runs;
315
387
  }
388
+ function progressOnlyRuns(events, relevant) {
389
+ const runs = /* @__PURE__ */ new Set();
390
+ for (const event of events) {
391
+ if (typeof event.run === "number" && !relevant.has(event.run) && PROGRESS_EVENTS.has(event.type)) {
392
+ runs.add(event.run);
393
+ }
394
+ }
395
+ return runs;
396
+ }
316
397
  function projectRunFact(manifest, sessionId, run, projection) {
317
398
  const runEvents = projection.runs.get(run);
318
399
  if (!runEvents) return void 0;
@@ -524,16 +605,50 @@ function asRecord(value) {
524
605
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
525
606
  }
526
607
  function sanitizeErrorMessage(value) {
527
- return value.replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer [redacted]").replace(
528
- /\b(authorization|api[-_ ]?key|token|secret|password)\b\s*[:=]\s*[^\s,;]+/gi,
608
+ return value.replace(
609
+ /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/-]+=*/gi,
610
+ "$1 [redacted]"
611
+ ).replace(
612
+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
613
+ "[redacted]"
614
+ ).replace(
615
+ /\b([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+:[^/\s@]+@)/gi,
616
+ "$1[redacted]@"
617
+ ).replace(
618
+ /\b(authorization|api[-_ ]?key|access[-_ ]?key|secret[-_ ]?key|client[-_ ]?secret|private[-_ ]?key|session[-_ ]?token|refresh[-_ ]?token|token|secret|password|passwd|pwd|credential)\b\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;}]+)/gi,
529
619
  "$1=[redacted]"
530
620
  ).replace(
531
- /\b(?:sk|pk|amarsia)_[A-Za-z0-9_-]{12,}\b/gi,
621
+ /\b(?:sk|pk|rk|ak|amarsia|ams_proj|ghp|gho|ghu|ghs|ghr|glpat|xox[baprs])_[A-Za-z0-9_-]{8,}\b/gi,
532
622
  "[redacted]"
623
+ ).replace(/\bAKIA[0-9A-Z]{16}\b/g, "[redacted]").replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[redacted-ssn]").replace(/(?<![\d-])\b\d{2}-\d{7}\b(?![\d-])/g, "[redacted-tin]").replace(
624
+ /\b(ssn|itin|ein|tin|tax[-_ ]?id|routing[-_ ]?number|account[-_ ]?number|acct[-_ ]?(?:no|num|#)?|iban|swift)\b(\s*(?:is|#|:|=)?\s*)[A-Z0-9-]{4,34}\b/gi,
625
+ "$1$2[redacted-id]"
626
+ ).replace(/\b(?:\d{4}[ -]?){3}\d{1,7}\b/g, "[redacted-card]").replace(
627
+ /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
628
+ "[redacted-email]"
629
+ ).replace(
630
+ /(?:\+\d{1,3}[\s.-]?)?(?:\(\d{3}\)|\b\d{3})[\s.-]\d{3}[\s.-]\d{4}\b/g,
631
+ "[redacted-phone]"
632
+ ).replace(
633
+ /(?:[$€£¥₹]|(?:\b(?:USD|EUR|GBP|CAD|AUD|JPY|INR|CHF)\s*))\s*[-+]?\d[\d,]*(?:\.\d+)?(?:\s*(?:k|m|b|bn|mm|thousand|million|billion))?\b/gi,
634
+ "[redacted-amount]"
635
+ ).replace(
636
+ /\b[-+]?\d[\d,]*(?:\.\d+)?\s*(?:USD|EUR|GBP|CAD|AUD|JPY|INR|CHF|dollars?|cents?|euros?|pounds?)\b/gi,
637
+ "[redacted-amount]"
638
+ ).replace(
639
+ /\b[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?\b/g,
640
+ "[redacted-figure]"
641
+ ).replace(
642
+ /\b(amount|total|subtotal|balance|income|revenue|salary|wages|compensation|distribution|deduction|tax|profit|loss|cost|price|fee|payment|invoice|net|gross|asset|liability|equity|credit|debit)(\s+(?:of|is|was|equals|=|:)\s*)[-+]?\d[\d,]*(?:\.\d+)?%?/gi,
643
+ "$1$2[redacted-figure]"
644
+ ).replace(
645
+ /(?:\/Users\/|\/home\/|[A-Za-z]:\\Users\\)[^\s,;'")\]}]+/g,
646
+ "[redacted-path]"
533
647
  ).slice(0, 8e3);
534
648
  }
535
649
  // Annotate the CommonJS export names for ESM import in node:
536
650
  0 && (module.exports = {
537
651
  AmarsiaTelemetryClient,
652
+ sanitizeErrorMessage,
538
653
  withAmarsiaTelemetry
539
654
  });
@@ -309,18 +309,21 @@ function toProviderResponse(request, response) {
309
309
  );
310
310
  const textOutput = response.output_text ?? content.filter((block) => block.type === "text").map((block) => block.text).join("");
311
311
  const stopReason = normalizeStopReason(response, toolCalls, refused);
312
- const output = request.outputType === "json" && toolCalls.length === 0 && stopReason !== "max_tokens" ? (0, import_structured_output.parseStructuredOutput)(textOutput, request.outputSchema ?? {}) : textOutput;
313
312
  if (textOutput) {
314
313
  request.publishOutput?.(textOutput);
315
314
  }
316
- return {
317
- output,
318
- responseId: response.id,
319
- stopReason,
320
- content,
321
- toolCalls,
322
- usage: normalizeUsage(response.usage)
323
- };
315
+ return (0, import_structured_output.resolveProviderStructuredOutput)(
316
+ request,
317
+ {
318
+ output: textOutput,
319
+ responseId: response.id,
320
+ stopReason,
321
+ content,
322
+ toolCalls,
323
+ usage: normalizeUsage(response.usage)
324
+ },
325
+ textOutput
326
+ );
324
327
  }
325
328
  function replay(item) {
326
329
  const value = {
@@ -19,7 +19,8 @@ var __copyProps = (to, from, except, desc) => {
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
20
  var metadata_exports = {};
21
21
  __export(metadata_exports, {
22
- createAmarsiaProjectMetadata: () => createAmarsiaProjectMetadata
22
+ createAmarsiaProjectMetadata: () => createAmarsiaProjectMetadata,
23
+ normalizeRepositoryUrl: () => normalizeRepositoryUrl
23
24
  });
24
25
  module.exports = __toCommonJS(metadata_exports);
25
26
  var import_crypto = require("crypto");
@@ -31,13 +32,14 @@ function createAmarsiaProjectMetadata(bundle, projectRoot) {
31
32
  packageName: packageInfo.name,
32
33
  rootPath: projectRoot
33
34
  }).slice(0, 32);
35
+ const sanitizedRootPath = sanitizeRootPath(projectRoot);
34
36
  const agents = flattenAgents(bundle.agents);
35
37
  const content = {
36
38
  project: {
37
39
  external_id: projectExternalId,
38
40
  name: packageInfo.name ?? "Orcha project",
39
41
  description: packageInfo.description,
40
- root_path: projectRoot,
42
+ root_path: sanitizedRootPath,
41
43
  package_name: packageInfo.name,
42
44
  repository_url: packageInfo.repositoryUrl,
43
45
  metadata: {
@@ -54,6 +56,14 @@ function createAmarsiaProjectMetadata(bundle, projectRoot) {
54
56
  ...content
55
57
  };
56
58
  }
59
+ function sanitizeRootPath(projectRoot) {
60
+ const trimmed = projectRoot.trim();
61
+ if (!trimmed || trimmed === "/" || trimmed === ".") {
62
+ return ".";
63
+ }
64
+ const folderName = (0, import_path.basename)((0, import_path.resolve)(trimmed));
65
+ return folderName || ".";
66
+ }
57
67
  function flattenAgents(agents) {
58
68
  const rootIds = new Set(
59
69
  Object.values(agents).map((manifest) => manifest.key)
@@ -213,7 +223,9 @@ function resolveGitConfigPath(projectRoot) {
213
223
  }
214
224
  }
215
225
  function normalizeRepositoryUrl(url) {
216
- return url?.replace(/^git\+/, "").replace(/^git@github\.com:/, "https://github.com/").replace(/\.git$/, "");
226
+ if (!url) return void 0;
227
+ const cleaned = url.trim().replace(/^git\+/, "").replace(/^git@([^:]+):/, "https://$1/").replace(/^ssh:\/\/(?:[^@]+@)?([^/]+)\//, "https://$1/").replace(/^(https?:\/\/)[^/@]+@/i, "$1").replace(/[?#].*$/, "").replace(/\.git$/, "");
228
+ return cleaned || void 0;
217
229
  }
218
230
  function hashStable(value) {
219
231
  return (0, import_crypto.createHash)("sha256").update(JSON.stringify(sortStable(value))).digest("hex");
@@ -231,5 +243,6 @@ function sortStable(value) {
231
243
  }
232
244
  // Annotate the CommonJS export names for ESM import in node:
233
245
  0 && (module.exports = {
234
- createAmarsiaProjectMetadata
246
+ createAmarsiaProjectMetadata,
247
+ normalizeRepositoryUrl
235
248
  });
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var errors_exports = {};
21
21
  __export(errors_exports, {
22
22
  OrchaError: () => OrchaError,
23
+ createProviderHttpError: () => createProviderHttpError,
23
24
  describeProviderError: () => describeProviderError,
24
25
  isRetryableProviderConnectionError: () => isRetryableProviderConnectionError
25
26
  });
@@ -36,18 +37,74 @@ class OrchaError extends Error {
36
37
  this.details = options.details;
37
38
  }
38
39
  }
40
+ const NON_RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([400, 401, 403, 404, 413, 422]);
41
+ const NON_RETRYABLE_ERROR_NAMES = /* @__PURE__ */ new Set([
42
+ "ValidationException",
43
+ "AccessDeniedException",
44
+ "ResourceNotFoundException",
45
+ "UnrecognizedClientException",
46
+ "InvalidSignatureException",
47
+ "ExpiredTokenException"
48
+ ]);
49
+ async function createProviderHttpError(response, providerLabel) {
50
+ const status = response.status;
51
+ const requestId = response.headers.get("request-id") ?? response.headers.get("x-request-id") ?? response.headers.get("x-amzn-requestid") ?? void 0;
52
+ let rawText = "";
53
+ try {
54
+ rawText = (await response.text()).trim();
55
+ } catch {
56
+ rawText = "";
57
+ }
58
+ let parsedMessage;
59
+ let errorCode;
60
+ if (rawText) {
61
+ try {
62
+ const parsed = JSON.parse(rawText);
63
+ const nestedError = typeof parsed.error === "object" && parsed.error !== null ? parsed.error : void 0;
64
+ if (typeof nestedError?.message === "string" && nestedError.message.trim()) {
65
+ parsedMessage = nestedError.message.trim();
66
+ } else if (typeof parsed.message === "string" && parsed.message.trim()) {
67
+ parsedMessage = parsed.message.trim();
68
+ } else if (typeof parsed.detail === "string" && parsed.detail.trim()) {
69
+ parsedMessage = parsed.detail.trim();
70
+ }
71
+ errorCode = stringOrNumberField(nestedError, "code") ?? stringOrNumberField(nestedError, "type") ?? stringOrNumberField(parsed, "code");
72
+ } catch {
73
+ const compact = rawText.replace(/\s+/g, " ").trim();
74
+ if (compact) {
75
+ parsedMessage = compact.length > 300 ? `${compact.slice(0, 300)}...` : compact;
76
+ }
77
+ }
78
+ }
79
+ const message = parsedMessage ?? `${providerLabel} request failed with HTTP ${status}.`;
80
+ const error = new Error(message);
81
+ error.statusCode = status;
82
+ if (requestId) {
83
+ error.requestId = requestId;
84
+ }
85
+ if (errorCode !== void 0) {
86
+ error.code = errorCode;
87
+ }
88
+ return error;
89
+ }
39
90
  function describeProviderError(error) {
40
91
  const rootMessage = errorMessage(error);
92
+ const statusCode = extractStatusCode(error);
93
+ const requestId = extractRequestId(error);
94
+ const errorName = extractErrorName(error);
95
+ const errorCode = stringOrNumberField(error, "code") ?? stringOrNumberField(error, "type");
96
+ const retryable = isProviderErrorRetryable(statusCode, errorName);
41
97
  const cause = deepestUsefulCause(error);
42
- if (!cause) {
43
- return { message: rootMessage };
44
- }
45
- const causeMessage = errorMessage(cause);
46
- const causeCode = stringOrNumberField(cause, "code");
47
- const syscall = stringField(cause, "syscall");
48
- const hostname = stringField(cause, "hostname");
49
- const explanation = causeMessage !== rootMessage ? causeMessage : causeCode ? String(causeCode) : void 0;
98
+ const causeMessage = cause ? errorMessage(cause) : void 0;
99
+ const causeCode = cause ? stringOrNumberField(cause, "code") : void 0;
100
+ const syscall = cause ? stringField(cause, "syscall") : void 0;
101
+ const hostname = cause ? stringField(cause, "hostname") : void 0;
102
+ const explanation = causeMessage && causeMessage !== rootMessage ? causeMessage : causeCode !== void 0 ? String(causeCode) : void 0;
50
103
  const details = {
104
+ ...statusCode !== void 0 ? { statusCode } : {},
105
+ ...requestId ? { requestId } : {},
106
+ ...errorName ? { errorName } : {},
107
+ ...errorCode !== void 0 ? { errorCode } : {},
51
108
  ...causeCode !== void 0 ? { causeCode } : {},
52
109
  ...syscall ? { syscall } : {},
53
110
  ...hostname ? { hostname } : {},
@@ -55,6 +112,7 @@ function describeProviderError(error) {
55
112
  };
56
113
  return {
57
114
  message: explanation ? `${rootMessage}: ${explanation}` : rootMessage,
115
+ retryable,
58
116
  ...Object.keys(details).length > 0 ? { details } : {}
59
117
  };
60
118
  }
@@ -83,6 +141,45 @@ function isRetryableProviderConnectionError(error) {
83
141
  }
84
142
  return false;
85
143
  }
144
+ function isProviderErrorRetryable(statusCode, errorName) {
145
+ if (errorName && NON_RETRYABLE_ERROR_NAMES.has(errorName)) {
146
+ return false;
147
+ }
148
+ if (statusCode !== void 0 && NON_RETRYABLE_STATUS_CODES.has(statusCode)) {
149
+ return false;
150
+ }
151
+ return true;
152
+ }
153
+ function extractStatusCode(error) {
154
+ if (typeof error !== "object" || error === null) return void 0;
155
+ const record = error;
156
+ if (typeof record.statusCode === "number") return record.statusCode;
157
+ if (typeof record.status === "number") return record.status;
158
+ const metadata = typeof record.$metadata === "object" && record.$metadata !== null ? record.$metadata : void 0;
159
+ if (typeof metadata?.httpStatusCode === "number") {
160
+ return metadata.httpStatusCode;
161
+ }
162
+ return void 0;
163
+ }
164
+ function extractRequestId(error) {
165
+ if (typeof error !== "object" || error === null) return void 0;
166
+ const record = error;
167
+ if (typeof record.requestId === "string" && record.requestId.trim()) {
168
+ return record.requestId.trim();
169
+ }
170
+ const metadata = typeof record.$metadata === "object" && record.$metadata !== null ? record.$metadata : void 0;
171
+ if (typeof metadata?.requestId === "string" && metadata.requestId.trim()) {
172
+ return metadata.requestId.trim();
173
+ }
174
+ return void 0;
175
+ }
176
+ function extractErrorName(error) {
177
+ if (!(error instanceof Error)) return void 0;
178
+ if (error.name && error.name !== "Error" && error.name !== "OrchaError") {
179
+ return error.name;
180
+ }
181
+ return void 0;
182
+ }
86
183
  function deepestUsefulCause(error) {
87
184
  let current = error;
88
185
  let useful;
@@ -125,6 +222,7 @@ function stringOrNumberField(value, key) {
125
222
  // Annotate the CommonJS export names for ESM import in node:
126
223
  0 && (module.exports = {
127
224
  OrchaError,
225
+ createProviderHttpError,
128
226
  describeProviderError,
129
227
  isRetryableProviderConnectionError
130
228
  });
@@ -24,6 +24,7 @@ __export(file_content_exports, {
24
24
  readLocalFileContent: () => readLocalFileContent
25
25
  });
26
26
  module.exports = __toCommonJS(file_content_exports);
27
+ var import_errors = require("./errors.js");
27
28
  const MIME_TYPES = {
28
29
  ".csv": "text/csv",
29
30
  ".doc": "application/msword",
@@ -72,7 +73,21 @@ function normalizeUrlContent(url, mimeType) {
72
73
  async function readLocalFileContent(content) {
73
74
  const fsModule = "fs/promises";
74
75
  const { readFile } = await import(fsModule);
75
- const bytes = await readFile(content.filePath);
76
+ let bytes;
77
+ try {
78
+ bytes = await readFile(content.filePath);
79
+ } catch (error) {
80
+ const reason = error instanceof Error ? error.message : String(error);
81
+ throw new import_errors.OrchaError(
82
+ "invalid_input",
83
+ `Failed to read local file "${content.filePath}": ${reason}`,
84
+ {
85
+ retryable: false,
86
+ cause: error,
87
+ details: { filePath: content.filePath }
88
+ }
89
+ );
90
+ }
76
91
  const base64 = bytes.toString("base64");
77
92
  return {
78
93
  bytes,