@riddledc/riddle-proof 0.5.53 → 0.5.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/basic-gameplay.cjs +255 -0
  2. package/dist/basic-gameplay.d.cts +117 -0
  3. package/dist/basic-gameplay.d.ts +117 -0
  4. package/dist/basic-gameplay.js +14 -0
  5. package/dist/checkpoint.cjs +2 -2
  6. package/dist/checkpoint.js +1 -1
  7. package/dist/{chunk-KYGWIA7A.js → chunk-2FBF2UDZ.js} +8 -8
  8. package/dist/{chunk-T5RHGGQ2.js → chunk-33XO42CY.js} +2 -2
  9. package/dist/{chunk-53UPEUVU.js → chunk-3UHWI3FO.js} +1 -1
  10. package/dist/{chunk-PVUZZ2P6.js → chunk-MO24D3PY.js} +2 -1
  11. package/dist/{chunk-4ASMX4R6.js → chunk-RFJ5BQF6.js} +1 -0
  12. package/dist/chunk-RNGJX62B.js +227 -0
  13. package/dist/{chunk-QBOKV3ES.js → chunk-RXFKKYWA.js} +1 -1
  14. package/dist/chunk-UR6ADV4Y.js +163 -0
  15. package/dist/cli.cjs +217 -12
  16. package/dist/cli.js +67 -10
  17. package/dist/engine-harness.cjs +4 -2
  18. package/dist/engine-harness.js +5 -5
  19. package/dist/index.cjs +409 -5
  20. package/dist/index.d.cts +2 -0
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.js +49 -13
  23. package/dist/openclaw.cjs +1 -0
  24. package/dist/openclaw.js +3 -3
  25. package/dist/proof-run-core.cjs +1 -0
  26. package/dist/proof-run-core.js +1 -1
  27. package/dist/proof-run-engine.cjs +1 -0
  28. package/dist/proof-run-engine.d.cts +3 -3
  29. package/dist/proof-run-engine.d.ts +3 -3
  30. package/dist/proof-run-engine.js +1 -1
  31. package/dist/riddle-client.cjs +207 -0
  32. package/dist/riddle-client.d.cts +71 -0
  33. package/dist/riddle-client.d.ts +71 -0
  34. package/dist/riddle-client.js +26 -0
  35. package/dist/run-card.js +2 -2
  36. package/dist/runner.cjs +1 -0
  37. package/dist/runner.js +4 -4
  38. package/dist/state.cjs +1 -0
  39. package/dist/state.js +3 -3
  40. package/dist/types.d.cts +1 -0
  41. package/dist/types.d.ts +1 -0
  42. package/package.json +12 -2
package/dist/index.cjs CHANGED
@@ -363,6 +363,7 @@ function visualDeltaRequiredForState(state = {}) {
363
363
  const bundle = objectValue(state?.evidence_bundle);
364
364
  const contract = objectValue(bundle.artifact_contract);
365
365
  const required = objectValue(contract.required);
366
+ if (required.visual_delta === false) return false;
366
367
  return required.visual_delta === true || VISUAL_FIRST_MODES.has(normalizedVerificationMode(state));
367
368
  }
