ax 0.10.3 → 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.38.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
@@ -84,9 +84,6 @@ async function usageLimitMessage(res) {
84
84
  const period = body.period ? ` for the ${body.period}` : "";
85
85
  return `this API key has used its ${scope}${period}${used}.${resets} GET /api/usage shows the numbers; ask ora to raise the limit.`;
86
86
  }
87
- async function errorBodyText(res) {
88
- return (await errorBody(res)).message;
89
- }
90
87
  var pause = (ms) => new Promise((r) => setTimeout(r, ms));
91
88
 
92
89
  // src/api/agent-files.ts
@@ -156,7 +153,7 @@ async function fetchAgentFiles(domain, options = {}) {
156
153
  }
157
154
 
158
155
  // src/contract/version.ts
159
- var BUILT_AGAINST = "1.38.0";
156
+ var BUILT_AGAINST = "1.42.0";
160
157
 
161
158
  // src/contract/index.ts
162
159
  function minor(version) {
@@ -179,6 +176,57 @@ function warnOnNewerContract(payloadVersion) {
179
176
  );
180
177
  }
181
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
+
182
230
  // src/api/audit.ts
183
231
  var PUBLIC_BASE2 = "https://ora.ai";
184
232
  var STREAM_IDLE_MS = 6e4;
@@ -201,6 +249,7 @@ function authHeaders(apiKey) {
201
249
  async function performAudit(target, options = {}) {
202
250
  const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
203
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);
204
253
  options.progress?.(`Auditing ${target} with ora`);
205
254
  const streamed = await consumeScanStream(base, target, options);
206
255
  warnOnNewerContract(streamed.result.contractVersion);
@@ -235,10 +284,12 @@ async function consumeScanStream(base, target, options) {
235
284
  if (res.status === 429) {
236
285
  dog.disarm();
237
286
  const usage = await usageLimitMessage(res);
238
- if (usage) throw new AuditApiError(`ora usage limit reached: ${usage}`);
287
+ const { payload } = await errorBody(res);
288
+ if (usage) throw new AuditApiError(`ora usage limit reached: ${usage}`, { payload });
239
289
  const wait = res.headers.get("retry-after");
240
290
  throw new AuditApiError(
241
- `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 }
242
293
  );
243
294
  }
244
295
  if (!res.ok || !res.body) {
@@ -382,6 +433,7 @@ function decodeEventBlock(block) {
382
433
 
383
434
  // src/api/deep-journey.ts
384
435
  var PUBLIC_BASE3 = "https://ora.ai";
436
+ var JOURNEY_RUNS_PATH = "/api/journey/runs";
385
437
  var STREAM_IDLE_MS2 = 12e4;
386
438
  var POLL_EVERY_MS2 = 5e3;
387
439
  var POLL_LIMIT2 = 180;
@@ -389,11 +441,29 @@ var FOLLOW_BUDGET_MS = 15 * 6e4;
389
441
  var MAX_RETRY_AFTER_MS = 6e4;
390
442
  var STREAM_REOPENS = 5;
391
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
+ }
392
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
+ }
393
463
  };
394
464
  var JourneyStreamHttpError = class extends DeepJourneyApiError {
395
- constructor(message, status, retryAfterMs) {
396
- super(message);
465
+ constructor(message, status, retryAfterMs, payload) {
466
+ super(message, { payload });
397
467
  this.status = status;
398
468
  this.retryAfterMs = retryAfterMs;
399
469
  }
@@ -414,7 +484,10 @@ async function getJson(url) {
414
484
  const detail = cause instanceof Error ? cause.message : String(cause);
415
485
  throw new DeepJourneyApiError(`ora request failed: ${detail}`);
416
486
  }
417
- 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
+ }
418
491
  return await res.json();
419
492
  }
420
493
  function fetchJourneyIntents(baseUrl) {
@@ -448,7 +521,7 @@ async function triggerRun(base, target, options) {
448
521
  };
449
522
  let res;
450
523
  try {
451
- res = await fetch(`${base}/api/journey/runs`, {
524
+ res = await fetch(`${base}${JOURNEY_RUNS_PATH}`, {
452
525
  method: "POST",
453
526
  headers: {
454
527
  "content-type": "application/json",
@@ -463,24 +536,38 @@ async function triggerRun(base, target, options) {
463
536
  throw new DeepJourneyApiError(`ora journey request failed: ${detail}`);
464
537
  }
465
538
  if (res.status === 401) {
539
+ const { payload } = await errorBody(res);
466
540
  throw new DeepJourneyApiError(
467
- "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 }
468
543
  );
469
544
  }
470
545
  if (res.status === 429) {
471
546
  const usage = await usageLimitMessage(res);
472
- if (usage) throw new DeepJourneyApiError(`ora usage limit reached: ${usage}`);
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
+ }
473
554
  const wait = res.headers.get("retry-after");
474
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";
475
556
  throw new DeepJourneyApiError(
476
- `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 }
477
559
  );
478
560
  }
479
561
  if (res.status === 503) {
480
- 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
+ });
481
567
  }
