ax 0.10.2 → 0.11.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.
@@ -1,2 +1,2 @@
1
1
  /** The ora contract version (spec info.version) these types were generated from. */
2
- export declare const BUILT_AGAINST = "1.32.0";
2
+ export declare const BUILT_AGAINST = "1.42.0";
package/dist/env.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Loads a local `.env` into the environment, if one is there.
3
+ *
4
+ * The CLI already promised this everywhere but never did it: `.env.example`
5
+ * says "Copy to `.env` and fill in", the missing-key error points at "a local
6
+ * .env file", and `.env.example` even ships inside the published tarball — yet
7
+ * nothing ever read the file. Following those instructions produced
8
+ * "Missing ORA_API_KEY".
9
+ *
10
+ * Uses Node's built-in loader rather than a dependency: the CLI ships as one
11
+ * self-contained bundle with no runtime deps, and this keeps it that way.
12
+ *
13
+ * Reads only the current directory, matching what the docs describe and what
14
+ * dotenv does by default. Exported variables win over the file, so a key set
15
+ * for the shell or by CI beats a stale `.env` left in the directory.
16
+ *
17
+ * Remembers which variables the file supplied (see `fromLocalEnvFile`): a file
18
+ * in whatever directory ax runs from is not the user's word on where a key goes.
19
+ *
20
+ * @returns whether a file was actually loaded.
21
+ */
22
+ export declare function loadLocalEnv(): boolean;
23
+ /** Whether `name` came from the last `loadLocalEnv`'s file rather than the shell. */
24
+ export declare function fromLocalEnvFile(name: string): boolean;
package/dist/index.cjs CHANGED
@@ -70,8 +70,19 @@ async function errorBody(res) {
70
70
  payload
71
71
  };
72
72
  }
