ax 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,12 +20,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
+ AgentFilesApiError: () => AgentFilesApiError,
23
24
  AuditApiError: () => AuditApiError,
24
25
  BUILT_AGAINST: () => BUILT_AGAINST,
25
26
  DeepJourneyApiError: () => DeepJourneyApiError,
26
27
  SkillApiError: () => SkillApiError,
27
28
  audit: () => performAudit,
28
29
  deepJourney: () => performDeepJourney,
30
+ fetchAgentFiles: () => fetchAgentFiles,
29
31
  fetchJourneyAgents: () => fetchJourneyAgents,
30
32
  fetchJourneyIntents: () => fetchJourneyIntents,
31
33
  fetchSkill: () => fetchSkill,
@@ -34,30 +36,6 @@ __export(src_exports, {
34
36
  });
35
37
  module.exports = __toCommonJS(src_exports);
36
38
 
37
- // src/contract/version.ts
38
- var BUILT_AGAINST = "1.25.0";
39
-
40
- // src/contract/index.ts
41
- function minor(version) {
42
- const [major = 0, min = 0] = version.split(".").map((n) => Number.parseInt(n, 10));
43
- return [major, min];
44
- }
45
- function isNewerContract(payloadVersion) {
46
- if (!payloadVersion || !/^\d+\.\d+\.\d+$/.test(payloadVersion)) return false;
47
- const [serverMajor, serverMinor] = minor(payloadVersion);
48
- const [builtMajor, builtMinor] = minor(BUILT_AGAINST);
49
- return serverMajor > builtMajor || serverMajor === builtMajor && serverMinor > builtMinor;
50
- }
51
- var warned = false;
52
- function warnOnNewerContract(payloadVersion) {
53
- if (warned || !isNewerContract(payloadVersion)) return;
54
- warned = true;
55
- process.stderr.write(
56
- `ora reports contract ${payloadVersion}; this CLI was built against ${BUILT_AGAINST}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
57
- `
58
- );
59
- }
60
-
61
39
  // src/api/shared.ts