482
568
  if (!res.ok) {
483
- 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 });
484
571
  }
485
572
  const record = await res.json();
486
573
  warnOnNewerContract(record.contractVersion);
@@ -534,10 +621,12 @@ async function followJourneyStream(base, streamPath, options) {
534
621
  if (!res.ok || !res.body) {
535
622
  dog.disarm();
536
623
  const retryAfterS = Number(res.headers.get("retry-after"));
624
+ const { message, payload } = await errorBody(res);
537
625
  throw new JourneyStreamHttpError(
538
- `ora journey stream failed (${res.status}): ${await errorBodyText(res)}`,
626
+ `ora journey stream failed (${res.status}): ${message}`,
539
627
  res.status,
540
- Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0
628
+ Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0,
629
+ payload
541
630
  );
542
631
  }
543
632
  const utf8 = new TextDecoder();
@@ -639,6 +728,7 @@ async function performDeepJourney(target, options) {
639
728
  ...options,
640
729
  apiKey: options.apiKey || process.env.ORA_PARTNER_API_KEY || process.env.ORA_SCAN_API_KEY || void 0
641
730
  };
731
+ if (options.apiKey) assertKeyDestination(base, "ORA_API_URL", PUBLIC_BASE3);
642
732
  const triggered = await triggerRun(base, target, options);
643
733
  const { record } = triggered;
644
734
  if (triggered.cached) {
@@ -663,8 +753,10 @@ async function performDeepJourney(target, options) {
663
753
  if (engineError) {
664
754
  throw new DeepJourneyApiError(`ora journey run failed: ${engineError}`);
665
755
  }
756
+ const runUrl = `${base}/api/journey/runs/${record.id}`;
666
757
  throw new DeepJourneyApiError(
667
- `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) }
668
760
  );
669
761
  }
670
762
  warnOnNewerContract(detail.contractVersion);
@@ -691,6 +783,14 @@ async function awaitDetailSettled(base, runId, options) {
691
783
  var import_node_crypto = require("crypto");
692
784
  var PUBLIC_BASE4 = "https://ora.ai";
693
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
+ }
694
794
  };
695
795
  function resolveBase(baseUrl) {
696
796
  return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE4).replace(/\/+$/, "");
@@ -705,12 +805,20 @@ async function fetchSkillIndex(baseUrl) {
705
805
  });
706
806
  } catch (cause) {
707
807
  throw new SkillApiError(
708
- `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"
709
810
  );
710
811
  }
711
- 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
+ }
712
818
  const body = await res.json();
713
- 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
+ }
714
822
  return body.skills;
715
823
  }