368
369
  function visualDeltaForState(state = {}) {
@@ -1407,9 +1408,9 @@ function cleanupMergedProofRun(state, repoDir, params, prState) {
1407
1408
  const baseBranch = stringValue(prState.base_branch) || stringValue(state?.base_branch) || "main";
1408
1409
  let fetchedBase = params.fetch_base === false;
1409
1410
  if (params.fetch_base !== false && baseBranch) {
1410
- const fetch = commandResult("git", ["fetch", "origin", baseBranch], repoDir, 12e4);
1411
- cleanup.fetch = fetch.ok ? { ok: true, base_branch: baseBranch } : { ok: false, base_branch: baseBranch, error: fetch.stderr.slice(0, 300) };
1412
- if (fetch.ok) {
1411
+ const fetch2 = commandResult("git", ["fetch", "origin", baseBranch], repoDir, 12e4);
1412
+ cleanup.fetch = fetch2.ok ? { ok: true, base_branch: baseBranch } : { ok: false, base_branch: baseBranch, error: fetch2.stderr.slice(0, 300) };
1413
+ if (fetch2.ok) {
1413
1414
  fetchedBase = true;
1414
1415
  state.base_synced_at = (/* @__PURE__ */ new Date()).toISOString();
1415
1416
  state.base_branch = baseBranch;
@@ -2775,6 +2776,10 @@ __export(index_exports, {
2775
2776
  DEFAULT_DIAGNOSTIC_ARRAY_LIMIT: () => DEFAULT_DIAGNOSTIC_ARRAY_LIMIT,
2776
2777
  DEFAULT_DIAGNOSTIC_HISTORY_LIMIT: () => DEFAULT_DIAGNOSTIC_HISTORY_LIMIT,
2777
2778
  DEFAULT_DIAGNOSTIC_STRING_LIMIT: () => DEFAULT_DIAGNOSTIC_STRING_LIMIT,
2779
+ DEFAULT_RIDDLE_API_BASE_URL: () => DEFAULT_RIDDLE_API_BASE_URL,
2780
+ DEFAULT_RIDDLE_API_KEY_FILE: () => DEFAULT_RIDDLE_API_KEY_FILE,
2781
+ RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION: () => RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION,
2782
+ RIDDLE_PROOF_BASIC_GAMEPLAY_VERSION: () => RIDDLE_PROOF_BASIC_GAMEPLAY_VERSION,
2778
2783
  RIDDLE_PROOF_CAPTURE_DIAGNOSTIC_VERSION: () => RIDDLE_PROOF_CAPTURE_DIAGNOSTIC_VERSION,
2779
2784
  RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION: () => RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
2780
2785
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: () => RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
@@ -2784,11 +2789,14 @@ __export(index_exports, {
2784
2789
  RIDDLE_PROOF_RUN_STATE_VERSION: () => RIDDLE_PROOF_RUN_STATE_VERSION,
2785
2790
  RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION: () => RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION,
2786
2791
  RIDDLE_PROOF_VISUAL_SESSION_VERSION: () => RIDDLE_PROOF_VISUAL_SESSION_VERSION,
2792
+ RiddleApiError: () => RiddleApiError,
2787
2793
  appendCaptureDiagnostic: () => appendCaptureDiagnostic,
2788
2794
  appendRunEvent: () => appendRunEvent,
2789
2795
  appendStageHeartbeat: () => appendStageHeartbeat,
2790
2796
  applyPrLifecycleState: () => applyPrLifecycleState,
2791
2797
  applyTerminalMetadata: () => applyTerminalMetadata,
2798
+ assessBasicGameplayEvidence: () => assessBasicGameplayEvidence,
2799
+ assessBasicGameplayRoute: () => assessBasicGameplayRoute,
2792
2800
  assessPlayabilityEvidence: () => assessPlayabilityEvidence,
2793
2801
  authorPacketPayloadFromCheckpointResponse: () => authorPacketPayloadFromCheckpointResponse,
2794
2802
  buildAuthorCheckpointPacket: () => buildAuthorCheckpointPacket,
@@ -2807,14 +2815,18 @@ __export(index_exports, {
2807
2815
  createDisabledRiddleProofAgentAdapter: () => createDisabledRiddleProofAgentAdapter,
2808
2816
  createLocalAgentAdapter: () => createCodexExecAgentAdapter,
2809
2817
  createLocalAgentJsonRunner: () => createCodexExecJsonRunner,
2818
+ createRiddleApiClient: () => createRiddleApiClient,
2810
2819
  createRiddleProofRunCard: () => createRiddleProofRunCard,
2811
2820
  createRunResult: () => createRunResult,
2812
2821
  createRunState: () => createRunState,
2813
2822
  createRunStatusSnapshot: () => createRunStatusSnapshot,
2823
+ deployRiddleStaticPreview: () => deployRiddleStaticPreview,
2824
+ extractBasicGameplayEvidence: () => extractBasicGameplayEvidence,
2814
2825
  extractPlayabilityEvidence: () => extractPlayabilityEvidence,
2815
2826
  isDuplicateCheckpointResponse: () => isDuplicateCheckpointResponse,
2816
2827
  isRiddleProofPlayabilityMode: () => isRiddleProofPlayabilityMode,
2817
2828
  isSuccessfulStatus: () => isSuccessfulStatus,
2829
+ isTerminalRiddleJobStatus: () => isTerminalRiddleJobStatus,
2818
2830
  isTerminalStatus: () => isTerminalStatus,
2819
2831
  nonEmptyString: () => nonEmptyString,
2820
2832
  normalizeCheckpointResponse: () => normalizeCheckpointResponse,
@@ -2822,15 +2834,20 @@ __export(index_exports, {
2822
2834
  normalizePrLifecycleState: () => normalizePrLifecycleState,
2823
2835
  normalizeRunParams: () => normalizeRunParams,
2824
2836
  normalizeTerminalMetadata: () => normalizeTerminalMetadata,
2837
+ parseRiddleViewport: () => parseRiddleViewport,
2825
2838
  parseVisualProofSession: () => parseVisualProofSession,
2839
+ pollRiddleJob: () => pollRiddleJob,
2826
2840
  proofContractFromAuthorCheckpointResponse: () => proofContractFromAuthorCheckpointResponse,
2827
2841
  readRiddleProofRunStatus: () => readRiddleProofRunStatus,
2828
2842
  recordValue: () => recordValue,
2829
2843
  redactForProofDiagnostics: () => redactForProofDiagnostics,
2844
+ resolveRiddleApiKey: () => resolveRiddleApiKey,
2845
+ riddleRequestJson: () => riddleRequestJson,
2830
2846
  runCodexExecAgentDoctor: () => runCodexExecAgentDoctor,
2831
2847
  runLocalAgentDoctor: () => runCodexExecAgentDoctor,
2832
2848
  runRiddleProof: () => runRiddleProof,
2833
2849
  runRiddleProofEngineHarness: () => runRiddleProofEngineHarness,
2850
+ runRiddleScript: () => runRiddleScript,
2834
2851
  setRunStatus: () => setRunStatus,
2835
2852
  statePathsForRunState: () => statePathsForRunState,
2836
2853
  summarizeCaptureArtifacts: () => summarizeCaptureArtifacts,
@@ -3495,8 +3512,8 @@ function buildProofAssessmentCheckpointPacket(input) {
3495
3512
  const artifactContract = recordValue(proofAssessmentRequest.artifact_contract) || recordValue(bundle?.artifact_contract);
3496
3513
  const requiredSignals = recordValue(recordValue(artifactContract)?.required);
3497
3514
  const visualDelta = visualDeltaFromState(fullState);
3498
- const verificationMode = nonEmptyString(input.request.verification_mode) || nonEmptyString(fullState.verification_mode) || nonEmptyString(bundle?.verification_mode) || "proof";
3499
- const visualDeltaRequired = requiredSignals?.visual_delta === true || verificationModeRequiresVisualDelta(verificationMode);
3515
+ const verificationMode = nonEmptyString(bundle?.verification_mode) || nonEmptyString(fullState.verification_mode) || nonEmptyString(input.request.verification_mode) || "proof";
3516
+ const visualDeltaRequired = requiredSignals?.visual_delta !== false && (requiredSignals?.visual_delta === true || verificationModeRequiresVisualDelta(verificationMode));
3500
3517
  const evidenceIssueCode2 = visualDeltaIssueCode(visualDelta, visualDeltaRequired);
3501
3518
  const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.verify_summary) || "Verify captured evidence and needs a supervising proof assessment.";
3502
3519
  const recoveryHint = evidenceIssueCode2 ? "Required visual_delta evidence is incomplete. Keep this same run in verify/evidence recovery with decision=revise_capture and continue_with_stage=verify unless the evidence proves an implementation or recon problem." : "Assess whether the current artifacts prove the requested change, then choose the next stage.";
@@ -4073,6 +4090,7 @@ function normalizeRunParams(input) {
4073
4090
  leave_draft: input.leave_draft,
4074
4091
  engine_state_path: input.engine_state_path,
4075
4092
  harness_state_path: input.harness_state_path,
4093
+ riddle_engine_module_url: input.riddle_engine_module_url,
4076
4094
  max_iterations: input.max_iterations,
4077
4095
  auto_approve: input.auto_approve,
4078
4096
  dry_run: input.dry_run,
@@ -7597,11 +7615,385 @@ function parseJson(value) {
7597
7615
  return null;
7598
7616
  }
7599
7617
  }
7618
+
7619
+ // src/basic-gameplay.ts
7620
+ var RIDDLE_PROOF_BASIC_GAMEPLAY_VERSION = "riddle-proof.basic-gameplay.v1";
7621
+ var RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION = "riddle-proof.basic-gameplay.assessment.v1";
7622
+ var BASIC_GAMEPLAY_CONTAINER_KEYS = [
7623
+ "basic_gameplay",
7624
+ "basicGameplay",
7625
+ "basic_gameplay_evidence",
7626
+ "basicGameplayEvidence",
7627
+ "gameplay_proof",
7628
+ "gameplayProof"
7629
+ ];
7630
+ function assessBasicGameplayEvidence(evidence, options = {}) {
7631
+ const run = extractBasicGameplayEvidence(evidence);
7632
+ if (!run) {
7633
+ return {
7634
+ version: RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION,
7635
+ evidence_present: false,
7636
+ passed: false,
7637
+ checked_routes: 0,
7638
+ passing_routes: 0,
7639
+ failing_routes: [],
7640
+ failure_counts: {},
7641
+ warning_counts: {},
7642
+ route_results: []
7643
+ };
7644
+ }
7645
+ const routeResults = (run.results || []).map((route) => assessBasicGameplayRoute(route, options));
7646
+ const failingRoutes = routeResults.filter((result) => !result.ok).map((result) => ({
7647
+ name: result.name,
7648
+ path: result.path,
7649
+ failures: result.failures,
7650
+ warnings: result.warnings
7651
+ }));
7652
+ return {
7653
+ version: RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION,
7654
+ evidence_present: true,
7655
+ passed: failingRoutes.length === 0,
7656
+ checked_routes: routeResults.length,
7657
+ passing_routes: routeResults.filter((result) => result.ok).length,
7658
+ failing_routes: failingRoutes,
7659
+ failure_counts: countCodes(routeResults.flatMap((result) => result.failures)),
7660
+ warning_counts: countCodes(routeResults.flatMap((result) => result.warnings)),
7661
+ route_results: routeResults
7662
+ };
7663
+ }
7664
+ function assessBasicGameplayRoute(route, options = {}) {
7665
+ const maxMobileOverflowPx = options.maxMobileOverflowPx ?? 4;
7666
+ const minBodyTextLength = options.minBodyTextLength ?? 20;
7667
+ const minVisibleLargeNodes = options.minVisibleLargeNodes ?? 3;
7668
+ const minSurfaceLargeNodes = options.minSurfaceLargeNodes ?? 8;
7669
+ const warnOnMissingResetPath = options.warnOnMissingResetPath ?? true;
7670
+ const warnOnConsoleError = options.warnOnConsoleError ?? true;
7671
+ const failOnConsoleError = options.failOnConsoleError ?? false;
7672
+ const failures = [];
7673
+ const warnings = [];
7674
+ const initial = route.initial || {};
7675
+ const timed = route.timed || {};
7676
+ const afterAction = route.after_action || route.afterAction || {};
7677
+ const mobile = route.mobile || {};
7678
+ const timedChange = changed(initial, timed);
7679
+ const actionChange = changed(timed, afterAction);
7680
+ const surfaceVisible = numberValue2(initial.visible_canvas_count) > 0 || numberValue2(initial.enabled_clickable_count) > 0 || numberValue2(initial.visible_large_node_count) >= minSurfaceLargeNodes;
7681
+ const actionResults = listValue2(route.action_results || route.actionResults);
7682
+ const actionAttempted = actionResults.some((result) => result.ok === true && result.action !== "wait");
7683
+ const actionFailed = actionResults.some((result) => result.ok === false && result.action !== "wait");
7684
+ const stateChangeObserved = actionChange.changed || timedChange.changed;
7685
+ const resetPathPresent = numberValue2(initial.reset_control_count) > 0 || numberValue2(timed.reset_control_count) > 0 || numberValue2(afterAction.reset_control_count) > 0;
7686
+ const responseStatus = firstNumber(route.http_status, route.response_status, route.status);
7687
+ const pageErrorCount = numberValue2(route.page_error_count);
7688
+ const consoleErrorCount = numberValue2(route.console_error_count);
7689
+ const mobileOverflowPx = numberValue2(mobile.overflow_px);
7690
+ if (responseStatus !== null && responseStatus >= 400) failures.push("route_http_error");
7691
+ if (pageErrorCount > 0) failures.push("fatal_page_error");
7692
+ if (numberValue2(initial.body_text_length) < minBodyTextLength && numberValue2(initial.visible_large_node_count) < minVisibleLargeNodes) {
7693
+ failures.push("route_blank_or_thin");
7694
+ }
7695
+ if (!surfaceVisible) failures.push("no_game_surface");
7696
+ if (mobileOverflowPx > maxMobileOverflowPx) failures.push("mobile_horizontal_overflow");
7697
+ if (!actionAttempted && !timedChange.changed) failures.push("primary_control_missing");
7698
+ if (actionAttempted && !stateChangeObserved) failures.push("primary_control_inert");
7699
+ if (failOnConsoleError && consoleErrorCount > 0) failures.push("fatal_page_error");
7700
+ if (numberValue2(initial.visible_canvas_count) > 0 && actionAttempted && !timedChange.canvas_changed && !actionChange.canvas_changed && !actionChange.screenshot_changed) {
7701
+ warnings.push("canvas_inert");
7702
+ }
7703
+ if (actionFailed) warnings.push("some_actions_failed");
7704
+ if (warnOnMissingResetPath && !resetPathPresent && route.requires_reset !== false && actionAttempted && stateChangeObserved) {
7705
+ warnings.push("missing_reset_path");
7706
+ }
7707
+ if (warnOnConsoleError && consoleErrorCount > 0) warnings.push("critical_console_error");
7708
+ return {
7709
+ name: route.name,
7710
+ path: route.path,
7711
+ ok: failures.length === 0,
7712
+ failures,
7713
+ warnings,
7714
+ signals: {
7715
+ route_loaded: !failures.includes("route_http_error") && !failures.includes("route_blank_or_thin"),
7716
+ surface_visible: surfaceVisible,
7717
+ action_attempted: actionAttempted,
7718
+ timed_progression_observed: timedChange.changed,
7719
+ first_interaction_observed: actionChange.changed,
7720
+ state_change_observed: stateChangeObserved,
7721
+ mobile_overflow_absent: mobileOverflowPx <= maxMobileOverflowPx,
7722
+ reset_path_present: resetPathPresent,
7723
+ fatal_errors_absent: pageErrorCount === 0
7724
+ },
7725
+ diffs: {
7726
+ timed: timedChange,
7727
+ after_action: actionChange
7728
+ }
7729
+ };
7730
+ }
7731
+ function extractBasicGameplayEvidence(...sources) {
7732
+ const seen = /* @__PURE__ */ new Set();
7733
+ for (const source of sources) {
7734
+ const found = findBasicGameplayEvidence(source, seen);
7735
+ if (found) return found;
7736
+ }
7737
+ return null;
7738
+ }
7739
+ function findBasicGameplayEvidence(value, seen, depth = 0) {
7740
+ if (depth > 6 || value === null || value === void 0) return null;
7741
+ if (typeof value === "string") {
7742
+ const parsed = parseJson2(value);
7743
+ return parsed === null ? null : findBasicGameplayEvidence(parsed, seen, depth + 1);
7744
+ }
7745
+ if (Array.isArray(value)) {
7746
+ if (seen.has(value)) return null;
7747
+ seen.add(value);
7748
+ if (value.some((item) => hasRouteShape(recordValue3(item)))) {
7749
+ return { results: value.filter((item) => hasRouteShape(recordValue3(item))) };
7750
+ }
7751
+ for (const item of value) {
7752
+ const found = findBasicGameplayEvidence(item, seen, depth + 1);
7753
+ if (found) return found;
7754
+ }
7755
+ return null;
7756
+ }
7757
+ const record = recordValue3(value);
7758
+ if (!record || seen.has(record)) return null;
7759
+ seen.add(record);
7760
+ if (record.version === RIDDLE_PROOF_BASIC_GAMEPLAY_VERSION || Array.isArray(record.results)) {
7761
+ return {
7762
+ ...record,
7763
+ results: listValue2(record.results).filter((item) => Boolean(recordValue3(item)))
7764
+ };
7765
+ }
7766
+ if (hasRouteShape(record)) {
7767
+ return { results: [record] };
7768
+ }
7769
+ for (const key of BASIC_GAMEPLAY_CONTAINER_KEYS) {
7770
+ if (Object.prototype.hasOwnProperty.call(record, key)) {
7771
+ const nested = findBasicGameplayEvidence(record[key], seen, depth + 1);
7772
+ if (nested) return nested;
7773
+ }
7774
+ }
7775
+ for (const item of Object.values(record)) {
7776
+ const found = findBasicGameplayEvidence(item, seen, depth + 1);
7777
+ if (found) return found;
7778
+ }
7779
+ return null;
7780
+ }
7781
+ function hasRouteShape(record) {
7782
+ return Boolean(record && (record.initial || record.after_action || record.afterAction || record.action_results || record.actionResults) && (record.path || record.name));
7783
+ }
7784
+ function changed(before, after) {
7785
+ const bodyTextChanged = Boolean(before.body_text_hash && after.body_text_hash && before.body_text_hash !== after.body_text_hash);
7786
+ const screenshotChanged = Boolean(before.screenshot_hash && after.screenshot_hash && before.screenshot_hash !== after.screenshot_hash);
7787
+ const beforeCanvasHashes = canvasHashes(before.canvases);
7788
+ const afterCanvasHashes = canvasHashes(after.canvases);
7789
+ const canvasChanged = Boolean(beforeCanvasHashes && afterCanvasHashes && beforeCanvasHashes !== afterCanvasHashes);
7790
+ return {
7791
+ body_text_changed: bodyTextChanged,
7792
+ screenshot_changed: screenshotChanged,
7793
+ canvas_changed: canvasChanged,
7794
+ changed: bodyTextChanged || screenshotChanged || canvasChanged
7795
+ };
7796
+ }
7797
+ function canvasHashes(canvases) {
7798
+ return (canvases || []).map((canvas) => canvas.hash).filter(Boolean).join("|");
7799
+ }
7800
+ function countCodes(codes) {
7801
+ const counts = {};
7802
+ for (const code of codes) counts[code] = (counts[code] || 0) + 1;
7803
+ return counts;
7804
+ }
7805
+ function firstNumber(...values) {
7806
+ for (const value of values) {
7807
+ const number = numericValue3(value);
7808
+ if (number !== null) return number;
7809
+ }
7810
+ return null;
7811
+ }
7812
+ function numberValue2(value) {
7813
+ return numericValue3(value) ?? 0;
7814
+ }
7815
+ function numericValue3(value) {
7816
+ if (typeof value === "number" && Number.isFinite(value)) return value;
7817
+ if (typeof value === "string" && value.trim()) {
7818
+ const parsed = Number(value);
7819
+ return Number.isFinite(parsed) ? parsed : null;
7820
+ }
7821
+ return null;
7822
+ }
7823
+ function recordValue3(value) {
7824
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
7825
+ }
7826
+ function listValue2(value) {
7827
+ return Array.isArray(value) ? value : [];
7828
+ }
7829
+ function parseJson2(value) {
7830
+ const trimmed = value.trim();
7831
+ if (!trimmed || !/^[{[]/.test(trimmed)) return null;
7832
+ try {
7833
+ return JSON.parse(trimmed);
7834
+ } catch {
7835
+ return null;
7836
+ }
7837
+ }
7838
+
7839
+ // src/riddle-client.ts
7840
+ var import_node_child_process4 = require("child_process");
7841
+ var import_node_fs5 = require("fs");
7842
+ var import_node_os2 = require("os");
7843
+ var import_node_path5 = __toESM(require("path"), 1);
7844
+ var DEFAULT_RIDDLE_API_BASE_URL = "https://api.riddledc.com";
7845
+ var DEFAULT_RIDDLE_API_KEY_FILE = "/tmp/riddle-api-key";
7846
+ var RiddleApiError = class extends Error {
7847
+ constructor(pathname, status, body) {
7848
+ super(`Riddle API ${pathname} failed HTTP ${status}: ${body}`);
7849
+ this.name = "RiddleApiError";
7850
+ this.status = status;
7851
+ this.body = body;
7852
+ this.path = pathname;
7853
+ }
7854
+ };
7855
+ function normalizeBaseUrl(value) {
7856
+ return (value || DEFAULT_RIDDLE_API_BASE_URL).replace(/\/$/, "");
7857
+ }
7858
+ function fetchFor(config = {}) {
7859
+ return config.fetchImpl || fetch;
7860
+ }
7861
+ function resolveRiddleApiKey(config = {}) {
7862
+ if (config.apiKey?.trim()) return config.apiKey.trim();
7863
+ if (process.env.RIDDLE_API_KEY?.trim()) return process.env.RIDDLE_API_KEY.trim();
7864
+ const keyFile = config.apiKeyFile || process.env.RIDDLE_API_KEY_FILE || DEFAULT_RIDDLE_API_KEY_FILE;
7865
+ if ((0, import_node_fs5.existsSync)(keyFile)) {
7866
+ const key = (0, import_node_fs5.readFileSync)(keyFile, "utf8").trim();
7867
+ if (key) return key;
7868
+ }
7869
+ throw new Error(`Riddle API key missing. Set RIDDLE_API_KEY or write ${DEFAULT_RIDDLE_API_KEY_FILE}.`);
7870
+ }
7871
+ async function riddleRequestJson(config, pathname, init = {}) {
7872
+ const response = await fetchFor(config)(`${normalizeBaseUrl(config.apiBaseUrl)}${pathname}`, {
7873
+ ...init,
7874
+ headers: {
7875
+ Authorization: `Bearer ${resolveRiddleApiKey(config)}`,
7876
+ "Content-Type": "application/json",
7877
+ ...init.headers || {}
7878
+ }
7879
+ });
7880
+ const text = await response.text();
7881
+ let json = null;
7882
+ try {
7883
+ json = JSON.parse(text);
7884
+ } catch {
7885
+ }
7886
+ if (!response.ok) throw new RiddleApiError(pathname, response.status, text);
7887
+ return json ?? text;
7888
+ }
7889
+ async function deployRiddleStaticPreview(config, directory, label) {
7890
+ if (!directory?.trim()) throw new Error("directory is required");
7891
+ if (!label?.trim()) throw new Error("label is required");
7892
+ const created = await riddleRequestJson(config, "/v1/preview", {
7893
+ method: "POST",
7894
+ body: JSON.stringify({ framework: "spa", label })
7895
+ });
7896
+ const id = String(created.id || "");
7897
+ const uploadUrl = String(created.upload_url || "");
7898
+ if (!id || !uploadUrl) throw new Error("Riddle preview create response was missing id or upload_url.");
7899
+ const scratch = (0, import_node_fs5.mkdtempSync)(import_node_path5.default.join((0, import_node_os2.tmpdir)(), "riddle-preview-upload-"));
7900
+ const tarball = import_node_path5.default.join(scratch, `${id}.tar.gz`);
7901
+ try {
7902
+ (0, import_node_child_process4.execFileSync)("tar", ["czf", tarball, "-C", directory, "."], { stdio: "pipe" });
7903
+ const upload = await fetchFor(config)(uploadUrl, {
7904
+ method: "PUT",
7905
+ headers: { "Content-Type": "application/gzip" },
7906
+ body: (0, import_node_fs5.readFileSync)(tarball)
7907
+ });
7908
+ if (!upload.ok) {
7909
+ throw new RiddleApiError(uploadUrl, upload.status, await upload.text());
7910
+ }
7911
+ } finally {
7912
+ (0, import_node_fs5.rmSync)(scratch, { recursive: true, force: true });
7913
+ }
7914
+ const published = await riddleRequestJson(config, `/v1/preview/${id}/publish`, {
7915
+ method: "POST"
7916
+ });
7917
+ return {
7918
+ ok: true,
7919
+ id: String(published.id || id),
7920
+ label,
7921
+ preview_url: String(published.preview_url || ""),
7922
+ file_count: typeof published.file_count === "number" ? published.file_count : void 0,
7923
+ total_bytes: typeof published.total_bytes === "number" ? published.total_bytes : void 0,
7924
+ expires_at: typeof created.expires_at === "string" ? created.expires_at : void 0,
7925
+ raw: published
7926
+ };
7927
+ }
7928
+ function parseRiddleViewport(value) {
7929
+ if (!value) return void 0;
7930
+ const match = /^(\d+)x(\d+)$/.exec(value.trim());
7931
+ if (!match) throw new Error("viewport must look like 1280x720");
7932
+ return { width: Number(match[1]), height: Number(match[2]) };
7933
+ }
7934
+ async function runRiddleScript(config, input) {
7935
+ if (!input.url?.trim()) throw new Error("url is required");
7936
+ if (!input.script?.trim()) throw new Error("script is required");
7937
+ const payload = {
7938
+ url: input.url,
7939
+ script: input.script,
7940
+ sync: input.sync ?? false,
7941
+ timeout_sec: input.timeoutSec || 120
7942
+ };
7943
+ if (input.viewport) payload.viewport = input.viewport;
7944
+ if (input.include) payload.include = input.include;
7945
+ if (input.options) payload.options = input.options;
7946
+ return riddleRequestJson(config, "/v1/run", {
7947
+ method: "POST",
7948
+ body: JSON.stringify(payload)
7949
+ });
7950
+ }
7951
+ function isTerminalRiddleJobStatus(status) {
7952
+ return ["completed", "complete", "completed_error", "completed_timeout", "failed"].includes(String(status || ""));
7953
+ }
7954
+ async function pollRiddleJob(config, jobId, options = {}) {
7955
+ if (!jobId?.trim()) throw new Error("jobId is required");
7956
+ const attempts = options.attempts || (options.wait ? 60 : 1);
7957
+ const intervalMs = options.intervalMs || 2e3;
7958
+ let job = null;
7959
+ for (let index = 0; index < attempts; index += 1) {
7960
+ job = await riddleRequestJson(config, `/v1/jobs/${jobId}`);
7961
+ if (isTerminalRiddleJobStatus(job.status)) break;
7962
+ if (index + 1 < attempts) {
7963
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
7964
+ }
7965
+ }
7966
+ const status = job?.status ? String(job.status) : null;
7967
+ if (!isTerminalRiddleJobStatus(status)) {
7968
+ return { ok: true, job_id: jobId, status, terminal: false, job };
7969
+ }
7970
+ const artifacts = await riddleRequestJson(config, `/v1/jobs/${jobId}/artifacts`);
7971
+ return {
7972
+ ok: status === "completed" || status === "complete",
7973
+ job_id: jobId,
7974
+ status,
7975
+ terminal: true,
7976
+ job,
7977
+ artifacts
7978
+ };
7979
+ }
7980
+ function createRiddleApiClient(config = {}) {
7981
+ return {
7982
+ requestJson: (pathname, init) => riddleRequestJson(config, pathname, init),
7983
+ deployStaticPreview: (directory, label) => deployRiddleStaticPreview(config, directory, label),
7984
+ runScript: (input) => runRiddleScript(config, input),
7985
+ pollJob: (jobId, options) => pollRiddleJob(config, jobId, options)
7986
+ };
7987
+ }
7600
7988
  // Annotate the CommonJS export names for ESM import in node:
7601
7989
  0 && (module.exports = {
7602
7990
  DEFAULT_DIAGNOSTIC_ARRAY_LIMIT,
7603
7991
  DEFAULT_DIAGNOSTIC_HISTORY_LIMIT,
7604
7992
  DEFAULT_DIAGNOSTIC_STRING_LIMIT,
7993
+ DEFAULT_RIDDLE_API_BASE_URL,
7994
+ DEFAULT_RIDDLE_API_KEY_FILE,
7995
+ RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION,
7996
+ RIDDLE_PROOF_BASIC_GAMEPLAY_VERSION,
7605
7997
  RIDDLE_PROOF_CAPTURE_DIAGNOSTIC_VERSION,
7606
7998
  RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
7607
7999
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
@@ -7611,11 +8003,14 @@ function parseJson(value) {
7611
8003
  RIDDLE_PROOF_RUN_STATE_VERSION,
7612
8004
  RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION,
7613
8005
  RIDDLE_PROOF_VISUAL_SESSION_VERSION,
8006
+ RiddleApiError,
7614
8007
  appendCaptureDiagnostic,
7615
8008
  appendRunEvent,
7616
8009
  appendStageHeartbeat,
7617
8010
  applyPrLifecycleState,
7618
8011
  applyTerminalMetadata,
8012
+ assessBasicGameplayEvidence,
8013
+ assessBasicGameplayRoute,
7619
8014
  assessPlayabilityEvidence,
7620
8015
  authorPacketPayloadFromCheckpointResponse,
7621
8016
  buildAuthorCheckpointPacket,
@@ -7634,14 +8029,18 @@ function parseJson(value) {
7634
8029
  createDisabledRiddleProofAgentAdapter,
7635
8030
  createLocalAgentAdapter,
7636
8031
  createLocalAgentJsonRunner,
8032
+ createRiddleApiClient,
7637
8033
  createRiddleProofRunCard,
7638
8034
  createRunResult,
7639
8035
  createRunState,
7640
8036
  createRunStatusSnapshot,
8037
+ deployRiddleStaticPreview,
8038
+ extractBasicGameplayEvidence,
7641
8039
  extractPlayabilityEvidence,
7642
8040
  isDuplicateCheckpointResponse,
7643
8041
  isRiddleProofPlayabilityMode,
7644
8042
  isSuccessfulStatus,
8043
+ isTerminalRiddleJobStatus,
7645
8044
  isTerminalStatus,
7646
8045
  nonEmptyString,
7647
8046
  normalizeCheckpointResponse,
@@ -7649,15 +8048,20 @@ function parseJson(value) {
7649
8048
  normalizePrLifecycleState,
7650
8049
  normalizeRunParams,
7651
8050
  normalizeTerminalMetadata,
8051
+ parseRiddleViewport,
7652
8052
  parseVisualProofSession,
8053
+ pollRiddleJob,
7653
8054
  proofContractFromAuthorCheckpointResponse,
7654
8055
  readRiddleProofRunStatus,
7655
8056
  recordValue,
7656
8057
  redactForProofDiagnostics,
8058
+ resolveRiddleApiKey,
8059
+ riddleRequestJson,
7657
8060
  runCodexExecAgentDoctor,
7658
8061
  runLocalAgentDoctor,
7659
8062
  runRiddleProof,
7660
8063
  runRiddleProofEngineHarness,
8064
+ runRiddleScript,
7661
8065
  setRunStatus,
7662
8066
  statePathsForRunState,
7663
8067
  summarizeCaptureArtifacts,
package/dist/index.d.cts CHANGED
@@ -9,3 +9,5 @@ export { CodexExecAgentConfig, CodexJsonRequest, CodexJsonResult, CodexJsonRunne
9
9
  export { CreateCaptureDiagnosticInput, DEFAULT_DIAGNOSTIC_ARRAY_LIMIT, DEFAULT_DIAGNOSTIC_HISTORY_LIMIT, DEFAULT_DIAGNOSTIC_STRING_LIMIT, RIDDLE_PROOF_CAPTURE_DIAGNOSTIC_VERSION, RiddleProofArtifactSummary, RiddleProofCaptureArtifactSummary, RiddleProofCaptureDiagnostic, RiddleProofDiagnosticRedactionOptions, appendCaptureDiagnostic, createCaptureDiagnostic, redactForProofDiagnostics, summarizeCaptureArtifacts } from './diagnostics.cjs';
10
10
  export { BuildVisualProofSessionInput, RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION, RIDDLE_PROOF_VISUAL_SESSION_VERSION, VisualProofSessionMismatch, buildVisualProofSession, compareVisualProofSessionFingerprint, parseVisualProofSession, visualSessionFingerprint, visualSessionFingerprintBasis } from './proof-session.cjs';
11
11
  export { AssessPlayabilityOptions, RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION, RIDDLE_PROOF_PLAYABILITY_VERSION, RiddleProofPlayabilityAssessment, RiddleProofPlayabilityEvidence, assessPlayabilityEvidence, extractPlayabilityEvidence, isRiddleProofPlayabilityMode } from './playability.cjs';
12
+ export { AssessBasicGameplayOptions, BasicGameplayActionResult, BasicGameplayCanvasState, BasicGameplayChangeSummary, BasicGameplayFailureCode, BasicGameplayMobileEvidence, BasicGameplaySnapshot, BasicGameplayWarningCode, RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION, RIDDLE_PROOF_BASIC_GAMEPLAY_VERSION, RiddleProofBasicGameplayAssessment, RiddleProofBasicGameplayEvidence, RiddleProofBasicGameplayRouteAssessment, RiddleProofBasicGameplayRouteEvidence, assessBasicGameplayEvidence, assessBasicGameplayRoute, extractBasicGameplayEvidence } from './basic-gameplay.cjs';
13
+ export { DEFAULT_RIDDLE_API_BASE_URL, DEFAULT_RIDDLE_API_KEY_FILE, RiddleApiError, RiddleClientConfig, RiddleFetch, RiddlePollJobResult, RiddlePreviewDeployResult, RiddleRunScriptInput, createRiddleApiClient, deployRiddleStaticPreview, isTerminalRiddleJobStatus, parseRiddleViewport, pollRiddleJob, resolveRiddleApiKey, riddleRequestJson, runRiddleScript } from './riddle-client.cjs';
package/dist/index.d.ts CHANGED
@@ -9,3 +9,5 @@ export { CodexExecAgentConfig, CodexJsonRequest, CodexJsonResult, CodexJsonRunne
9
9
  export { CreateCaptureDiagnosticInput, DEFAULT_DIAGNOSTIC_ARRAY_LIMIT, DEFAULT_DIAGNOSTIC_HISTORY_LIMIT, DEFAULT_DIAGNOSTIC_STRING_LIMIT, RIDDLE_PROOF_CAPTURE_DIAGNOSTIC_VERSION, RiddleProofArtifactSummary, RiddleProofCaptureArtifactSummary, RiddleProofCaptureDiagnostic, RiddleProofDiagnosticRedactionOptions, appendCaptureDiagnostic, createCaptureDiagnostic, redactForProofDiagnostics, summarizeCaptureArtifacts } from './diagnostics.js';
10
10
  export { BuildVisualProofSessionInput, RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION, RIDDLE_PROOF_VISUAL_SESSION_VERSION, VisualProofSessionMismatch, buildVisualProofSession, compareVisualProofSessionFingerprint, parseVisualProofSession, visualSessionFingerprint, visualSessionFingerprintBasis } from './proof-session.js';
11
11
  export { AssessPlayabilityOptions, RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION, RIDDLE_PROOF_PLAYABILITY_VERSION, RiddleProofPlayabilityAssessment, RiddleProofPlayabilityEvidence, assessPlayabilityEvidence, extractPlayabilityEvidence, isRiddleProofPlayabilityMode } from './playability.js';
12
+ export { AssessBasicGameplayOptions, BasicGameplayActionResult, BasicGameplayCanvasState, BasicGameplayChangeSummary, BasicGameplayFailureCode, BasicGameplayMobileEvidence, BasicGameplaySnapshot, BasicGameplayWarningCode, RIDDLE_PROOF_BASIC_GAMEPLAY_ASSESSMENT_VERSION, RIDDLE_PROOF_BASIC_GAMEPLAY_VERSION, RiddleProofBasicGameplayAssessment, RiddleProofBasicGameplayEvidence, RiddleProofBasicGameplayRouteAssessment, RiddleProofBasicGameplayRouteEvidence, assessBasicGameplayEvidence, assessBasicGameplayRoute, extractBasicGameplayEvidence } from './basic-gameplay.js';
13
+ export { DEFAULT_RIDDLE_API_BASE_URL, DEFAULT_RIDDLE_API_KEY_FILE, RiddleApiError, RiddleClientConfig, RiddleFetch, RiddlePollJobResult, RiddlePreviewDeployResult, RiddleRunScriptInput, createRiddleApiClient, deployRiddleStaticPreview, isTerminalRiddleJobStatus, parseRiddleViewport, pollRiddleJob, resolveRiddleApiKey, riddleRequestJson, runRiddleScript } from './riddle-client.js';