73
- async function errorBodyText(res) {
74
- return (await errorBody(res)).message;
73
+ async function usageLimitMessage(res) {
74
+ let body = null;
75
+ try {
76
+ body = await res.clone().json();
77
+ } catch {
78
+ return null;
79
+ }
80
+ if (body?.error !== "usage_limit_reached") return null;
81
+ const used = body.used !== void 0 && body.limit !== void 0 ? ` (${body.used} of ${body.limit})` : "";
82
+ const resets = body.resets_at ? ` It resets at ${body.resets_at}.` : "";
83
+ const scope = body.kind ? `${body.kind} limit` : "usage limit";
84
+ const period = body.period ? ` for the ${body.period}` : "";
85
+ return `this API key has used its ${scope}${period}${used}.${resets} GET /api/usage shows the numbers; ask ora to raise the limit.`;
75
86
  }
76
87
  var pause = (ms) => new Promise((r) => setTimeout(r, ms));
77
88
 
@@ -142,7 +153,7 @@ async function fetchAgentFiles(domain, options = {}) {
142
153
  }
143
154
 
144
155
  // src/contract/version.ts
145
- var BUILT_AGAINST = "1.32.0";
156
+ var BUILT_AGAINST = "1.42.0";
146
157
 
147
158
  // src/contract/index.ts
148
159
  function minor(version) {
@@ -165,6 +176,57 @@ function warnOnNewerContract(payloadVersion) {
165
176
  );
166
177
  }
167
178
 
179
+ // src/env.ts
180
+ var fromFile = /* @__PURE__ */ new Set();
181
+ function envName(name) {
182
+ return process.platform === "win32" ? name.toUpperCase() : name;
183
+ }
184
+ function fromLocalEnvFile(name) {
185
+ return fromFile.has(envName(name));
186
+ }
187
+
188
+ // src/api/key-destination.ts
189
+ var KeyDestinationError = class extends Error {
190
+ constructor(message) {
191
+ super(message);
192
+ this.name = "KeyDestinationError";
193
+ }
194
+ };
195
+ function isLoopback(hostname) {
196
+ return hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
197
+ }
198
+ function isThisMachine(hostname) {
199
+ return isLoopback(hostname) || hostname.endsWith(".localhost");
200
+ }
201
+ function keyDestinationProblem(base, variable, defaultBase) {
202
+ let url;
203
+ try {
204
+ url = new URL(base);
205
+ } catch {
206
+ return `${variable} is not a URL, so ax did not send your key anywhere.`;
207
+ }
208
+ if (url.origin === new URL(defaultBase).origin) return void 0;
209
+ const local = isThisMachine(url.hostname);
210
+ if (url.protocol !== "https:" && !local) {
211
+ return `${variable} is ${url.origin}. ax sends your key only over https, or over plain http to this machine.`;
212
+ }
213
+ if (!isLoopback(url.hostname) && fromLocalEnvFile(variable) && sameOrigin(process.env[variable], url)) {
214
+ return `${variable} in ./.env points at ${url.host}, so ax did not send your key there. To use that host, export ${variable} in your shell.`;
215
+ }
216
+ return void 0;
217
+ }
218
+ function sameOrigin(value, url) {
219
+ try {
220
+ return value !== void 0 && new URL(value).origin === url.origin;
221
+ } catch {
222
+ return false;
223
+ }
224
+ }
225
+ function assertKeyDestination(base, variable, defaultBase) {
226
+ const problem = keyDestinationProblem(base, variable, defaultBase);
227
+ if (problem) throw new KeyDestinationError(problem);
228
+ }
229
+
168
230
  // src/api/audit.ts
169
231
  var PUBLIC_BASE2 = "https://ora.ai";
170
232
  var STREAM_IDLE_MS = 6e4;
@@ -187,6 +249,7 @@ function authHeaders(apiKey) {
187
249
  async function performAudit(target, options = {}) {
188
250
  const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
189
251
  options = { ...options, apiKey: options.apiKey || process.env.ORA_SCAN_API_KEY || void 0 };
252
+ if (options.apiKey) assertKeyDestination(base, "ORA_API_URL", PUBLIC_BASE2);
190
253
  options.progress?.(`Auditing ${target} with ora`);
191
254
  const streamed = await consumeScanStream(base, target, options);
192
255
  warnOnNewerContract(streamed.result.contractVersion);
@@ -220,9 +283,13 @@ async function consumeScanStream(base, target, options) {
220
283
  }
221
284
  if (res.status === 429) {
222
285
  dog.disarm();
286
+ const usage = await usageLimitMessage(res);
287
+ const { payload } = await errorBody(res);
288
+ if (usage) throw new AuditApiError(`ora usage limit reached: ${usage}`, { payload });
223
289
  const wait = res.headers.get("retry-after");
224
290
  throw new AuditApiError(
225
- `ora rate limit exceeded${wait ? ` \u2014 retry after ${wait}s` : ""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`
291
+ `ora rate limit exceeded${wait ? ` \u2014 retry after ${wait}s` : ""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`,
292
+ { payload }
226
293
  );
227
294
  }
228
295
  if (!res.ok || !res.body) {
@@ -366,6 +433,7 @@ function decodeEventBlock(block) {
366
433
 
367
434
  // src/api/deep-journey.ts
368
435
  var PUBLIC_BASE3 = "https://ora.ai";
436
+ var JOURNEY_RUNS_PATH = "/api/journey/runs";
369
437
  var STREAM_IDLE_MS2 = 12e4;
370
438
  var POLL_EVERY_MS2 = 5e3;
371
439
  var POLL_LIMIT2 = 180;
@@ -373,11 +441,29 @@ var FOLLOW_BUDGET_MS = 15 * 6e4;
373
441
  var MAX_RETRY_AFTER_MS = 6e4;
374
442
  var STREAM_REOPENS = 5;
375
443
  var STREAM_REOPEN_PAUSE_MS = 2e3;
444
+ function servedNextAction(body) {
445
+ if (!body || typeof body !== "object") return void 0;
446
+ const action = body.next_action;
447
+ if (!action || typeof action !== "object") return void 0;
448
+ const { method, url, reason } = action;
449
+ return (method === "GET" || method === "POST") && typeof url === "string" && typeof reason === "string" ? action : void 0;
450
+ }
376
451
  var DeepJourneyApiError = class extends Error {
452
+ code;
453
+ runUrl;
454
+ payload;
455
+ nextAction;
456
+ constructor(message, options = {}) {
457
+ super(message);
458
+ this.code = options.code ?? null;
459
+ this.runUrl = options.runUrl;
460
+ this.payload = options.payload;
461
+ this.nextAction = options.nextAction ?? servedNextAction(options.payload);
462
+ }
377
463
  };
378
464
  var JourneyStreamHttpError = class extends DeepJourneyApiError {
379
- constructor(message, status, retryAfterMs) {
380
- super(message);
465
+ constructor(message, status, retryAfterMs, payload) {
466
+ super(message, { payload });
381
467
  this.status = status;
382
468
  this.retryAfterMs = retryAfterMs;
383
469
  }
@@ -398,7 +484,10 @@ async function getJson(url) {
398
484
  const detail = cause instanceof Error ? cause.message : String(cause);
399
485
  throw new DeepJourneyApiError(`ora request failed: ${detail}`);
400
486
  }
401
- if (!res.ok) throw new DeepJourneyApiError(`ora request failed: ${await errorBodyText(res)}`);
487
+ if (!res.ok) {
488
+ const { message, payload } = await errorBody(res);
489
+ throw new DeepJourneyApiError(`ora request failed: ${message}`, { payload });
490
+ }
402
491
  return await res.json();
403
492
  }
404
493
  function fetchJourneyIntents(baseUrl) {
@@ -432,7 +521,7 @@ async function triggerRun(base, target, options) {
432
521
  };
433
522
  let res;
434
523
  try {
435
- res = await fetch(`${base}/api/journey/runs`, {
524
+ res = await fetch(`${base}${JOURNEY_RUNS_PATH}`, {
436
525
  method: "POST",
437
526
  headers: {
438
527
  "content-type": "application/json",
@@ -447,22 +536,38 @@ async function triggerRun(base, target, options) {
447
536
  throw new DeepJourneyApiError(`ora journey request failed: ${detail}`);
448
537
  }
449
538
  if (res.status === 401) {
539
+ const { payload } = await errorBody(res);
450
540
  throw new DeepJourneyApiError(
451
- "free-text tasks need an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)"
541
+ "free-text tasks need an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)",
542
+ { code: "NEEDS_KEY", payload }
452
543
  );
453
544
  }
454
545
  if (res.status === 429) {
546
+ const usage = await usageLimitMessage(res);
547
+ const { payload } = await errorBody(res);
548
+ if (usage) {
549
+ throw new DeepJourneyApiError(`ora usage limit reached: ${usage}`, {
550
+ code: "USAGE_LIMIT_REACHED",
551
+ payload
552
+ });
553
+ }
455
554
  const wait = res.headers.get("retry-after");
456
555
  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";
457
556
  throw new DeepJourneyApiError(
458
- `ora journey caller limit exceeded${wait ? ` \u2014 retry after ${formatWait(Number(wait) * 1e3)}` : ""} (${caps})`
557
+ `ora journey caller limit exceeded${wait ? ` \u2014 retry after ${formatWait(Number(wait) * 1e3)}` : ""} (${caps})`,
558
+ { code: "RATE_LIMITED", payload }
459
559
  );
460
560
  }
461
561
  if (res.status === 503) {
462
- throw new DeepJourneyApiError("ora's run engine is unavailable right now \u2014 try again shortly");
562
+ const { payload } = await errorBody(res);
563
+ throw new DeepJourneyApiError("ora's run engine is unavailable right now \u2014 try again shortly", {
564
+ code: "ENGINE_UNAVAILABLE",
565
+ payload
566
+ });
463
567
  }
464
568
  if (!res.ok) {
465
- throw new DeepJourneyApiError(`ora journey request failed: ${await errorBodyText(res)}`);
569
+ const { message, payload } = await errorBody(res);
570
+ throw new DeepJourneyApiError(`ora journey request failed: ${message}`, { payload });
466
571
  }
467
572
  const record = await res.json();
468
573
  warnOnNewerContract(record.contractVersion);
@@ -516,10 +621,12 @@ async function followJourneyStream(base, streamPath, options) {
516
621
  if (!res.ok || !res.body) {
517
622
  dog.disarm();
518
623
  const retryAfterS = Number(res.headers.get("retry-after"));
624
+ const { message, payload } = await errorBody(res);
519
625
  throw new JourneyStreamHttpError(
520
- `ora journey stream failed (${res.status}): ${await errorBodyText(res)}`,
626
+ `ora journey stream failed (${res.status}): ${message}`,
521
627
  res.status,
522
- Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0
628
+ Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0,
629
+ payload
523
630
  );
524
631
  }
525
632
  const utf8 = new TextDecoder();
@@ -621,6 +728,7 @@ async function performDeepJourney(target, options) {
621
728
  ...options,
622
729
  apiKey: options.apiKey || process.env.ORA_PARTNER_API_KEY || process.env.ORA_SCAN_API_KEY || void 0
623
730
  };
731
+ if (options.apiKey) assertKeyDestination(base, "ORA_API_URL", PUBLIC_BASE3);
624
732
  const triggered = await triggerRun(base, target, options);
625
733
  const { record } = triggered;
626
734
  if (triggered.cached) {
@@ -645,8 +753,10 @@ async function performDeepJourney(target, options) {
645
753
  if (engineError) {
646
754
  throw new DeepJourneyApiError(`ora journey run failed: ${engineError}`);
647
755
  }
756
+ const runUrl = `${base}/api/journey/runs/${record.id}`;
648
757
  throw new DeepJourneyApiError(
649
- `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`
758
+ `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 ${runUrl} shortly`,
759
+ { code: "RUN_STILL_RUNNING", runUrl, nextAction: servedNextAction(detail) }
650
760
  );
651
761
  }
652
762
  warnOnNewerContract(detail.contractVersion);
@@ -673,6 +783,14 @@ async function awaitDetailSettled(base, runId, options) {
673
783
  var import_node_crypto = require("crypto");
674
784
  var PUBLIC_BASE4 = "https://ora.ai";
675
785
  var SkillApiError = class extends Error {
786
+ code;
787
+ payload;
788
+ constructor(message, code, options = {}) {
789
+ super(message);
790
+ this.name = "SkillApiError";
791
+ this.code = code;
792
+ this.payload = options.payload;
793
+ }
676
794
  };
677
795
  function resolveBase(baseUrl) {
678
796
  return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE4).replace(/\/+$/, "");
@@ -687,12 +805,20 @@ async function fetchSkillIndex(baseUrl) {
687
805
  });
688
806
  } catch (cause) {
689
807
  throw new SkillApiError(
690
- `could not reach the skill registry at ${base}: ${cause instanceof Error ? cause.message : String(cause)}`
808
+ `could not reach the skill registry at ${base}: ${cause instanceof Error ? cause.message : String(cause)}`,
809
+ "REGISTRY_UNREACHABLE"
691
810
  );
692
811
  }
693
- if (!res.ok) throw new SkillApiError(`skill registry answered HTTP ${res.status}`);
812
+ if (!res.ok) {
813
+ const { payload } = await errorBody(res);
814
+ throw new SkillApiError(`skill registry answered HTTP ${res.status}`, "REGISTRY_ERROR", {
815
+ payload
816
+ });
817
+ }
694
818
  const body = await res.json();
695
- if (!Array.isArray(body.skills)) throw new SkillApiError("skill registry index has no skills[]");
819
+ if (!Array.isArray(body.skills)) {
820
+ throw new SkillApiError("skill registry index has no skills[]", "REGISTRY_ERROR");
821
+ }
696
822
  return body.skills;
697
823
  }
698
824
  function digestOf(bytes) {
@@ -704,7 +830,10 @@ async function fetchSkill(name, baseUrl) {
704
830
  const entry = index.find((s) => s.name === name);
705
831
  if (!entry) {
706
832
  const known = index.map((s) => s.name).join(", ");
707
- throw new SkillApiError(`unknown skill ${JSON.stringify(name)} - the registry has: ${known}`);
833
+ throw new SkillApiError(
834
+ `unknown skill ${JSON.stringify(name)} - the registry has: ${known}`,
835
+ "UNKNOWN_SKILL"
836
+ );
708
837
  }
709
838
  const url = entry.url.startsWith("http") ? entry.url : `${base}${entry.url}`;
710
839
  let res;
@@ -712,14 +841,23 @@ async function fetchSkill(name, baseUrl) {
712
841
  res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
713
842
  } catch (cause) {
714
843
  throw new SkillApiError(
715
- `could not fetch ${url}: ${cause instanceof Error ? cause.message : String(cause)}`
844
+ `could not fetch ${url}: ${cause instanceof Error ? cause.message : String(cause)}`,
845
+ "REGISTRY_UNREACHABLE"
846
+ );
847
+ }
848
+ if (!res.ok) {
849
+ const { payload } = await errorBody(res);
850
+ throw new SkillApiError(
851
+ `skill fetch answered HTTP ${res.status} for ${url}`,
852
+ "REGISTRY_ERROR",
853
+ { payload }
716
854
  );
717
855
  }
718
- if (!res.ok) throw new SkillApiError(`skill fetch answered HTTP ${res.status} for ${url}`);
719
856
  const bytes = new Uint8Array(await res.arrayBuffer());
720
857
  if (entry.digest && digestOf(bytes) !== entry.digest) {
721
858
  throw new SkillApiError(
722
- `digest mismatch for ${name}: index says ${entry.digest}, served bytes hash to ${digestOf(bytes)} - refusing to use them`
859
+ `digest mismatch for ${name}: index says ${entry.digest}, served bytes hash to ${digestOf(bytes)} - refusing to use them`,
860
+ "DIGEST_MISMATCH"
723
861
  );
724
862
  }
725
863
  return { entry, bytes };
package/dist/index.js CHANGED
@@ -32,8 +32,19 @@ async function errorBody(res) {
32
32
  payload
33
33
  };
34
34
  }
35
- async function errorBodyText(res) {
36
- return (await errorBody(res)).message;
35
+ async function usageLimitMessage(res) {
36
+ let body = null;
37
+ try {
38
+ body = await res.clone().json();
39
+ } catch {
40
+ return null;
41
+ }
42
+ if (body?.error !== "usage_limit_reached") return null;
43
+ const used = body.used !== void 0 && body.limit !== void 0 ? ` (${body.used} of ${body.limit})` : "";
44
+ const resets = body.resets_at ? ` It resets at ${body.resets_at}.` : "";
45
+ const scope = body.kind ? `${body.kind} limit` : "usage limit";
46
+ const period = body.period ? ` for the ${body.period}` : "";
47
+ return `this API key has used its ${scope}${period}${used}.${resets} GET /api/usage shows the numbers; ask ora to raise the limit.`;
37
48
  }
38
49
  var pause = (ms) => new Promise((r) => setTimeout(r, ms));
39
50
 
@@ -104,7 +115,7 @@ async function fetchAgentFiles(domain, options = {}) {
104
115
  }
105
116
 
106
117
  // src/contract/version.ts
107
- var BUILT_AGAINST = "1.32.0";
118
+ var BUILT_AGAINST = "1.42.0";
108
119
 
109
120
  // src/contract/index.ts
110
121
  function minor(version) {
@@ -127,6 +138,57 @@ function warnOnNewerContract(payloadVersion) {
127
138
  );
128
139
  }
129
140
 
141
+ // src/env.ts
142
+ var fromFile = /* @__PURE__ */ new Set();
143
+ function envName(name) {
144
+ return process.platform === "win32" ? name.toUpperCase() : name;
145
+ }
146
+ function fromLocalEnvFile(name) {
147
+ return fromFile.has(envName(name));
148
+ }
149
+
150
+ // src/api/key-destination.ts
151
+ var KeyDestinationError = class extends Error {
152
+ constructor(message) {
153
+ super(message);
154
+ this.name = "KeyDestinationError";
155
+ }
156
+ };
157
+ function isLoopback(hostname) {
158
+ return hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
159
+ }
160
+ function isThisMachine(hostname) {
161
+ return isLoopback(hostname) || hostname.endsWith(".localhost");
162
+ }
163
+ function keyDestinationProblem(base, variable, defaultBase) {
164
+ let url;
165
+ try {
166
+ url = new URL(base);
167
+ } catch {
168
+ return `${variable} is not a URL, so ax did not send your key anywhere.`;
169
+ }
170
+ if (url.origin === new URL(defaultBase).origin) return void 0;
171
+ const local = isThisMachine(url.hostname);
172
+ if (url.protocol !== "https:" && !local) {
173
+ return `${variable} is ${url.origin}. ax sends your key only over https, or over plain http to this machine.`;
174
+ }
175
+ if (!isLoopback(url.hostname) && fromLocalEnvFile(variable) && sameOrigin(process.env[variable], url)) {
176
+ return `${variable} in ./.env points at ${url.host}, so ax did not send your key there. To use that host, export ${variable} in your shell.`;
177
+ }
178
+ return void 0;
179
+ }
180
+ function sameOrigin(value, url) {
181
+ try {
182
+ return value !== void 0 && new URL(value).origin === url.origin;
183
+ } catch {
184
+ return false;
185
+ }
186
+ }
187
+ function assertKeyDestination(base, variable, defaultBase) {
188
+ const problem = keyDestinationProblem(base, variable, defaultBase);
189
+ if (problem) throw new KeyDestinationError(problem);
190
+ }
191
+
130
192
  // src/api/audit.ts
131
193
  var PUBLIC_BASE2 = "https://ora.ai";
132
194
  var STREAM_IDLE_MS = 6e4;
@@ -149,6 +211,7 @@ function authHeaders(apiKey) {
149
211
  async function performAudit(target, options = {}) {
150
212
  const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
151
213
  options = { ...options, apiKey: options.apiKey || process.env.ORA_SCAN_API_KEY || void 0 };
214
+ if (options.apiKey) assertKeyDestination(base, "ORA_API_URL", PUBLIC_BASE2);
152
215
  options.progress?.(`Auditing ${target} with ora`);
153
216
  const streamed = await consumeScanStream(base, target, options);
154
217
  warnOnNewerContract(streamed.result.contractVersion);
@@ -182,9 +245,13 @@ async function consumeScanStream(base, target, options) {
182
245
  }
183
246
  if (res.status === 429) {
184
247
  dog.disarm();
248
+ const usage = await usageLimitMessage(res);
249
+ const { payload } = await errorBody(res);
250
+ if (usage) throw new AuditApiError(`ora usage limit reached: ${usage}`, { payload });
185
251
  const wait = res.headers.get("retry-after");
186
252
  throw new AuditApiError(
187
- `ora rate limit exceeded${wait ? ` \u2014 retry after ${wait}s` : ""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`
253
+ `ora rate limit exceeded${wait ? ` \u2014 retry after ${wait}s` : ""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`,
254
+ { payload }
188
255
  );
189
256
  }
190
257
  if (!res.ok || !res.body) {
@@ -328,6 +395,7 @@ function decodeEventBlock(block) {
328
395
 
329
396
  // src/api/deep-journey.ts
330
397
  var PUBLIC_BASE3 = "https://ora.ai";
398
+ var JOURNEY_RUNS_PATH = "/api/journey/runs";
331
399
  var STREAM_IDLE_MS2 = 12e4;
332
400
  var POLL_EVERY_MS2 = 5e3;
333
401
  var POLL_LIMIT2 = 180;
@@ -335,11 +403,29 @@ var FOLLOW_BUDGET_MS = 15 * 6e4;
335
403
  var MAX_RETRY_AFTER_MS = 6e4;
336
404
  var STREAM_REOPENS = 5;
337
405
  var STREAM_REOPEN_PAUSE_MS = 2e3;
406
+ function servedNextAction(body) {
407
+ if (!body || typeof body !== "object") return void 0;
408
+ const action = body.next_action;
409
+ if (!action || typeof action !== "object") return void 0;
410
+ const { method, url, reason } = action;
411
+ return (method === "GET" || method === "POST") && typeof url === "string" && typeof reason === "string" ? action : void 0;
412
+ }
338
413
  var DeepJourneyApiError = class extends Error {
414
+ code;
415
+ runUrl;
416
+ payload;
417
+ nextAction;
418
+ constructor(message, options = {}) {
419
+ super(message);
420
+ this.code = options.code ?? null;
421
+ this.runUrl = options.runUrl;
422
+ this.payload = options.payload;
423
+ this.nextAction = options.nextAction ?? servedNextAction(options.payload);
424
+ }
339
425
  };
340
426
  var JourneyStreamHttpError = class extends DeepJourneyApiError {
341
- constructor(message, status, retryAfterMs) {
342
- super(message);
427
+ constructor(message, status, retryAfterMs, payload) {
428
+ super(message, { payload });
343
429
  this.status = status;
344
430
  this.retryAfterMs = retryAfterMs;
345
431
  }
@@ -360,7 +446,10 @@ async function getJson(url) {
360
446
  const detail = cause instanceof Error ? cause.message : String(cause);
361
447
  throw new DeepJourneyApiError(`ora request failed: ${detail}`);
362
448
  }
363
- if (!res.ok) throw new DeepJourneyApiError(`ora request failed: ${await errorBodyText(res)}`);
449
+ if (!res.ok) {
450
+ const { message, payload } = await errorBody(res);
451
+ throw new DeepJourneyApiError(`ora request failed: ${message}`, { payload });
452
+ }
364
453
  return await res.json();
365
454
  }
366
455
  function fetchJourneyIntents(baseUrl) {
@@ -394,7 +483,7 @@ async function triggerRun(base, target, options) {
394
483
  };
395
484
  let res;
396
485
  try {
397
- res = await fetch(`${base}/api/journey/runs`, {
486
+ res = await fetch(`${base}${JOURNEY_RUNS_PATH}`, {
398
487
  method: "POST",
399
488
  headers: {
400
489
  "content-type": "application/json",
@@ -409,22 +498,38 @@ async function triggerRun(base, target, options) {
409
498
  throw new DeepJourneyApiError(`ora journey request failed: ${detail}`);
410
499
  }
411
500
  if (res.status === 401) {
501
+ const { payload } = await errorBody(res);
412
502
  throw new DeepJourneyApiError(
413
- "free-text tasks need an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)"
503
+ "free-text tasks need an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)",
504
+ { code: "NEEDS_KEY", payload }
414
505
  );
415
506
  }
416
507
  if (res.status === 429) {
508
+ const usage = await usageLimitMessage(res);
509
+ const { payload } = await errorBody(res);
510
+ if (usage) {
511
+ throw new DeepJourneyApiError(`ora usage limit reached: ${usage}`, {
512
+ code: "USAGE_LIMIT_REACHED",
513
+ payload
514
+ });
515
+ }
417
516
  const wait = res.headers.get("retry-after");
418
517
  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";
419
518
  throw new DeepJourneyApiError(
420
- `ora journey caller limit exceeded${wait ? ` \u2014 retry after ${formatWait(Number(wait) * 1e3)}` : ""} (${caps})`
519
+ `ora journey caller limit exceeded${wait ? ` \u2014 retry after ${formatWait(Number(wait) * 1e3)}` : ""} (${caps})`,
520
+ { code: "RATE_LIMITED", payload }
421
521
  );
422
522
  }
423
523
  if (res.status === 503) {
424
- throw new DeepJourneyApiError("ora's run engine is unavailable right now \u2014 try again shortly");
524
+ const { payload } = await errorBody(res);
525
+ throw new DeepJourneyApiError("ora's run engine is unavailable right now \u2014 try again shortly", {
526
+ code: "ENGINE_UNAVAILABLE",
527
+ payload
528
+ });
425
529
  }
426
530
  if (!res.ok) {
427
- throw new DeepJourneyApiError(`ora journey request failed: ${await errorBodyText(res)}`);
531
+ const { message, payload } = await errorBody(res);
532
+ throw new DeepJourneyApiError(`ora journey request failed: ${message}`, { payload });
428
533
  }
429
534
  const record = await res.json();
430
535
  warnOnNewerContract(record.contractVersion);
@@ -478,10 +583,12 @@ async function followJourneyStream(base, streamPath, options) {
478
583
  if (!res.ok || !res.body) {
479
584
  dog.disarm();
480
585
  const retryAfterS = Number(res.headers.get("retry-after"));
586
+ const { message, payload } = await errorBody(res);
481
587
  throw new JourneyStreamHttpError(
482
- `ora journey stream failed (${res.status}): ${await errorBodyText(res)}`,
588
+ `ora journey stream failed (${res.status}): ${message}`,
483
589
  res.status,
484
- Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0
590
+ Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0,
591
+ payload
485
592
  );
486
593
  }
487
594
  const utf8 = new TextDecoder();
@@ -583,6 +690,7 @@ async function performDeepJourney(target, options) {
583
690
  ...options,
584
691
  apiKey: options.apiKey || process.env.ORA_PARTNER_API_KEY || process.env.ORA_SCAN_API_KEY || void 0
585
692
  };
693
+ if (options.apiKey) assertKeyDestination(base, "ORA_API_URL", PUBLIC_BASE3);
586
694
  const triggered = await triggerRun(base, target, options);
587
695
  const { record } = triggered;
588
696
  if (triggered.cached) {
@@ -607,8 +715,10 @@ async function performDeepJourney(target, options) {
607
715
  if (engineError) {
608
716
  throw new DeepJourneyApiError(`ora journey run failed: ${engineError}`);
609
717
  }
718
+ const runUrl = `${base}/api/journey/runs/${record.id}`;
610
719
  throw new DeepJourneyApiError(
611
- `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`
720
+ `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 ${runUrl} shortly`,
721
+ { code: "RUN_STILL_RUNNING", runUrl, nextAction: servedNextAction(detail) }
612
722
  );
613
723
  }
614
724
  warnOnNewerContract(detail.contractVersion);
@@ -635,6 +745,14 @@ async function awaitDetailSettled(base, runId, options) {
635
745
  import { createHash } from "crypto";
636
746
  var PUBLIC_BASE4 = "https://ora.ai";
637
747
  var SkillApiError = class extends Error {
748
+ code;
749
+ payload;
750
+ constructor(message, code, options = {}) {
751
+ super(message);
752
+ this.name = "SkillApiError";
753
+ this.code = code;
754
+ this.payload = options.payload;
755
+ }
638
756
  };
639
757
  function resolveBase(baseUrl) {
640
758
  return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE4).replace(/\/+$/, "");
@@ -649,12 +767,20 @@ async function fetchSkillIndex(baseUrl) {
649
767
  });
650
768
  } catch (cause) {
651
769
  throw new SkillApiError(
652
- `could not reach the skill registry at ${base}: ${cause instanceof Error ? cause.message : String(cause)}`
770
+ `could not reach the skill registry at ${base}: ${cause instanceof Error ? cause.message : String(cause)}`,
771
+ "REGISTRY_UNREACHABLE"
653
772
  );
654
773
  }
655
- if (!res.ok) throw new SkillApiError(`skill registry answered HTTP ${res.status}`);
774
+ if (!res.ok) {
775
+ const { payload } = await errorBody(res);
776
+ throw new SkillApiError(`skill registry answered HTTP ${res.status}`, "REGISTRY_ERROR", {
777
+ payload
778
+ });
779
+ }
656
780
  const body = await res.json();
657
- if (!Array.isArray(body.skills)) throw new SkillApiError("skill registry index has no skills[]");
781
+ if (!Array.isArray(body.skills)) {
782
+ throw new SkillApiError("skill registry index has no skills[]", "REGISTRY_ERROR");
783
+ }
658
784
  return body.skills;
659
785
  }
660
786
  function digestOf(bytes) {
@@ -666,7 +792,10 @@ async function fetchSkill(name, baseUrl) {
666
792
  const entry = index.find((s) => s.name === name);
667
793
  if (!entry) {
668
794
  const known = index.map((s) => s.name).join(", ");
669
- throw new SkillApiError(`unknown skill ${JSON.stringify(name)} - the registry has: ${known}`);
795
+ throw new SkillApiError(
796
+ `unknown skill ${JSON.stringify(name)} - the registry has: ${known}`,
797
+ "UNKNOWN_SKILL"
798
+ );
670
799
  }
671
800
  const url = entry.url.startsWith("http") ? entry.url : `${base}${entry.url}`;
672
801
  let res;
@@ -674,14 +803,23 @@ async function fetchSkill(name, baseUrl) {
674
803
  res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
675
804
  } catch (cause) {
676
805
  throw new SkillApiError(
677
- `could not fetch ${url}: ${cause instanceof Error ? cause.message : String(cause)}`
806
+ `could not fetch ${url}: ${cause instanceof Error ? cause.message : String(cause)}`,
807
+ "REGISTRY_UNREACHABLE"
808
+ );
809
+ }
810
+ if (!res.ok) {
811
+ const { payload } = await errorBody(res);
812
+ throw new SkillApiError(
813
+ `skill fetch answered HTTP ${res.status} for ${url}`,
814
+ "REGISTRY_ERROR",
815
+ { payload }
678
816
  );
679
817
  }
680
- if (!res.ok) throw new SkillApiError(`skill fetch answered HTTP ${res.status} for ${url}`);
681
818
  const bytes = new Uint8Array(await res.arrayBuffer());
682
819
  if (entry.digest && digestOf(bytes) !== entry.digest) {
683
820
  throw new SkillApiError(
684
- `digest mismatch for ${name}: index says ${entry.digest}, served bytes hash to ${digestOf(bytes)} - refusing to use them`
821
+ `digest mismatch for ${name}: index says ${entry.digest}, served bytes hash to ${digestOf(bytes)} - refusing to use them`,
822
+ "DIGEST_MISMATCH"
685
823
  );
686
824
  }
687
825
  return { entry, bytes };