716
824
  function digestOf(bytes) {
@@ -722,7 +830,10 @@ async function fetchSkill(name, baseUrl) {
722
830
  const entry = index.find((s) => s.name === name);
723
831
  if (!entry) {
724
832
  const known = index.map((s) => s.name).join(", ");
725
- 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
+ );
726
837
  }
727
838
  const url = entry.url.startsWith("http") ? entry.url : `${base}${entry.url}`;
728
839
  let res;
@@ -730,14 +841,23 @@ async function fetchSkill(name, baseUrl) {
730
841
  res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
731
842
  } catch (cause) {
732
843
  throw new SkillApiError(
733
- `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 }
734
854
  );
735
855
  }
736
- if (!res.ok) throw new SkillApiError(`skill fetch answered HTTP ${res.status} for ${url}`);
737
856
  const bytes = new Uint8Array(await res.arrayBuffer());
738
857
  if (entry.digest && digestOf(bytes) !== entry.digest) {
739
858
  throw new SkillApiError(
740
- `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"
741
861
  );
742
862
  }
743
863
  return { entry, bytes };
package/dist/index.js CHANGED
@@ -46,9 +46,6 @@ async function usageLimitMessage(res) {
46
46
  const period = body.period ? ` for the ${body.period}` : "";
47
47
  return `this API key has used its ${scope}${period}${used}.${resets} GET /api/usage shows the numbers; ask ora to raise the limit.`;
48
48
  }
49
- async function errorBodyText(res) {
50
- return (await errorBody(res)).message;
51
- }
52
49
  var pause = (ms) => new Promise((r) => setTimeout(r, ms));
53
50
 
54
51
  // src/api/agent-files.ts
@@ -118,7 +115,7 @@ async function fetchAgentFiles(domain, options = {}) {
118
115
  }
119
116
 
120
117
  // src/contract/version.ts
121
- var BUILT_AGAINST = "1.38.0";
118
+ var BUILT_AGAINST = "1.42.0";
122
119
 
123
120
  // src/contract/index.ts
124
121
  function minor(version) {
@@ -141,6 +138,57 @@ function warnOnNewerContract(payloadVersion) {
141
138
  );
142
139
  }
143
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
+
144
192
  // src/api/audit.ts
145
193
  var PUBLIC_BASE2 = "https://ora.ai";
146
194
  var STREAM_IDLE_MS = 6e4;
@@ -163,6 +211,7 @@ function authHeaders(apiKey) {
163
211
  async function performAudit(target, options = {}) {
164
212
  const base = (options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE2).replace(/\/+$/, "");
165
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);
166
215
  options.progress?.(`Auditing ${target} with ora`);
167
216
  const streamed = await consumeScanStream(base, target, options);
168
217
  warnOnNewerContract(streamed.result.contractVersion);
@@ -197,10 +246,12 @@ async function consumeScanStream(base, target, options) {
197
246
  if (res.status === 429) {
198
247
  dog.disarm();
199
248
  const usage = await usageLimitMessage(res);
200
- if (usage) throw new AuditApiError(`ora usage limit reached: ${usage}`);
249
+ const { payload } = await errorBody(res);
250
+ if (usage) throw new AuditApiError(`ora usage limit reached: ${usage}`, { payload });
201
251
  const wait = res.headers.get("retry-after");
202
252
  throw new AuditApiError(
203
- `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 }
204
255
  );
205
256
  }
206
257
  if (!res.ok || !res.body) {
@@ -344,6 +395,7 @@ function decodeEventBlock(block) {
344
395
 
345
396
  // src/api/deep-journey.ts
346
397
  var PUBLIC_BASE3 = "https://ora.ai";
398
+ var JOURNEY_RUNS_PATH = "/api/journey/runs";
347
399
  var STREAM_IDLE_MS2 = 12e4;
348
400
  var POLL_EVERY_MS2 = 5e3;
349
401
  var POLL_LIMIT2 = 180;
@@ -351,11 +403,29 @@ var FOLLOW_BUDGET_MS = 15 * 6e4;
351
403
  var MAX_RETRY_AFTER_MS = 6e4;
352
404
  var STREAM_REOPENS = 5;
353
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
+ }
354
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
+ }
355
425
  };
356
426
  var JourneyStreamHttpError = class extends DeepJourneyApiError {
357
- constructor(message, status, retryAfterMs) {
358
- super(message);
427
+ constructor(message, status, retryAfterMs, payload) {
428
+ super(message, { payload });
359
429
  this.status = status;
360
430
  this.retryAfterMs = retryAfterMs;
361
431
  }
@@ -376,7 +446,10 @@ async function getJson(url) {
376
446
  const detail = cause instanceof Error ? cause.message : String(cause);
377
447
  throw new DeepJourneyApiError(`ora request failed: ${detail}`);
378
448
  }
379
- 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
+ }
380
453
  return await res.json();
381
454
  }
382
455
  function fetchJourneyIntents(baseUrl) {
@@ -410,7 +483,7 @@ async function triggerRun(base, target, options) {
410
483
  };
411
484
  let res;
412
485
  try {
413
- res = await fetch(`${base}/api/journey/runs`, {
486
+ res = await fetch(`${base}${JOURNEY_RUNS_PATH}`, {
414
487
  method: "POST",
415
488
  headers: {
416
489
  "content-type": "application/json",
@@ -425,24 +498,38 @@ async function triggerRun(base, target, options) {
425
498
  throw new DeepJourneyApiError(`ora journey request failed: ${detail}`);
426
499
  }
427
500
  if (res.status === 401) {
501
+ const { payload } = await errorBody(res);
428
502
  throw new DeepJourneyApiError(
429
- "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 }
430
505
  );
431
506
  }
432
507
  if (res.status === 429) {
433
508
  const usage = await usageLimitMessage(res);
434
- if (usage) throw new DeepJourneyApiError(`ora usage limit reached: ${usage}`);
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
+ }
435
516
  const wait = res.headers.get("retry-after");
436
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";
437
518
  throw new DeepJourneyApiError(
438
- `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 }
439
521
  );
440
522
  }
441
523
  if (res.status === 503) {
442
- 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
+ });
443
529
  }