62
40
  function watchdog(ms) {
63
41
  const controller = new AbortController();
@@ -97,8 +75,96 @@ async function errorBodyText(res) {
97
75
  }
98
76
  var pause = (ms) => new Promise((r) => setTimeout(r, ms));
99
77
 
100
- // src/api/audit.ts
78
+ // src/api/agent-files.ts
101
79
  var PUBLIC_BASE = "https://ora.ai";
80
+ var TIMEOUT_MS = 3e4;
81
+ var AgentFilesApiError = class extends Error {
82
+ status;
83
+ payload;
84
+ constructor(message, options = {}) {
85
+ super(message);
86
+ this.name = "AgentFilesApiError";
87
+ this.status = options.status ?? null;
88
+ this.payload = options.payload;
89
+ }
90
+ };
91
+ var SAFE_PATH = /^\/\.well-known\/[a-z0-9][a-z0-9._-]*\.json$/;
92
+ function isSafeAgentFilePath(path) {
93
+ return SAFE_PATH.test(path) && !path.includes("..");
94
+ }
95
+ function trimTrailingSlashes(value) {
96
+ let end = value.length;
97
+ while (end > 0 && value[end - 1] === "/") end--;
98
+ return value.slice(0, end);
99
+ }
100
+ function normalizeDomainInput(input) {
101
+ return trimTrailingSlashes(input.trim().replace(/^https?:\/\//i, ""));
102
+ }
103
+ async function fetchAgentFiles(domain, options = {}) {
104
+ const base = trimTrailingSlashes(options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE);
105
+ const url = `${base}/api/agent-files/${encodeURIComponent(normalizeDomainInput(domain))}`;
106
+ let res;
107
+ try {
108
+ res = await fetch(url, {
109
+ headers: { accept: "application/json" },
110
+ signal: AbortSignal.timeout(TIMEOUT_MS)
111
+ });
112
+ } catch (cause) {
113
+ throw new AgentFilesApiError(
114
+ `could not reach ora at ${base}: ${cause instanceof Error ? cause.message : String(cause)}`
115
+ );
116
+ }
117
+ if (!res.ok) {
118
+ const { message, payload } = await errorBody(res);
119
+ throw new AgentFilesApiError(message, { status: res.status, payload });
120
+ }
121
+ const body = await res.json();
122
+ if (!Array.isArray(body?.files)) {
123
+ throw new AgentFilesApiError("ora answered without a files list", {
124
+ status: res.status,
125
+ payload: body
126
+ });
127
+ }
128
+ for (const file of body.files) {
129
+ if (!isSafeAgentFilePath(file.path)) {
130
+ throw new AgentFilesApiError(
131
+ `ora named a file path ax will not write: ${JSON.stringify(file.path)}`,
132
+ {
133
+ status: res.status,
134
+ payload: body
135
+ }
136
+ );
137
+ }
138
+ }
139
+ return body;
140
+ }
141
+
142
+ // src/contract/version.ts
143
+ var BUILT_AGAINST = "1.30.0";
144
+
145
+ // src/contract/index.ts
146
+ function minor(version) {
147
+ const [major = 0, min = 0] = version.split(".").map((n) => Number.parseInt(n, 10));
148
+ return [major, min];
149
+ }
150
+ function isNewerContract(payloadVersion) {
151
+ if (!payloadVersion || !/^\d+\.\d+\.\d+$/.test(payloadVersion)) return false;
152
+ const [serverMajor, serverMinor] = minor(payloadVersion);
153
+ const [builtMajor, builtMinor] = minor(BUILT_AGAINST);
154
+ return serverMajor > builtMajor || serverMajor === builtMajor && serverMinor > builtMinor;
155
+ }
156
+ var warned = false;
157
+ function warnOnNewerContract(payloadVersion) {
158
+ if (warned || !isNewerContract(payloadVersion)) return;
159
+ warned = true;
160
+ process.stderr.write(
161
+ `ora reports contract ${payloadVersion}; this CLI was built against ${BUILT_AGAINST}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
162
+ `
163
+ );
164
+ }
165
+
166
+ // src/api/audit.ts
167
+ var PUBLIC_BASE2 = "https://ora.ai";
102
168
  var STREAM_IDLE_MS = 6e4;
103
169
  var POLL_EVERY_MS = 2e3;
104
170
  var POLL_LIMIT = 45;
@@ -117,7 +183,7 @@ function authHeaders(apiKey) {
117
183
  return apiKey ? { authorization: `Bearer ${apiKey}` } : {};
118
184
  }
119
185
  async function performAudit(target, options = {}) {
120
- const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE).replace(/\/+$/, "");
186
+ const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
121
187
  options = { ...options, apiKey: options.apiKey || process.env.ORA_SCAN_API_KEY || void 0 };
122
188
  options.progress?.(`Auditing ${target} with ora`);
123
189
  const streamed = await consumeScanStream(base, target, options);
@@ -297,14 +363,27 @@ function decodeEventBlock(block) {
297
363
  }
298
364
 
299
365
  // src/api/deep-journey.ts
300
- var PUBLIC_BASE2 = "https://ora.ai";
366
+ var PUBLIC_BASE3 = "https://ora.ai";
301
367
  var STREAM_IDLE_MS2 = 12e4;
302
368
  var POLL_EVERY_MS2 = 5e3;
303
369
  var POLL_LIMIT2 = 180;
370
+ var FOLLOW_BUDGET_MS = 15 * 6e4;
371
+ var MAX_RETRY_AFTER_MS = 6e4;
372
+ var STREAM_REOPENS = 5;
373
+ var STREAM_REOPEN_PAUSE_MS = 2e3;
304
374
  var DeepJourneyApiError = class extends Error {
305
375
  };
376
+ var JourneyStreamHttpError = class extends DeepJourneyApiError {
377
+ constructor(message, status, retryAfterMs) {
378
+ super(message);
379
+ this.status = status;
380
+ this.retryAfterMs = retryAfterMs;
381
+ }
382
+ status;
383
+ retryAfterMs;
384
+ };
306
385
  function apiBase(baseUrl) {
307
- return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
386
+ return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE3).replace(/\/+$/, "");
308
387
  }
309
388
  async function getJson(url) {
310
389
  let res;
@@ -372,7 +451,7 @@ async function triggerRun(base, target, options) {
372
451
  }
373
452
  if (res.status === 429) {
374
453
  const wait = res.headers.get("retry-after");
375
- const caps = options.apiKey ? "keyed allowance: 1000 runs per 24h per key" : "burst: 20/min/IP; daily: 200 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";
454
+ const caps = options.apiKey ? "keyed allowance: 1000 runs per 24h per key" : "burst: 20/min/IP; daily: 20 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";
376
455
  throw new DeepJourneyApiError(
377
456
  `ora journey caller limit exceeded${wait ? ` \u2014 retry after ${formatWait(Number(wait) * 1e3)}` : ""} (${caps})`
378
457
  );
@@ -418,7 +497,12 @@ async function followJourneyStream(base, streamPath, options) {
418
497
  let res;
419
498
  try {
420
499
  res = await fetch(target, {
421
- headers: { accept: "text/event-stream" },
500
+ headers: {
501
+ accept: "text/event-stream",
502
+ // A recognized key lifts the stream's per-IP limit on a run that
503
+ // already exists, which reopening after a drop relies on.
504
+ ...options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {}
505
+ },
422
506
  signal: dog.signal
423
507
  });
424
508
  } catch (cause) {
@@ -429,7 +513,12 @@ async function followJourneyStream(base, streamPath, options) {
429
513
  }
430
514
  if (!res.ok || !res.body) {
431
515
  dog.disarm();
432
- throw new DeepJourneyApiError(`ora journey stream failed: ${await errorBodyText(res)}`);
516
+ const retryAfterS = Number(res.headers.get("retry-after"));
517
+ throw new JourneyStreamHttpError(
518
+ `ora journey stream failed (${res.status}): ${await errorBodyText(res)}`,
519
+ res.status,
520
+ Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0
521
+ );
433
522
  }
434
523
  const utf8 = new TextDecoder();
435
524
  const collected = {};
@@ -483,14 +572,38 @@ async function followJourneyStream(base, streamPath, options) {
483
572
  }
484
573
  return collected;
485
574
  }
575
+ async function streamToEnd(base, streamPath, options, deadline) {
576
+ const pauseMs = options.reopenPauseMs ?? STREAM_REOPEN_PAUSE_MS;
577
+ let lastFailure;
578
+ let waitMs = 0;
579
+ for (let attempt = 0; attempt <= STREAM_REOPENS && Date.now() < deadline; attempt++) {
580
+ if (attempt > 0) {
581
+ options.progress?.("stream dropped \u2014 reopening");
582
+ await pause(waitMs);
583
+ }
584
+ waitMs = pauseMs;
585
+ try {
586
+ const streamed = await followJourneyStream(base, streamPath, options);
587
+ if (streamed.result || streamed.errorMessage) return streamed.errorMessage;
588
+ lastFailure = new DeepJourneyApiError("ora journey stream closed before the run ended");
589
+ } catch (cause) {
590
+ lastFailure = cause;
591
+ if (cause instanceof JourneyStreamHttpError) {
592
+ if (cause.status !== 429) throw cause;
593
+ waitMs = Math.min(cause.retryAfterMs ?? pauseMs, MAX_RETRY_AFTER_MS);
594
+ }
595
+ }
596
+ }
597
+ throw lastFailure ?? new DeepJourneyApiError("ora journey stream was never opened");
598
+ }
486
599
  function fetchRunDetail(base, runId) {
487
600
  return getJson(`${base}/api/journey/runs/${encodeURIComponent(runId)}`);
488
601
  }
489
- async function awaitByPolling(base, runId, options) {
602
+ async function awaitByPolling(base, runId, options, deadline) {
490
603
  const every = options.pollEveryMs ?? POLL_EVERY_MS2;
491
604
  const limit = options.pollLimit ?? POLL_LIMIT2;
492
605
  let latest = await fetchRunDetail(base, runId);
493
- for (let round = 0; round < limit && latest.status === "running"; round++) {
606
+ for (let round = 0; round < limit && latest.status === "running" && Date.now() < deadline; round++) {
494
607
  options.progress?.("agent working\u2026 (polling)");
495
608
  await pause(every);
496
609
  try {
@@ -512,16 +625,18 @@ async function performDeepJourney(target, options) {
512
625
  options.progress?.("target at its 24h cap \u2014 fetching the most recent stored run");
513
626
  }
514
627
  let engineError;
515
- if (!options.noStream && record.status === "running") {
628
+ let streamFailure;
629
+ if (record.status === "running") {
630
+ const deadline = Date.now() + (options.followBudgetMs ?? FOLLOW_BUDGET_MS);
631
+ const streamOptions = options.noStream ? { ...options, onTrajectory: void 0 } : options;
516
632
  try {
517
- const streamed = await followJourneyStream(base, record.stream_url, options);
518
- engineError = streamed.errorMessage;
519
- } catch {
520
- options.progress?.("stream went quiet \u2014 switching to polling");
521
- await awaitByPolling(base, record.id, options);
633
+ engineError = await streamToEnd(base, record.stream_url, streamOptions, deadline);
634
+ } catch (cause) {
635
+ if (cause instanceof JourneyStreamHttpError && cause.status !== 429) throw cause;
636
+ streamFailure = cause instanceof Error ? cause.message : String(cause);
637
+ options.progress?.(`stream unavailable (${streamFailure}) \u2014 polling`);
638
+ await awaitByPolling(base, record.id, options, deadline);
522
639
  }
523
- } else if (options.noStream && record.status === "running") {
524
- await awaitByPolling(base, record.id, options);
525
640
  }
526
641
  const detail = await awaitDetailSettled(base, record.id, options);
527
642
  if (detail.status === "running") {
@@ -529,7 +644,7 @@ async function performDeepJourney(target, options) {
529
644
  throw new DeepJourneyApiError(`ora journey run failed: ${engineError}`);
530
645
  }
531
646
  throw new DeepJourneyApiError(
532
- `run ${record.id} is still executing \u2014 the ${options.noStream ? "poll budget ran out" : "stream ended"} before a terminal result. Check ${base}/api/journey/runs/${record.id} shortly`
647
+ `run ${record.id} is still executing \u2014 ${streamFailure ? `the stream could not be followed (${streamFailure}) and polling ran out of time` : "the stream ended"} before a terminal result. Check ${base}/api/journey/runs/${record.id} shortly`
533
648
  );
534
649
  }
535
650
  warnOnNewerContract(detail.contractVersion);
@@ -554,11 +669,11 @@ async function awaitDetailSettled(base, runId, options) {
554
669
 
555
670
  // src/api/skills.ts
556
671
  var import_node_crypto = require("crypto");
557
- var PUBLIC_BASE3 = "https://ora.ai";
672
+ var PUBLIC_BASE4 = "https://ora.ai";
558
673
  var SkillApiError = class extends Error {
559
674
  };
560
675
  function resolveBase(baseUrl) {
561
- return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE3).replace(/\/+$/, "");
676
+ return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE4).replace(/\/+$/, "");
562
677
  }
563
678
  async function fetchSkillIndex(baseUrl) {
564
679
  const base = resolveBase(baseUrl);
@@ -609,12 +724,14 @@ async function fetchSkill(name, baseUrl) {
609
724
  }
610
725
  // Annotate the CommonJS export names for ESM import in node:
611
726
  0 && (module.exports = {
727
+ AgentFilesApiError,
612
728
  AuditApiError,
613
729
  BUILT_AGAINST,
614
730
  DeepJourneyApiError,
615
731
  SkillApiError,
616
732
  audit,
617
733
  deepJourney,
734
+ fetchAgentFiles,
618
735
  fetchJourneyAgents,
619
736
  fetchJourneyIntents,
620
737
  fetchSkill,
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { type AgentFile, AgentFilesApiError, type AgentFilesBundle, type AgentFilesOptions, fetchAgentFiles, } from "./api/agent-files";
1
2
  export { AuditApiError, type AuditOptions, type AuditOutcome, type AuditResult, performAudit as audit, } from "./api/audit";
2
3
  export { DeepJourneyApiError, type DeepJourneyOptions, type DeepJourneyOutcome, fetchJourneyAgents, fetchJourneyIntents, type JourneyAgentOption, type JourneyIntentOption, performDeepJourney as deepJourney, type RunAllowance, } from "./api/deep-journey";
3
4
  export { type FetchedSkill, fetchSkill, fetchSkillIndex, SkillApiError, type SkillEntry, } from "./api/skills";
package/dist/index.js CHANGED
@@ -1,27 +1,3 @@
1
- // src/contract/version.ts
2
- var BUILT_AGAINST = "1.25.0";
3
-
4
- // src/contract/index.ts
5
- function minor(version) {
6
- const [major = 0, min = 0] = version.split(".").map((n) => Number.parseInt(n, 10));
7
- return [major, min];
8
- }
9
- function isNewerContract(payloadVersion) {
10
- if (!payloadVersion || !/^\d+\.\d+\.\d+$/.test(payloadVersion)) return false;
11
- const [serverMajor, serverMinor] = minor(payloadVersion);
12
- const [builtMajor, builtMinor] = minor(BUILT_AGAINST);
13
- return serverMajor > builtMajor || serverMajor === builtMajor && serverMinor > builtMinor;
14
- }
15
- var warned = false;
16
- function warnOnNewerContract(payloadVersion) {
17
- if (warned || !isNewerContract(payloadVersion)) return;
18
- warned = true;
19
- process.stderr.write(
20
- `ora reports contract ${payloadVersion}; this CLI was built against ${BUILT_AGAINST}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
21
- `
22
- );
23
- }
24
-
25
1
  // src/api/shared.ts
26
2
  function watchdog(ms) {
27
3
  const controller = new AbortController();
@@ -61,8 +37,96 @@ async function errorBodyText(res) {
61
37
  }
62
38
  var pause = (ms) => new Promise((r) => setTimeout(r, ms));
63
39
 
64
- // src/api/audit.ts
40
+ // src/api/agent-files.ts
65
41
  var PUBLIC_BASE = "https://ora.ai";
42
+ var TIMEOUT_MS = 3e4;
43
+ var AgentFilesApiError = class extends Error {
44
+ status;
45
+ payload;
46
+ constructor(message, options = {}) {
47
+ super(message);
48
+ this.name = "AgentFilesApiError";
49
+ this.status = options.status ?? null;
50
+ this.payload = options.payload;
51
+ }
52
+ };
53
+ var SAFE_PATH = /^\/\.well-known\/[a-z0-9][a-z0-9._-]*\.json$/;
54
+ function isSafeAgentFilePath(path) {
55
+ return SAFE_PATH.test(path) && !path.includes("..");
56
+ }
57
+ function trimTrailingSlashes(value) {
58
+ let end = value.length;
59
+ while (end > 0 && value[end - 1] === "/") end--;
60
+ return value.slice(0, end);
61
+ }
62
+ function normalizeDomainInput(input) {
63
+ return trimTrailingSlashes(input.trim().replace(/^https?:\/\//i, ""));
64
+ }
65
+ async function fetchAgentFiles(domain, options = {}) {
66
+ const base = trimTrailingSlashes(options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE);
67
+ const url = `${base}/api/agent-files/${encodeURIComponent(normalizeDomainInput(domain))}`;
68
+ let res;
69
+ try {
70
+ res = await fetch(url, {
71
+ headers: { accept: "application/json" },
72
+ signal: AbortSignal.timeout(TIMEOUT_MS)
73
+ });
74
+ } catch (cause) {
75
+ throw new AgentFilesApiError(
76
+ `could not reach ora at ${base}: ${cause instanceof Error ? cause.message : String(cause)}`
77
+ );
78
+ }
79
+ if (!res.ok) {
80
+ const { message, payload } = await errorBody(res);
81
+ throw new AgentFilesApiError(message, { status: res.status, payload });
82
+ }
83
+ const body = await res.json();
84
+ if (!Array.isArray(body?.files)) {
85
+ throw new AgentFilesApiError("ora answered without a files list", {
86
+ status: res.status,
87
+ payload: body
88
+ });
89
+ }
90
+ for (const file of body.files) {
91
+ if (!isSafeAgentFilePath(file.path)) {
92
+ throw new AgentFilesApiError(
93
+ `ora named a file path ax will not write: ${JSON.stringify(file.path)}`,
94
+ {
95
+ status: res.status,
96
+ payload: body
97
+ }
98
+ );
99
+ }
100
+ }
101
+ return body;
102
+ }
103
+
104
+ // src/contract/version.ts
105
+ var BUILT_AGAINST = "1.30.0";
106
+
107
+ // src/contract/index.ts
108
+ function minor(version) {
109
+ const [major = 0, min = 0] = version.split(".").map((n) => Number.parseInt(n, 10));
110
+ return [major, min];
111
+ }
112
+ function isNewerContract(payloadVersion) {
113
+ if (!payloadVersion || !/^\d+\.\d+\.\d+$/.test(payloadVersion)) return false;
114
+ const [serverMajor, serverMinor] = minor(payloadVersion);
115
+ const [builtMajor, builtMinor] = minor(BUILT_AGAINST);
116
+ return serverMajor > builtMajor || serverMajor === builtMajor && serverMinor > builtMinor;
117
+ }
118
+ var warned = false;
119
+ function warnOnNewerContract(payloadVersion) {
120
+ if (warned || !isNewerContract(payloadVersion)) return;
121
+ warned = true;
122
+ process.stderr.write(
123
+ `ora reports contract ${payloadVersion}; this CLI was built against ${BUILT_AGAINST}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
124
+ `
125
+ );
126
+ }
127
+
128
+ // src/api/audit.ts
129
+ var PUBLIC_BASE2 = "https://ora.ai";
66
130
  var STREAM_IDLE_MS = 6e4;
67
131
  var POLL_EVERY_MS = 2e3;
68
132
  var POLL_LIMIT = 45;
@@ -81,7 +145,7 @@ function authHeaders(apiKey) {
81
145
  return apiKey ? { authorization: `Bearer ${apiKey}` } : {};
82
146
  }
83
147
  async function performAudit(target, options = {}) {
84
- const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE).replace(/\/+$/, "");
148
+ const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
85
149
  options = { ...options, apiKey: options.apiKey || process.env.ORA_SCAN_API_KEY || void 0 };
86
150
  options.progress?.(`Auditing ${target} with ora`);
87
151
  const streamed = await consumeScanStream(base, target, options);
@@ -261,14 +325,27 @@ function decodeEventBlock(block) {
261
325
  }
262
326
 
263
327
  // src/api/deep-journey.ts
264
- var PUBLIC_BASE2 = "https://ora.ai";
328
+ var PUBLIC_BASE3 = "https://ora.ai";
265
329
  var STREAM_IDLE_MS2 = 12e4;
266
330
  var POLL_EVERY_MS2 = 5e3;
267
331
  var POLL_LIMIT2 = 180;
332
+ var FOLLOW_BUDGET_MS = 15 * 6e4;
333
+ var MAX_RETRY_AFTER_MS = 6e4;
334
+ var STREAM_REOPENS = 5;
335
+ var STREAM_REOPEN_PAUSE_MS = 2e3;
268
336
  var DeepJourneyApiError = class extends Error {
269
337
  };
338
+ var JourneyStreamHttpError = class extends DeepJourneyApiError {
339
+ constructor(message, status, retryAfterMs) {
340
+ super(message);
341
+ this.status = status;
342
+ this.retryAfterMs = retryAfterMs;
343
+ }
344
+ status;
345
+ retryAfterMs;
346
+ };
270
347
  function apiBase(baseUrl) {
271
- return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
348
+ return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE3).replace(/\/+$/, "");
272
349
  }
273
350
  async function getJson(url) {
274
351
  let res;
@@ -336,7 +413,7 @@ async function triggerRun(base, target, options) {
336
413
  }
337
414
  if (res.status === 429) {
338
415
  const wait = res.headers.get("retry-after");
339
- const caps = options.apiKey ? "keyed allowance: 1000 runs per 24h per key" : "burst: 20/min/IP; daily: 200 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";
416
+ const caps = options.apiKey ? "keyed allowance: 1000 runs per 24h per key" : "burst: 20/min/IP; daily: 20 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";
340
417
  throw new DeepJourneyApiError(
341
418
  `ora journey caller limit exceeded${wait ? ` \u2014 retry after ${formatWait(Number(wait) * 1e3)}` : ""} (${caps})`
342
419
  );
@@ -382,7 +459,12 @@ async function followJourneyStream(base, streamPath, options) {
382
459
  let res;
383
460
  try {
384
461
  res = await fetch(target, {
385
- headers: { accept: "text/event-stream" },
462
+ headers: {
463
+ accept: "text/event-stream",
464
+ // A recognized key lifts the stream's per-IP limit on a run that
465
+ // already exists, which reopening after a drop relies on.
466
+ ...options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {}
467
+ },
386
468
  signal: dog.signal
387
469
  });
388
470
  } catch (cause) {
@@ -393,7 +475,12 @@ async function followJourneyStream(base, streamPath, options) {
393
475
  }
394
476
  if (!res.ok || !res.body) {
395
477
  dog.disarm();
396
- throw new DeepJourneyApiError(`ora journey stream failed: ${await errorBodyText(res)}`);
478
+ const retryAfterS = Number(res.headers.get("retry-after"));
479
+ throw new JourneyStreamHttpError(
480
+ `ora journey stream failed (${res.status}): ${await errorBodyText(res)}`,
481
+ res.status,
482
+ Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0
483
+ );
397
484
  }
398
485
  const utf8 = new TextDecoder();
399
486
  const collected = {};
@@ -447,14 +534,38 @@ async function followJourneyStream(base, streamPath, options) {
447
534
  }
448
535
  return collected;
449
536
  }
537
+ async function streamToEnd(base, streamPath, options, deadline) {
538
+ const pauseMs = options.reopenPauseMs ?? STREAM_REOPEN_PAUSE_MS;
539
+ let lastFailure;
540
+ let waitMs = 0;
541
+ for (let attempt = 0; attempt <= STREAM_REOPENS && Date.now() < deadline; attempt++) {
542
+ if (attempt > 0) {
543
+ options.progress?.("stream dropped \u2014 reopening");
544
+ await pause(waitMs);
545
+ }
546
+ waitMs = pauseMs;
547
+ try {
548
+ const streamed = await followJourneyStream(base, streamPath, options);
549
+ if (streamed.result || streamed.errorMessage) return streamed.errorMessage;
550
+ lastFailure = new DeepJourneyApiError("ora journey stream closed before the run ended");
551
+ } catch (cause) {
552
+ lastFailure = cause;
553
+ if (cause instanceof JourneyStreamHttpError) {
554
+ if (cause.status !== 429) throw cause;
555
+ waitMs = Math.min(cause.retryAfterMs ?? pauseMs, MAX_RETRY_AFTER_MS);
556
+ }
557
+ }
558
+ }
559
+ throw lastFailure ?? new DeepJourneyApiError("ora journey stream was never opened");
560
+ }
450
561
  function fetchRunDetail(base, runId) {
451
562
  return getJson(`${base}/api/journey/runs/${encodeURIComponent(runId)}`);
452
563
  }
453
- async function awaitByPolling(base, runId, options) {
564
+ async function awaitByPolling(base, runId, options, deadline) {
454
565
  const every = options.pollEveryMs ?? POLL_EVERY_MS2;
455
566
  const limit = options.pollLimit ?? POLL_LIMIT2;
456
567
  let latest = await fetchRunDetail(base, runId);
457
- for (let round = 0; round < limit && latest.status === "running"; round++) {
568
+ for (let round = 0; round < limit && latest.status === "running" && Date.now() < deadline; round++) {
458
569
  options.progress?.("agent working\u2026 (polling)");
459
570
  await pause(every);
460
571
  try {
@@ -476,16 +587,18 @@ async function performDeepJourney(target, options) {
476
587
  options.progress?.("target at its 24h cap \u2014 fetching the most recent stored run");
477
588
  }
478
589
  let engineError;
479
- if (!options.noStream && record.status === "running") {
590
+ let streamFailure;
591
+ if (record.status === "running") {
592
+ const deadline = Date.now() + (options.followBudgetMs ?? FOLLOW_BUDGET_MS);
593
+ const streamOptions = options.noStream ? { ...options, onTrajectory: void 0 } : options;
480
594
  try {
481
- const streamed = await followJourneyStream(base, record.stream_url, options);
482
- engineError = streamed.errorMessage;
483
- } catch {
484
- options.progress?.("stream went quiet \u2014 switching to polling");
485
- await awaitByPolling(base, record.id, options);
595
+ engineError = await streamToEnd(base, record.stream_url, streamOptions, deadline);
596
+ } catch (cause) {
597
+ if (cause instanceof JourneyStreamHttpError && cause.status !== 429) throw cause;
598
+ streamFailure = cause instanceof Error ? cause.message : String(cause);
599
+ options.progress?.(`stream unavailable (${streamFailure}) \u2014 polling`);
600
+ await awaitByPolling(base, record.id, options, deadline);
486
601
  }
487
- } else if (options.noStream && record.status === "running") {
488
- await awaitByPolling(base, record.id, options);
489
602
  }
490
603
  const detail = await awaitDetailSettled(base, record.id, options);
491
604
  if (detail.status === "running") {
@@ -493,7 +606,7 @@ async function performDeepJourney(target, options) {
493
606
  throw new DeepJourneyApiError(`ora journey run failed: ${engineError}`);
494
607
  }
495
608
  throw new DeepJourneyApiError(
496
- `run ${record.id} is still executing \u2014 the ${options.noStream ? "poll budget ran out" : "stream ended"} before a terminal result. Check ${base}/api/journey/runs/${record.id} shortly`
609
+ `run ${record.id} is still executing \u2014 ${streamFailure ? `the stream could not be followed (${streamFailure}) and polling ran out of time` : "the stream ended"} before a terminal result. Check ${base}/api/journey/runs/${record.id} shortly`
497
610
  );
498
611
  }
499
612
  warnOnNewerContract(detail.contractVersion);
@@ -518,11 +631,11 @@ async function awaitDetailSettled(base, runId, options) {
518
631
 
519
632
  // src/api/skills.ts
520
633
  import { createHash } from "crypto";
521
- var PUBLIC_BASE3 = "https://ora.ai";
634
+ var PUBLIC_BASE4 = "https://ora.ai";
522
635
  var SkillApiError = class extends Error {
523
636
  };
524
637
  function resolveBase(baseUrl) {
525
- return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE3).replace(/\/+$/, "");
638
+ return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE4).replace(/\/+$/, "");
526
639
  }
527
640
  async function fetchSkillIndex(baseUrl) {
528
641
  const base = resolveBase(baseUrl);
@@ -572,12 +685,14 @@ async function fetchSkill(name, baseUrl) {
572
685
  return { entry, bytes };
573
686
  }
574
687
  export {
688
+ AgentFilesApiError,
575
689
  AuditApiError,
576
690
  BUILT_AGAINST,
577
691
  DeepJourneyApiError,
578
692
  SkillApiError,
579
693
  performAudit as audit,
580
694
  performDeepJourney as deepJourney,
695
+ fetchAgentFiles,
581
696
  fetchJourneyAgents,
582
697
  fetchJourneyIntents,
583
698
  fetchSkill,