444
530
  if (!res.ok) {
445
- 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 });
446
533
  }
447
534
  const record = await res.json();
448
535
  warnOnNewerContract(record.contractVersion);
@@ -496,10 +583,12 @@ async function followJourneyStream(base, streamPath, options) {
496
583
  if (!res.ok || !res.body) {
497
584
  dog.disarm();
498
585
  const retryAfterS = Number(res.headers.get("retry-after"));
586
+ const { message, payload } = await errorBody(res);
499
587
  throw new JourneyStreamHttpError(
500
- `ora journey stream failed (${res.status}): ${await errorBodyText(res)}`,
588
+ `ora journey stream failed (${res.status}): ${message}`,
501
589
  res.status,
502
- Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0
590
+ Number.isFinite(retryAfterS) && retryAfterS > 0 ? retryAfterS * 1e3 : void 0,
591
+ payload
503
592
  );
504
593
  }
505
594
  const utf8 = new TextDecoder();
@@ -601,6 +690,7 @@ async function performDeepJourney(target, options) {
601
690
  ...options,
602
691
  apiKey: options.apiKey || process.env.ORA_PARTNER_API_KEY || process.env.ORA_SCAN_API_KEY || void 0
603
692
  };
693
+ if (options.apiKey) assertKeyDestination(base, "ORA_API_URL", PUBLIC_BASE3);
604
694
  const triggered = await triggerRun(base, target, options);
605
695
  const { record } = triggered;
606
696
  if (triggered.cached) {
@@ -625,8 +715,10 @@ async function performDeepJourney(target, options) {
625
715
  if (engineError) {
626
716
  throw new DeepJourneyApiError(`ora journey run failed: ${engineError}`);
627
717
  }
718
+ const runUrl = `${base}/api/journey/runs/${record.id}`;
628
719
  throw new DeepJourneyApiError(
629
- `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) }
630
722
  );
631
723
  }
632
724
  warnOnNewerContract(detail.contractVersion);
@@ -653,6 +745,14 @@ async function awaitDetailSettled(base, runId, options) {
653
745
  import { createHash } from "crypto";
654
746
  var PUBLIC_BASE4 = "https://ora.ai";
655
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
+ }
656
756
  };
657
757
  function resolveBase(baseUrl) {
658
758
  return (baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE4).replace(/\/+$/, "");
@@ -667,12 +767,20 @@ async function fetchSkillIndex(baseUrl) {
667
767
  });
668
768
  } catch (cause) {
669
769
  throw new SkillApiError(
670
- `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"
671
772
  );
672
773
  }
673
- 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
+ }
674
780
  const body = await res.json();
675
- 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
+ }
676
784
  return body.skills;
677
785
  }
678
786
  function digestOf(bytes) {
@@ -684,7 +792,10 @@ async function fetchSkill(name, baseUrl) {
684
792
  const entry = index.find((s) => s.name === name);
685
793
  if (!entry) {
686
794
  const known = index.map((s) => s.name).join(", ");
687
- 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
+ );
688
799
  }
689
800
  const url = entry.url.startsWith("http") ? entry.url : `${base}${entry.url}`;
690
801
  let res;
@@ -692,14 +803,23 @@ async function fetchSkill(name, baseUrl) {
692
803
  res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
693
804
  } catch (cause) {
694
805
  throw new SkillApiError(
695
- `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 }
696
816
  );
697
817
  }
698
- if (!res.ok) throw new SkillApiError(`skill fetch answered HTTP ${res.status} for ${url}`);
699
818
  const bytes = new Uint8Array(await res.arrayBuffer());
700
819
  if (entry.digest && digestOf(bytes) !== entry.digest) {
701
820
  throw new SkillApiError(
702
- `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"
703
823
  );
704
824
  }
705
825
  return { entry, bytes };