zk-credits 0.2.4 → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -23
- package/dist/base-registered-trial.d.ts +6 -2
- package/dist/base-registered-trial.js +18 -2
- package/dist/base-sidecar.d.ts +2 -0
- package/dist/base-sidecar.js +13 -1
- package/dist/cli.js +152 -40
- package/dist/codex-profile.js +2 -1
- package/dist/gateway-trial-status.d.ts +13 -0
- package/dist/gateway-trial-status.js +70 -0
- package/dist/local-x402-agent.d.ts +34 -0
- package/dist/local-x402-agent.js +130 -0
- package/dist/responses-bridge.js +20 -3
- package/dist/sidecar.d.ts +2 -0
- package/dist/sidecar.js +8 -0
- package/dist/zk-credits.js +647 -356
- package/package.json +5 -1
package/dist/zk-credits.js
CHANGED
|
@@ -34651,7 +34651,7 @@ var require_lib = __commonJS({
|
|
|
34651
34651
|
};
|
|
34652
34652
|
}
|
|
34653
34653
|
// @__NO_SIDE_EFFECTS__
|
|
34654
|
-
function
|
|
34654
|
+
function join9(separator = "") {
|
|
34655
34655
|
astr("join", separator);
|
|
34656
34656
|
return {
|
|
34657
34657
|
encode: (from) => {
|
|
@@ -34867,15 +34867,15 @@ var require_lib = __commonJS({
|
|
|
34867
34867
|
convertRadix2,
|
|
34868
34868
|
radix,
|
|
34869
34869
|
radix2,
|
|
34870
|
-
join:
|
|
34870
|
+
join: join9,
|
|
34871
34871
|
padding
|
|
34872
34872
|
};
|
|
34873
|
-
exports.base16 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789ABCDEF"), /* @__PURE__ */
|
|
34874
|
-
exports.base32 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */ padding(5), /* @__PURE__ */
|
|
34875
|
-
exports.base32nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */
|
|
34876
|
-
exports.base32hex = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */ padding(5), /* @__PURE__ */
|
|
34877
|
-
exports.base32hexnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */
|
|
34878
|
-
exports.base32crockford = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), /* @__PURE__ */
|
|
34873
|
+
exports.base16 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789ABCDEF"), /* @__PURE__ */ join9(""));
|
|
34874
|
+
exports.base32 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */ padding(5), /* @__PURE__ */ join9(""));
|
|
34875
|
+
exports.base32nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */ join9(""));
|
|
34876
|
+
exports.base32hex = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */ padding(5), /* @__PURE__ */ join9(""));
|
|
34877
|
+
exports.base32hexnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */ join9(""));
|
|
34878
|
+
exports.base32crockford = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), /* @__PURE__ */ join9(""), /* @__PURE__ */ normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
|
|
34879
34879
|
var hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")();
|
|
34880
34880
|
var decodeBase64Builtin = (s, isUrl) => {
|
|
34881
34881
|
astr("base64", s);
|
|
@@ -34893,8 +34893,8 @@ var require_lib = __commonJS({
|
|
|
34893
34893
|
decode(s) {
|
|
34894
34894
|
return decodeBase64Builtin(s, false);
|
|
34895
34895
|
}
|
|
34896
|
-
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */ padding(6), /* @__PURE__ */
|
|
34897
|
-
exports.base64nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */
|
|
34896
|
+
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */ padding(6), /* @__PURE__ */ join9(""));
|
|
34897
|
+
exports.base64nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */ join9(""));
|
|
34898
34898
|
exports.base64url = hasBase64Builtin ? {
|
|
34899
34899
|
encode(b) {
|
|
34900
34900
|
abytes(b);
|
|
@@ -34903,9 +34903,9 @@ var require_lib = __commonJS({
|
|
|
34903
34903
|
decode(s) {
|
|
34904
34904
|
return decodeBase64Builtin(s, true);
|
|
34905
34905
|
}
|
|
34906
|
-
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */ padding(6), /* @__PURE__ */
|
|
34907
|
-
exports.base64urlnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */
|
|
34908
|
-
var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */
|
|
34906
|
+
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */ padding(6), /* @__PURE__ */ join9(""));
|
|
34907
|
+
exports.base64urlnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */ join9(""));
|
|
34908
|
+
var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join9(""));
|
|
34909
34909
|
exports.base58 = /* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
|
|
34910
34910
|
exports.base58flickr = /* @__PURE__ */ genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
|
|
34911
34911
|
exports.base58xrp = /* @__PURE__ */ genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
|
|
@@ -34937,7 +34937,7 @@ var require_lib = __commonJS({
|
|
|
34937
34937
|
var createBase58check = (sha256) => /* @__PURE__ */ chain(checksum(4, (data) => sha256(sha256(data))), exports.base58);
|
|
34938
34938
|
exports.createBase58check = createBase58check;
|
|
34939
34939
|
exports.base58check = exports.createBase58check;
|
|
34940
|
-
var BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */
|
|
34940
|
+
var BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */ join9(""));
|
|
34941
34941
|
var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
|
|
34942
34942
|
function bech32Polymod(pre) {
|
|
34943
34943
|
const b = pre >> 25;
|
|
@@ -35046,7 +35046,7 @@ var require_lib = __commonJS({
|
|
|
35046
35046
|
return Uint8Array.fromHex(s);
|
|
35047
35047
|
}
|
|
35048
35048
|
};
|
|
35049
|
-
exports.hex = hasHexBuiltin ? hexBuiltin : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789abcdef"), /* @__PURE__ */
|
|
35049
|
+
exports.hex = hasHexBuiltin ? hexBuiltin : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789abcdef"), /* @__PURE__ */ join9(""), /* @__PURE__ */ normalize((s) => {
|
|
35050
35050
|
if (typeof s !== "string" || s.length % 2 !== 0)
|
|
35051
35051
|
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
|
|
35052
35052
|
return s.toLowerCase();
|
|
@@ -80653,9 +80653,9 @@ var require_cjs2 = __commonJS({
|
|
|
80653
80653
|
});
|
|
80654
80654
|
|
|
80655
80655
|
// dist/cli.js
|
|
80656
|
-
import { homedir } from "node:os";
|
|
80657
|
-
import { readFile as
|
|
80658
|
-
import { join as
|
|
80656
|
+
import { homedir as homedir2 } from "node:os";
|
|
80657
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
80658
|
+
import { join as join8 } from "node:path";
|
|
80659
80659
|
import { createInterface } from "node:readline/promises";
|
|
80660
80660
|
|
|
80661
80661
|
// dist/codex-launcher.js
|
|
@@ -80687,6 +80687,7 @@ function renderCodexProfile(options) {
|
|
|
80687
80687
|
const model = options.model?.trim() || DEFAULT_CODEX_MODEL;
|
|
80688
80688
|
return [
|
|
80689
80689
|
`model = ${tomlString(model)}`,
|
|
80690
|
+
'model_reasoning_effort = "none"',
|
|
80690
80691
|
'model_provider = "zk_credits"',
|
|
80691
80692
|
"",
|
|
80692
80693
|
"[model_providers.zk_credits]",
|
|
@@ -80732,7 +80733,7 @@ function codexModelsResponse() {
|
|
|
80732
80733
|
apply_patch_tool_type: "freeform",
|
|
80733
80734
|
web_search_tool_type: "text",
|
|
80734
80735
|
truncation_policy: { mode: "tokens", limit: 1e4 },
|
|
80735
|
-
supports_parallel_tool_calls:
|
|
80736
|
+
supports_parallel_tool_calls: false,
|
|
80736
80737
|
supports_image_detail_original: false,
|
|
80737
80738
|
context_window: 128e3,
|
|
80738
80739
|
max_context_window: 128e3,
|
|
@@ -80884,6 +80885,10 @@ var TREE_DEPTH = 20;
|
|
|
80884
80885
|
var FIELD_ORDER = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
|
|
80885
80886
|
var REPLAY_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
80886
80887
|
var MAX_PENDING_PAYMENTS = 64;
|
|
80888
|
+
var PAYMENT_PROOF_FIELDS = ["pi_a", "pi_b", "pi_c"];
|
|
80889
|
+
function proofForPayment(proof) {
|
|
80890
|
+
return Object.fromEntries(PAYMENT_PROOF_FIELDS.filter((field3) => Object.prototype.hasOwnProperty.call(proof, field3)).map((field3) => [field3, proof[field3]]));
|
|
80891
|
+
}
|
|
80887
80892
|
function field(value, label) {
|
|
80888
80893
|
if (!/^\d+$/u.test(value))
|
|
80889
80894
|
throw new Error(`Invalid ${label}`);
|
|
@@ -80926,6 +80931,7 @@ function requestBodyBytes(body) {
|
|
|
80926
80931
|
}
|
|
80927
80932
|
function createBasePaymentFactory(options) {
|
|
80928
80933
|
const secret = secretFromBase64Url(options.credential.secret);
|
|
80934
|
+
let internalTrialProofAttempted = false;
|
|
80929
80935
|
return async ({ method, url, body, requirements }) => {
|
|
80930
80936
|
if (requirements.extra.deploymentDomain !== options.credential.deploymentDomain) {
|
|
80931
80937
|
throw new Error("Credential deployment domain does not match the gateway challenge");
|
|
@@ -80961,6 +80967,11 @@ function createBasePaymentFactory(options) {
|
|
|
80961
80967
|
nullifier,
|
|
80962
80968
|
share
|
|
80963
80969
|
];
|
|
80970
|
+
if (options.internalTrialOneProof) {
|
|
80971
|
+
if (internalTrialProofAttempted)
|
|
80972
|
+
throw new Error("internal_trial_limit_reached");
|
|
80973
|
+
internalTrialProofAttempted = true;
|
|
80974
|
+
}
|
|
80964
80975
|
const proof = await options.prove({
|
|
80965
80976
|
secret: secretToField(secret),
|
|
80966
80977
|
tier_id: String(options.credential.tierId),
|
|
@@ -80979,7 +80990,7 @@ function createBasePaymentFactory(options) {
|
|
|
80979
80990
|
await slotLedger.commit(selectedSlot);
|
|
80980
80991
|
const payment = buildPaymentPayload({
|
|
80981
80992
|
requirements,
|
|
80982
|
-
proof: proof.proof,
|
|
80993
|
+
proof: proofForPayment(proof.proof),
|
|
80983
80994
|
publicSignals: [...proof.publicSignals],
|
|
80984
80995
|
nonce,
|
|
80985
80996
|
responseKey: responseKeys.publicKey
|
|
@@ -81256,6 +81267,13 @@ function createFileWitnessProvider(value) {
|
|
|
81256
81267
|
};
|
|
81257
81268
|
}
|
|
81258
81269
|
|
|
81270
|
+
// dist/local-x402-agent.js
|
|
81271
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
81272
|
+
import { homedir } from "node:os";
|
|
81273
|
+
import { join as join7 } from "node:path";
|
|
81274
|
+
import { decryptAnyCredentialExport } from "@zk-credits/shared/base";
|
|
81275
|
+
import { BASE_SEPOLIA_NETWORK, createZkPrepaidLifecycleMetrics } from "@zk-credits/x402-zk-prepaid";
|
|
81276
|
+
|
|
81259
81277
|
// dist/base-event-sync.js
|
|
81260
81278
|
var import_chains = __toESM(require_chains(), 1);
|
|
81261
81279
|
var import_viem = __toESM(require_cjs2(), 1);
|
|
@@ -81873,9 +81891,6 @@ async function createPinnedBaseProofGenerator(options) {
|
|
|
81873
81891
|
};
|
|
81874
81892
|
}
|
|
81875
81893
|
|
|
81876
|
-
// dist/cli.js
|
|
81877
|
-
import { createZkPrepaidLifecycleMetrics } from "@zk-credits/x402-zk-prepaid";
|
|
81878
|
-
|
|
81879
81894
|
// dist/slot-ledger.js
|
|
81880
81895
|
import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
81881
81896
|
import { dirname as dirname3 } from "node:path";
|
|
@@ -82000,229 +82015,18 @@ var BaseSlotLedger = class _BaseSlotLedger {
|
|
|
82000
82015
|
}
|
|
82001
82016
|
};
|
|
82002
82017
|
|
|
82003
|
-
// dist/cli.js
|
|
82004
|
-
import { decryptAnyCredentialExport } from "@zk-credits/shared/base";
|
|
82005
|
-
|
|
82006
|
-
// dist/sidecar-config.js
|
|
82007
|
-
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
82008
|
-
import { join as join4 } from "node:path";
|
|
82009
|
-
function createLoopbackToken() {
|
|
82010
|
-
return randomBytes3(32).toString("base64url");
|
|
82011
|
-
}
|
|
82012
|
-
function sidecarStatePaths(stateDirectory2) {
|
|
82013
|
-
return {
|
|
82014
|
-
tokenPath: join4(stateDirectory2, "loopback-token"),
|
|
82015
|
-
logPath: join4(stateDirectory2, "sidecar.log")
|
|
82016
|
-
};
|
|
82017
|
-
}
|
|
82018
|
-
function formatOpenAiEnvironment(loopbackBaseUrl2, localToken) {
|
|
82019
|
-
const url = new URL(loopbackBaseUrl2);
|
|
82020
|
-
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !/^[A-Za-z0-9_-]+$/.test(localToken)) {
|
|
82021
|
-
throw new Error("Sidecar environment must use a valid 127.0.0.1 URL and local token");
|
|
82022
|
-
}
|
|
82023
|
-
return [
|
|
82024
|
-
`export OPENAI_BASE_URL=${url.origin}/v1`,
|
|
82025
|
-
`export OPENAI_API_KEY=${localToken}`
|
|
82026
|
-
].join("\n");
|
|
82027
|
-
}
|
|
82028
|
-
|
|
82029
|
-
// dist/cli-runtime.js
|
|
82030
|
-
function setupModel(args) {
|
|
82031
|
-
if (args[1] !== "codex")
|
|
82032
|
-
throw new Error("Usage: zk-credits setup codex [--model <model>]");
|
|
82033
|
-
if (args.length === 2)
|
|
82034
|
-
return void 0;
|
|
82035
|
-
if (args.length === 4 && args[2] === "--model" && args[3]?.trim())
|
|
82036
|
-
return args[3];
|
|
82037
|
-
throw new Error("Usage: zk-credits setup codex [--model <model>]");
|
|
82038
|
-
}
|
|
82039
|
-
async function runCliCommand(args, dependencies) {
|
|
82040
|
-
switch (args[0]) {
|
|
82041
|
-
case "env": {
|
|
82042
|
-
dependencies.write(formatOpenAiEnvironment(dependencies.loopbackBaseUrl, await dependencies.readToken()));
|
|
82043
|
-
return 0;
|
|
82044
|
-
}
|
|
82045
|
-
case "setup": {
|
|
82046
|
-
const model = setupModel(args);
|
|
82047
|
-
if (!await dependencies.isCredentialConfigured())
|
|
82048
|
-
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH before running zk-credits setup");
|
|
82049
|
-
await dependencies.validateSetupPrerequisites();
|
|
82050
|
-
await dependencies.ensureSidecar();
|
|
82051
|
-
await dependencies.configureCodex(model);
|
|
82052
|
-
dependencies.write("ZK Credits is ready for Codex.");
|
|
82053
|
-
dependencies.write("Run: zk-credits codex");
|
|
82054
|
-
return 0;
|
|
82055
|
-
}
|
|
82056
|
-
case "token": {
|
|
82057
|
-
dependencies.write(await dependencies.ensureSidecar());
|
|
82058
|
-
return 0;
|
|
82059
|
-
}
|
|
82060
|
-
case "status": {
|
|
82061
|
-
dependencies.write(`Credential export: ${await dependencies.isCredentialConfigured() ? "configured" : "missing"}`);
|
|
82062
|
-
dependencies.write(`Codex profile: ${await dependencies.isCodexProfileInstalled() ? "installed" : "missing"}`);
|
|
82063
|
-
dependencies.write(`Sidecar: ${await dependencies.isSidecarHealthy() ? "running" : "stopped"}`);
|
|
82064
|
-
return 0;
|
|
82065
|
-
}
|
|
82066
|
-
case "codex": {
|
|
82067
|
-
if (!await dependencies.isCodexProfileInstalled()) {
|
|
82068
|
-
throw new Error("Run zk-credits setup codex first");
|
|
82069
|
-
}
|
|
82070
|
-
await dependencies.ensureSidecar();
|
|
82071
|
-
return dependencies.launchCodex(args.slice(1));
|
|
82072
|
-
}
|
|
82073
|
-
case "cline": {
|
|
82074
|
-
if (!await dependencies.isCredentialConfigured())
|
|
82075
|
-
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH before running zk-credits cline");
|
|
82076
|
-
const localToken = await dependencies.ensureSidecar();
|
|
82077
|
-
return dependencies.launchCline(args.slice(1), localToken);
|
|
82078
|
-
}
|
|
82079
|
-
default:
|
|
82080
|
-
throw new Error("Usage: zk-credits <cline|setup codex|codex|status|token|serve|env>");
|
|
82081
|
-
}
|
|
82082
|
-
}
|
|
82083
|
-
|
|
82084
|
-
// dist/node-sidecar-lifecycle.js
|
|
82085
|
-
import { spawn as spawn3 } from "node:child_process";
|
|
82086
|
-
import { chmod as chmod4, mkdir as mkdir6, open } from "node:fs/promises";
|
|
82087
|
-
import { dirname as dirname5 } from "node:path";
|
|
82088
|
-
|
|
82089
|
-
// dist/sidecar-state.js
|
|
82090
|
-
import { chmod as chmod3, mkdir as mkdir5, readFile as readFile4, rename as rename3, writeFile as writeFile4 } from "node:fs/promises";
|
|
82091
|
-
import { dirname as dirname4 } from "node:path";
|
|
82092
|
-
async function writeLoopbackToken(tokenPath, token) {
|
|
82093
|
-
if (!token)
|
|
82094
|
-
throw new Error("Loopback token is required");
|
|
82095
|
-
await mkdir5(dirname4(tokenPath), { recursive: true, mode: 448 });
|
|
82096
|
-
const temporaryPath = `${tokenPath}.tmp`;
|
|
82097
|
-
await writeFile4(temporaryPath, `${token}
|
|
82098
|
-
`, { encoding: "utf8", mode: 384 });
|
|
82099
|
-
await chmod3(temporaryPath, 384);
|
|
82100
|
-
await rename3(temporaryPath, tokenPath);
|
|
82101
|
-
await chmod3(tokenPath, 384);
|
|
82102
|
-
}
|
|
82103
|
-
async function readLoopbackToken(tokenPath) {
|
|
82104
|
-
const token = (await readFile4(tokenPath, "utf8")).trim();
|
|
82105
|
-
if (!token)
|
|
82106
|
-
throw new Error("No active ZK Credits sidecar token; start zk-credits serve first");
|
|
82107
|
-
return token;
|
|
82108
|
-
}
|
|
82109
|
-
|
|
82110
|
-
// dist/node-sidecar-lifecycle.js
|
|
82111
|
-
var CHILD_ENVIRONMENT_KEYS = [
|
|
82112
|
-
"HOME",
|
|
82113
|
-
"PATH",
|
|
82114
|
-
"TMP",
|
|
82115
|
-
"TEMP",
|
|
82116
|
-
"TMPDIR",
|
|
82117
|
-
"LANG",
|
|
82118
|
-
"LC_ALL",
|
|
82119
|
-
"TZ",
|
|
82120
|
-
"SystemRoot",
|
|
82121
|
-
"WINDIR",
|
|
82122
|
-
"COMSPEC",
|
|
82123
|
-
"PATHEXT",
|
|
82124
|
-
"ZK_CREDITS_CREDENTIAL_PATH",
|
|
82125
|
-
"ZK_CREDITS_ARTIFACT_DIR",
|
|
82126
|
-
"ZK_CREDITS_WITNESS_PATH",
|
|
82127
|
-
"ZK_CREDITS_GATEWAY_URL",
|
|
82128
|
-
"BASE_RPC_URL",
|
|
82129
|
-
"BASE_PRIVATE_CREDIT_BOND_ADDRESS",
|
|
82130
|
-
"BASE_DEPLOYMENT_BLOCK",
|
|
82131
|
-
"BASE_CONFIRMATIONS"
|
|
82132
|
-
];
|
|
82133
|
-
function sidecarEnvironment(stateDirectory2, port) {
|
|
82134
|
-
const environment = {};
|
|
82135
|
-
for (const key of CHILD_ENVIRONMENT_KEYS) {
|
|
82136
|
-
const value = process.env[key];
|
|
82137
|
-
if (value !== void 0)
|
|
82138
|
-
environment[key] = value;
|
|
82139
|
-
}
|
|
82140
|
-
environment.ZK_CREDITS_HOME = stateDirectory2;
|
|
82141
|
-
environment.ZK_CREDITS_SIDECAR_PORT = port;
|
|
82142
|
-
return environment;
|
|
82143
|
-
}
|
|
82144
|
-
async function startDetachedProcess(specification) {
|
|
82145
|
-
await mkdir6(dirname5(specification.logPath), { recursive: true, mode: 448 });
|
|
82146
|
-
const log = await open(specification.logPath, "a", 384);
|
|
82147
|
-
await chmod4(specification.logPath, 384);
|
|
82148
|
-
try {
|
|
82149
|
-
const child = spawn3(specification.executable, specification.args, {
|
|
82150
|
-
detached: true,
|
|
82151
|
-
env: specification.env,
|
|
82152
|
-
stdio: [specification.stdin === void 0 ? "ignore" : "pipe", log.fd, log.fd]
|
|
82153
|
-
});
|
|
82154
|
-
await new Promise((resolve4, reject) => {
|
|
82155
|
-
child.once("spawn", resolve4);
|
|
82156
|
-
child.once("error", reject);
|
|
82157
|
-
});
|
|
82158
|
-
if (specification.stdin !== void 0 && child.stdin) {
|
|
82159
|
-
child.stdin.on("error", () => void 0);
|
|
82160
|
-
child.stdin.end(specification.stdin);
|
|
82161
|
-
}
|
|
82162
|
-
child.unref();
|
|
82163
|
-
} finally {
|
|
82164
|
-
await log.close();
|
|
82165
|
-
}
|
|
82166
|
-
}
|
|
82167
|
-
var defaultRuntime = {
|
|
82168
|
-
fetchHealth: async (url) => fetch(url, { signal: AbortSignal.timeout(500) }),
|
|
82169
|
-
startDetachedProcess,
|
|
82170
|
-
wait: async (milliseconds) => new Promise((resolve4) => setTimeout(resolve4, milliseconds))
|
|
82171
|
-
};
|
|
82172
|
-
function createNodeSidecarLifecycle(options, runtime = defaultRuntime) {
|
|
82173
|
-
const url = new URL(options.loopbackBaseUrl);
|
|
82174
|
-
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port) {
|
|
82175
|
-
throw new Error("Sidecar lifecycle requires a 127.0.0.1 HTTP URL with an explicit port");
|
|
82176
|
-
}
|
|
82177
|
-
return {
|
|
82178
|
-
logPath: options.logPath,
|
|
82179
|
-
async isHealthy() {
|
|
82180
|
-
try {
|
|
82181
|
-
const response = await runtime.fetchHealth(`${url.origin}/health`);
|
|
82182
|
-
if (!response.ok)
|
|
82183
|
-
return false;
|
|
82184
|
-
const body = await response.json();
|
|
82185
|
-
return body.service === "zk-credits-sidecar" && body.status === "ok";
|
|
82186
|
-
} catch {
|
|
82187
|
-
return false;
|
|
82188
|
-
}
|
|
82189
|
-
},
|
|
82190
|
-
async startDetached() {
|
|
82191
|
-
if (!options.readCredentialPassword)
|
|
82192
|
-
throw new Error("Credential password prompt is unavailable");
|
|
82193
|
-
const password = await options.readCredentialPassword();
|
|
82194
|
-
await runtime.startDetachedProcess({
|
|
82195
|
-
executable: process.execPath,
|
|
82196
|
-
args: [options.cliEntryPath, "serve", "--port", url.port, "--credential-password-stdin"],
|
|
82197
|
-
env: sidecarEnvironment(options.stateDirectory, url.port),
|
|
82198
|
-
logPath: options.logPath,
|
|
82199
|
-
stdin: password
|
|
82200
|
-
});
|
|
82201
|
-
},
|
|
82202
|
-
readToken: () => readLoopbackToken(options.tokenPath),
|
|
82203
|
-
wait: runtime.wait
|
|
82204
|
-
};
|
|
82205
|
-
}
|
|
82206
|
-
|
|
82207
|
-
// dist/server-startup.js
|
|
82208
|
-
async function activateSidecarServer(activation) {
|
|
82209
|
-
const address2 = await activation.listen();
|
|
82210
|
-
await activation.publishToken();
|
|
82211
|
-
return address2;
|
|
82212
|
-
}
|
|
82213
|
-
|
|
82214
82018
|
// dist/setup-config.js
|
|
82215
82019
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
82216
|
-
import { chmod as
|
|
82217
|
-
import { dirname as
|
|
82020
|
+
import { chmod as chmod4, lstat as lstat2, mkdir as mkdir6, open as open2, readFile as readFile5, readdir, realpath as realpath2, rename as rename4, rm as rm2 } from "node:fs/promises";
|
|
82021
|
+
import { dirname as dirname5, join as join5, resolve as resolve3 } from "node:path";
|
|
82218
82022
|
|
|
82219
82023
|
// dist/artifact-release.js
|
|
82220
82024
|
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
82221
82025
|
import { execFile as nodeExecFile } from "node:child_process";
|
|
82222
82026
|
import { gunzipSync } from "node:zlib";
|
|
82223
82027
|
import { promisify as promisify2 } from "node:util";
|
|
82224
|
-
import { chmod as
|
|
82225
|
-
import { dirname as
|
|
82028
|
+
import { chmod as chmod3, lstat, mkdir as mkdir5, open, readFile as readFile4, rename as rename3, rm } from "node:fs/promises";
|
|
82029
|
+
import { dirname as dirname4, join as join4, resolve as resolve2 } from "node:path";
|
|
82226
82030
|
var execFile = promisify2(nodeExecFile);
|
|
82227
82031
|
var MAX_COMPRESSED_BYTES = 20 * 1024 * 1024;
|
|
82228
82032
|
var MAX_EXPANDED_BYTES = 32 * 1024 * 1024;
|
|
@@ -82347,7 +82151,7 @@ function pinnedAsset(release, raw) {
|
|
|
82347
82151
|
}
|
|
82348
82152
|
}
|
|
82349
82153
|
async function writeBundleFile(directory, name, bytes) {
|
|
82350
|
-
const file = await
|
|
82154
|
+
const file = await open(join4(directory, name), "wx", 384);
|
|
82351
82155
|
try {
|
|
82352
82156
|
await file.writeFile(bytes);
|
|
82353
82157
|
await file.sync();
|
|
@@ -82356,9 +82160,9 @@ async function writeBundleFile(directory, name, bytes) {
|
|
|
82356
82160
|
}
|
|
82357
82161
|
}
|
|
82358
82162
|
async function replaceDirectoryAtomically(stage, target) {
|
|
82359
|
-
const parent =
|
|
82360
|
-
await
|
|
82361
|
-
const backup =
|
|
82163
|
+
const parent = dirname4(target);
|
|
82164
|
+
await mkdir5(parent, { recursive: true, mode: 448 });
|
|
82165
|
+
const backup = join4(parent, ".base-sepolia-old-" + randomUUID());
|
|
82362
82166
|
let movedOld = false;
|
|
82363
82167
|
try {
|
|
82364
82168
|
try {
|
|
@@ -82366,7 +82170,7 @@ async function replaceDirectoryAtomically(stage, target) {
|
|
|
82366
82170
|
if (existing.isSymbolicLink() || !existing.isDirectory()) {
|
|
82367
82171
|
throw new Error("Local proving bundle destination must be a regular directory");
|
|
82368
82172
|
}
|
|
82369
|
-
await
|
|
82173
|
+
await rename3(target, backup);
|
|
82370
82174
|
movedOld = true;
|
|
82371
82175
|
} catch (error) {
|
|
82372
82176
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
@@ -82375,11 +82179,11 @@ async function replaceDirectoryAtomically(stage, target) {
|
|
|
82375
82179
|
}
|
|
82376
82180
|
}
|
|
82377
82181
|
try {
|
|
82378
|
-
await
|
|
82379
|
-
await
|
|
82182
|
+
await rename3(stage, target);
|
|
82183
|
+
await chmod3(target, 448);
|
|
82380
82184
|
} catch (error) {
|
|
82381
82185
|
if (movedOld)
|
|
82382
|
-
await
|
|
82186
|
+
await rename3(backup, target);
|
|
82383
82187
|
throw error;
|
|
82384
82188
|
}
|
|
82385
82189
|
if (movedOld)
|
|
@@ -82394,13 +82198,13 @@ async function acquirePinnedArtifactBundle(options) {
|
|
|
82394
82198
|
throw new Error("This sidecar manifest has no pinned artifact release");
|
|
82395
82199
|
const names = new Set(options.manifest.artifacts.map((artifact) => artifact.file));
|
|
82396
82200
|
const command = options.runGithubCommand ?? defaultGithubCommand;
|
|
82397
|
-
const parent =
|
|
82398
|
-
const tempDirectory =
|
|
82399
|
-
const stage =
|
|
82201
|
+
const parent = dirname4(resolve2(options.targetDirectory));
|
|
82202
|
+
const tempDirectory = join4(parent, ".base-sepolia-download-" + randomUUID());
|
|
82203
|
+
const stage = join4(parent, ".base-sepolia-stage-" + randomUUID());
|
|
82400
82204
|
try {
|
|
82401
|
-
await
|
|
82402
|
-
await
|
|
82403
|
-
await
|
|
82205
|
+
await mkdir5(parent, { recursive: true, mode: 448 });
|
|
82206
|
+
await mkdir5(tempDirectory, { recursive: false, mode: 448 });
|
|
82207
|
+
await mkdir5(stage, { recursive: false, mode: 448 });
|
|
82404
82208
|
const releaseJson = await command(["api", `repos/${release.repository}/releases/${release.releaseId}`]);
|
|
82405
82209
|
pinnedAsset(release, releaseJson);
|
|
82406
82210
|
await command([
|
|
@@ -82414,12 +82218,12 @@ async function acquirePinnedArtifactBundle(options) {
|
|
|
82414
82218
|
"--pattern",
|
|
82415
82219
|
release.assetName
|
|
82416
82220
|
]);
|
|
82417
|
-
const archivePath =
|
|
82221
|
+
const archivePath = join4(tempDirectory, release.assetName);
|
|
82418
82222
|
const archiveInfo = await lstat(archivePath);
|
|
82419
82223
|
if (archiveInfo.isSymbolicLink() || !archiveInfo.isFile() || archiveInfo.size > MAX_COMPRESSED_BYTES) {
|
|
82420
82224
|
throw new Error("Pinned proving bundle archive is missing or too large");
|
|
82421
82225
|
}
|
|
82422
|
-
const compressed = await
|
|
82226
|
+
const compressed = await readFile4(archivePath);
|
|
82423
82227
|
if (digest(compressed) !== release.sha256)
|
|
82424
82228
|
throw new Error("Pinned proving bundle archive failed its SHA-256 check");
|
|
82425
82229
|
let expanded;
|
|
@@ -82431,7 +82235,7 @@ async function acquirePinnedArtifactBundle(options) {
|
|
|
82431
82235
|
const files = parseTar(expanded, names);
|
|
82432
82236
|
for (const [name, bytes] of files)
|
|
82433
82237
|
await writeBundleFile(stage, name, bytes);
|
|
82434
|
-
await
|
|
82238
|
+
await chmod3(stage, 448);
|
|
82435
82239
|
await resolvePinnedArtifactBundle({ artifactDirectory: stage, manifest: options.manifest });
|
|
82436
82240
|
await replaceDirectoryAtomically(stage, resolve2(options.targetDirectory));
|
|
82437
82241
|
await resolvePinnedArtifactBundle({ artifactDirectory: resolve2(options.targetDirectory), manifest: options.manifest });
|
|
@@ -82514,9 +82318,9 @@ function optionalEnvironmentInteger(environment, name) {
|
|
|
82514
82318
|
}
|
|
82515
82319
|
async function candidateDirectories(homeDirectory, stateDirectory2) {
|
|
82516
82320
|
const roots = [
|
|
82517
|
-
|
|
82518
|
-
|
|
82519
|
-
|
|
82321
|
+
join5(stateDirectory2, "artifacts", "base-sepolia"),
|
|
82322
|
+
join5(homeDirectory, ".zk-credits", "artifacts", "base-sepolia"),
|
|
82323
|
+
join5(homeDirectory, "Downloads")
|
|
82520
82324
|
];
|
|
82521
82325
|
const candidates = [...roots];
|
|
82522
82326
|
for (const root of roots) {
|
|
@@ -82528,7 +82332,7 @@ async function candidateDirectories(homeDirectory, stateDirectory2) {
|
|
|
82528
82332
|
}
|
|
82529
82333
|
for (const entry of entries) {
|
|
82530
82334
|
if (entry.isDirectory())
|
|
82531
|
-
candidates.push(
|
|
82335
|
+
candidates.push(join5(root, entry.name));
|
|
82532
82336
|
}
|
|
82533
82337
|
}
|
|
82534
82338
|
return [...new Set(candidates.map((path) => resolve3(path)))];
|
|
@@ -82625,10 +82429,10 @@ function assertPinnedEventSource(source, manifest) {
|
|
|
82625
82429
|
}
|
|
82626
82430
|
function witnessCandidates(homeDirectory, stateDirectory2) {
|
|
82627
82431
|
const roots = [
|
|
82628
|
-
|
|
82629
|
-
|
|
82630
|
-
|
|
82631
|
-
|
|
82432
|
+
join5(stateDirectory2, "witnesses"),
|
|
82433
|
+
join5(stateDirectory2, "witness"),
|
|
82434
|
+
join5(homeDirectory, ".zk-credits", "witnesses"),
|
|
82435
|
+
join5(homeDirectory, "Downloads")
|
|
82632
82436
|
];
|
|
82633
82437
|
return [...new Set(roots.flatMap((root) => [...WITNESS_FILENAMES].map((name) => resolve3(root, name))))];
|
|
82634
82438
|
}
|
|
@@ -82710,7 +82514,7 @@ async function readSetupConfig(path) {
|
|
|
82710
82514
|
const info = await lstat2(path);
|
|
82711
82515
|
if (!info.isFile())
|
|
82712
82516
|
throw new Error("Local setup config must be a regular file");
|
|
82713
|
-
raw = await
|
|
82517
|
+
raw = await readFile5(path, "utf8");
|
|
82714
82518
|
} catch (error) {
|
|
82715
82519
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
|
|
82716
82520
|
return void 0;
|
|
@@ -82727,8 +82531,8 @@ async function readSetupConfig(path) {
|
|
|
82727
82531
|
}
|
|
82728
82532
|
async function writeSetupConfig(path, config) {
|
|
82729
82533
|
const normalized = parseSetupConfig(config);
|
|
82730
|
-
const directory =
|
|
82731
|
-
await
|
|
82534
|
+
const directory = dirname5(resolve3(path));
|
|
82535
|
+
await mkdir6(directory, { recursive: true, mode: 448 });
|
|
82732
82536
|
const destination = resolve3(path);
|
|
82733
82537
|
try {
|
|
82734
82538
|
const existing = await lstat2(destination);
|
|
@@ -82738,17 +82542,17 @@ async function writeSetupConfig(path, config) {
|
|
|
82738
82542
|
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT"))
|
|
82739
82543
|
throw error;
|
|
82740
82544
|
}
|
|
82741
|
-
const temporary =
|
|
82545
|
+
const temporary = join5(directory, ".config-" + randomUUID2() + ".tmp");
|
|
82742
82546
|
try {
|
|
82743
|
-
const file = await
|
|
82547
|
+
const file = await open2(temporary, "wx", 384);
|
|
82744
82548
|
try {
|
|
82745
82549
|
await file.writeFile(JSON.stringify(normalized, null, 2) + "\n", "utf8");
|
|
82746
82550
|
await file.sync();
|
|
82747
82551
|
} finally {
|
|
82748
82552
|
await file.close();
|
|
82749
82553
|
}
|
|
82750
|
-
await
|
|
82751
|
-
await
|
|
82554
|
+
await rename4(temporary, destination);
|
|
82555
|
+
await chmod4(destination, 384);
|
|
82752
82556
|
} finally {
|
|
82753
82557
|
await rm2(temporary, { force: true });
|
|
82754
82558
|
}
|
|
@@ -82776,21 +82580,6 @@ function applySetupConfig(environment, config) {
|
|
|
82776
82580
|
}
|
|
82777
82581
|
}
|
|
82778
82582
|
|
|
82779
|
-
// dist/sidecar-lifecycle.js
|
|
82780
|
-
async function ensureSidecarReady(dependencies, options = {}) {
|
|
82781
|
-
if (await dependencies.isHealthy())
|
|
82782
|
-
return dependencies.readToken();
|
|
82783
|
-
await dependencies.startDetached();
|
|
82784
|
-
const attempts = options.attempts ?? 50;
|
|
82785
|
-
const intervalMs = options.intervalMs ?? 100;
|
|
82786
|
-
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
82787
|
-
await dependencies.wait(intervalMs);
|
|
82788
|
-
if (await dependencies.isHealthy())
|
|
82789
|
-
return dependencies.readToken();
|
|
82790
|
-
}
|
|
82791
|
-
throw new Error(`ZK Credits sidecar did not become ready; inspect ${dependencies.logPath}`);
|
|
82792
|
-
}
|
|
82793
|
-
|
|
82794
82583
|
// dist/sidecar.js
|
|
82795
82584
|
import { createServer } from "node:http";
|
|
82796
82585
|
|
|
@@ -82873,6 +82662,11 @@ function responseTools(value) {
|
|
|
82873
82662
|
tools.push({ type: "function", function: definition });
|
|
82874
82663
|
continue;
|
|
82875
82664
|
}
|
|
82665
|
+
if (tool.type === "custom") {
|
|
82666
|
+
if (!hasOnlyKeys(tool, ["type", "name", "description", "format"]) || tool.name !== "apply_patch" || tool.description !== void 0 && typeof tool.description !== "string" || !isRecord3(tool.format) || !hasOnlyKeys(tool.format, ["type", "syntax", "definition"]) || tool.format.type !== "grammar" || tool.format.syntax !== "lark" || typeof tool.format.definition !== "string")
|
|
82667
|
+
return void 0;
|
|
82668
|
+
continue;
|
|
82669
|
+
}
|
|
82876
82670
|
if (tool.type === "web_search") {
|
|
82877
82671
|
if (!hasOnlyKeys(tool, ["type", "external_web_access"]) || tool.external_web_access !== void 0 && typeof tool.external_web_access !== "boolean")
|
|
82878
82672
|
return void 0;
|
|
@@ -82970,8 +82764,6 @@ function translateResponsesRequest(body) {
|
|
|
82970
82764
|
}
|
|
82971
82765
|
chatRequest.max_completion_tokens = body.max_output_tokens;
|
|
82972
82766
|
}
|
|
82973
|
-
if (body.parallel_tool_calls !== void 0)
|
|
82974
|
-
chatRequest.parallel_tool_calls = body.parallel_tool_calls;
|
|
82975
82767
|
for (const key of ["temperature", "top_p", "stop", "seed", "presence_penalty", "frequency_penalty", "logit_bias"]) {
|
|
82976
82768
|
if (body[key] !== void 0)
|
|
82977
82769
|
chatRequest[key] = body[key];
|
|
@@ -83031,8 +82823,9 @@ function responsesEventStream(chatValue, model) {
|
|
|
83031
82823
|
if (text !== null && text !== void 0 && typeof text !== "string") {
|
|
83032
82824
|
throw new Error("Gateway returned an unsupported chat content value");
|
|
83033
82825
|
}
|
|
83034
|
-
if (refusal !== void 0 && typeof refusal !== "string")
|
|
82826
|
+
if (refusal !== void 0 && refusal !== null && typeof refusal !== "string") {
|
|
83035
82827
|
throw new Error("Gateway returned an invalid refusal value");
|
|
82828
|
+
}
|
|
83036
82829
|
if (typeof text === "string" || typeof refusal === "string") {
|
|
83037
82830
|
const itemId = `msg_${randomUUID3().replaceAll("-", "")}`;
|
|
83038
82831
|
const isRefusal = typeof refusal === "string";
|
|
@@ -83221,6 +83014,7 @@ async function relayResponsesGatewayResponse(res, upstream, responseModel) {
|
|
|
83221
83014
|
function createSidecarServer(options) {
|
|
83222
83015
|
const gatewayBaseUrl = options.gatewayBaseUrl.replace(/\/$/u, "");
|
|
83223
83016
|
let server = null;
|
|
83017
|
+
let internalTrialRequestClaimed = false;
|
|
83224
83018
|
const inFlight = /* @__PURE__ */ new Set();
|
|
83225
83019
|
const handler = async (req, res) => {
|
|
83226
83020
|
const pathname = new URL(req.url || "/", "http://127.0.0.1").pathname;
|
|
@@ -83281,6 +83075,13 @@ function createSidecarServer(options) {
|
|
|
83281
83075
|
return;
|
|
83282
83076
|
}
|
|
83283
83077
|
}
|
|
83078
|
+
if (options.internalTrialOneProof) {
|
|
83079
|
+
if (internalTrialRequestClaimed) {
|
|
83080
|
+
sendJson(res, 409, { error: "internal_trial_limit_reached" });
|
|
83081
|
+
return;
|
|
83082
|
+
}
|
|
83083
|
+
internalTrialRequestClaimed = true;
|
|
83084
|
+
}
|
|
83284
83085
|
const upstream = await options.prepaidClient.fetch(`${gatewayBaseUrl}/v1/chat/completions`, {
|
|
83285
83086
|
method: "POST",
|
|
83286
83087
|
headers: { "Content-Type": "application/json" },
|
|
@@ -83335,9 +83136,337 @@ function createSidecarServer(options) {
|
|
|
83335
83136
|
};
|
|
83336
83137
|
}
|
|
83337
83138
|
|
|
83139
|
+
// dist/sidecar-config.js
|
|
83140
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
83141
|
+
import { join as join6 } from "node:path";
|
|
83142
|
+
function createLoopbackToken() {
|
|
83143
|
+
return randomBytes3(32).toString("base64url");
|
|
83144
|
+
}
|
|
83145
|
+
function sidecarStatePaths(stateDirectory2) {
|
|
83146
|
+
return {
|
|
83147
|
+
tokenPath: join6(stateDirectory2, "loopback-token"),
|
|
83148
|
+
logPath: join6(stateDirectory2, "sidecar.log")
|
|
83149
|
+
};
|
|
83150
|
+
}
|
|
83151
|
+
function formatOpenAiEnvironment(loopbackBaseUrl2, localToken) {
|
|
83152
|
+
const url = new URL(loopbackBaseUrl2);
|
|
83153
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !/^[A-Za-z0-9_-]+$/.test(localToken)) {
|
|
83154
|
+
throw new Error("Sidecar environment must use a valid 127.0.0.1 URL and local token");
|
|
83155
|
+
}
|
|
83156
|
+
return [
|
|
83157
|
+
`export OPENAI_BASE_URL=${url.origin}/v1`,
|
|
83158
|
+
`export OPENAI_API_KEY=${localToken}`
|
|
83159
|
+
].join("\n");
|
|
83160
|
+
}
|
|
83161
|
+
|
|
83162
|
+
// dist/sidecar-state.js
|
|
83163
|
+
import { chmod as chmod5, mkdir as mkdir7, readFile as readFile6, rename as rename5, writeFile as writeFile4 } from "node:fs/promises";
|
|
83164
|
+
import { dirname as dirname6 } from "node:path";
|
|
83165
|
+
async function writeLoopbackToken(tokenPath, token) {
|
|
83166
|
+
if (!token)
|
|
83167
|
+
throw new Error("Loopback token is required");
|
|
83168
|
+
await mkdir7(dirname6(tokenPath), { recursive: true, mode: 448 });
|
|
83169
|
+
const temporaryPath = `${tokenPath}.tmp`;
|
|
83170
|
+
await writeFile4(temporaryPath, `${token}
|
|
83171
|
+
`, { encoding: "utf8", mode: 384 });
|
|
83172
|
+
await chmod5(temporaryPath, 384);
|
|
83173
|
+
await rename5(temporaryPath, tokenPath);
|
|
83174
|
+
await chmod5(tokenPath, 384);
|
|
83175
|
+
}
|
|
83176
|
+
async function readLoopbackToken(tokenPath) {
|
|
83177
|
+
const token = (await readFile6(tokenPath, "utf8")).trim();
|
|
83178
|
+
if (!token)
|
|
83179
|
+
throw new Error("No active ZK Credits sidecar token; start zk-credits serve first");
|
|
83180
|
+
return token;
|
|
83181
|
+
}
|
|
83182
|
+
|
|
83183
|
+
// dist/local-x402-agent.js
|
|
83184
|
+
var DEFAULT_GATEWAY_URL = "https://zk-credits-gateway.onrender.com";
|
|
83185
|
+
var DEFAULT_PORT = 3210;
|
|
83186
|
+
async function witnessProviderForSource(source, cachePath) {
|
|
83187
|
+
if (source.kind === "file") {
|
|
83188
|
+
const value = JSON.parse(await readFile7(source.path, "utf8"));
|
|
83189
|
+
return createFileWitnessProvider(value);
|
|
83190
|
+
}
|
|
83191
|
+
return createBaseEventWitnessProvider({
|
|
83192
|
+
rpcUrl: source.rpcUrl,
|
|
83193
|
+
contractAddress: source.contractAddress,
|
|
83194
|
+
deploymentBlock: source.deploymentBlock === void 0 ? void 0 : BigInt(source.deploymentBlock),
|
|
83195
|
+
confirmations: source.confirmations === void 0 ? void 0 : BigInt(source.confirmations),
|
|
83196
|
+
cachePath
|
|
83197
|
+
});
|
|
83198
|
+
}
|
|
83199
|
+
async function readCredential(path, password) {
|
|
83200
|
+
const parsed = JSON.parse(await readFile7(path, "utf8"));
|
|
83201
|
+
if (parsed.format !== "zk-credits-credential" || parsed.version !== 1 && parsed.version !== 2) {
|
|
83202
|
+
throw new Error("Credential file is not a supported zk-credits export");
|
|
83203
|
+
}
|
|
83204
|
+
return decryptAnyCredentialExport(parsed, password);
|
|
83205
|
+
}
|
|
83206
|
+
async function createLocalX402Agent(options) {
|
|
83207
|
+
const environment = options.environment ?? process.env;
|
|
83208
|
+
const homeDirectory = options.homeDirectory ?? homedir();
|
|
83209
|
+
const stateDirectory2 = options.stateDirectory ?? environment.ZK_CREDITS_HOME ?? join7(homeDirectory, ".zk-credits");
|
|
83210
|
+
const credentialPath = environment.ZK_CREDITS_CREDENTIAL_PATH;
|
|
83211
|
+
if (!credentialPath)
|
|
83212
|
+
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH to the encrypted browser export");
|
|
83213
|
+
const savedConfig = await readSetupConfig(join7(stateDirectory2, "config.json"));
|
|
83214
|
+
if (savedConfig)
|
|
83215
|
+
applySetupConfig(environment, savedConfig);
|
|
83216
|
+
const credential = await readCredential(credentialPath, options.credentialPassword);
|
|
83217
|
+
const artifactDirectory = environment.ZK_CREDITS_ARTIFACT_DIR;
|
|
83218
|
+
if (!artifactDirectory)
|
|
83219
|
+
throw new Error("Run `zk-credits setup codex` first to install and verify the pinned proving bundle");
|
|
83220
|
+
const witnessPath = environment.ZK_CREDITS_WITNESS_PATH;
|
|
83221
|
+
const rpcUrl = environment.BASE_RPC_URL;
|
|
83222
|
+
const contractAddress = environment.BASE_PRIVATE_CREDIT_BOND_ADDRESS;
|
|
83223
|
+
const witnessProvider = witnessPath ? await witnessProviderForSource({ kind: "file", path: witnessPath }, join7(stateDirectory2, "base-event-sync.json")) : rpcUrl && contractAddress ? await witnessProviderForSource({
|
|
83224
|
+
kind: "base-events",
|
|
83225
|
+
rpcUrl,
|
|
83226
|
+
contractAddress,
|
|
83227
|
+
...environment.BASE_DEPLOYMENT_BLOCK && /^\d+$/u.test(environment.BASE_DEPLOYMENT_BLOCK) ? { deploymentBlock: environment.BASE_DEPLOYMENT_BLOCK } : {},
|
|
83228
|
+
...environment.BASE_CONFIRMATIONS && /^\d+$/u.test(environment.BASE_CONFIRMATIONS) ? { confirmations: environment.BASE_CONFIRMATIONS } : {}
|
|
83229
|
+
}, join7(stateDirectory2, "base-event-sync.json")) : (() => {
|
|
83230
|
+
throw new Error("Local setup is missing its Base witness source; rerun `zk-credits setup codex`");
|
|
83231
|
+
})();
|
|
83232
|
+
const proofMetrics = createBaseProofMetrics();
|
|
83233
|
+
const exchangeMetrics = createZkPrepaidLifecycleMetrics();
|
|
83234
|
+
const slotLedger = await BaseSlotLedger.open({ path: join7(stateDirectory2, "base-slots.json") });
|
|
83235
|
+
const prove = await createPinnedBaseProofGenerator({ artifactDirectory, metrics: proofMetrics });
|
|
83236
|
+
validateBaseCreditWitness(await witnessProvider.witnessForCredential(credential));
|
|
83237
|
+
if (credential.deploymentDomain !== "84532" || credential.expiry <= Math.floor(Date.now() / 1e3)) {
|
|
83238
|
+
throw new Error(`Credential is not active for ${BASE_SEPOLIA_NETWORK}`);
|
|
83239
|
+
}
|
|
83240
|
+
const prepaid = createBasePrepaidClient({
|
|
83241
|
+
credential,
|
|
83242
|
+
witnessProvider,
|
|
83243
|
+
prove,
|
|
83244
|
+
slotLedger,
|
|
83245
|
+
lifecycle: exchangeMetrics.observe
|
|
83246
|
+
});
|
|
83247
|
+
const localToken = createLoopbackToken();
|
|
83248
|
+
const paths = sidecarStatePaths(stateDirectory2);
|
|
83249
|
+
const metrics = () => ({
|
|
83250
|
+
...proofMetrics.snapshot(),
|
|
83251
|
+
exchange: exchangeMetrics.snapshot()
|
|
83252
|
+
});
|
|
83253
|
+
const server = createSidecarServer({
|
|
83254
|
+
localToken,
|
|
83255
|
+
gatewayBaseUrl: environment.ZK_CREDITS_GATEWAY_URL || DEFAULT_GATEWAY_URL,
|
|
83256
|
+
prepaidClient: prepaid.client,
|
|
83257
|
+
metrics
|
|
83258
|
+
});
|
|
83259
|
+
let baseUrl;
|
|
83260
|
+
try {
|
|
83261
|
+
const port = options.port ?? Number(environment.ZK_CREDITS_SIDECAR_PORT || DEFAULT_PORT);
|
|
83262
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
83263
|
+
throw new Error("Local metrics port is invalid");
|
|
83264
|
+
baseUrl = await server.listen(port);
|
|
83265
|
+
await writeLoopbackToken(paths.tokenPath, localToken);
|
|
83266
|
+
} catch (error) {
|
|
83267
|
+
await server.close();
|
|
83268
|
+
throw error;
|
|
83269
|
+
}
|
|
83270
|
+
return {
|
|
83271
|
+
client: prepaid.client,
|
|
83272
|
+
metricsUrl: `${baseUrl}/metrics`,
|
|
83273
|
+
close: async () => server.close()
|
|
83274
|
+
};
|
|
83275
|
+
}
|
|
83276
|
+
|
|
83277
|
+
// dist/cli.js
|
|
83278
|
+
import { createZkPrepaidLifecycleMetrics as createZkPrepaidLifecycleMetrics2 } from "@zk-credits/x402-zk-prepaid";
|
|
83279
|
+
import { decryptAnyCredentialExport as decryptAnyCredentialExport2 } from "@zk-credits/shared/base";
|
|
83280
|
+
|
|
83281
|
+
// dist/cli-runtime.js
|
|
83282
|
+
function setupModel(args) {
|
|
83283
|
+
if (args[1] !== "codex")
|
|
83284
|
+
throw new Error("Usage: zk-credits setup codex [--model <model>]");
|
|
83285
|
+
if (args.length === 2)
|
|
83286
|
+
return void 0;
|
|
83287
|
+
if (args.length === 4 && args[2] === "--model" && args[3]?.trim())
|
|
83288
|
+
return args[3];
|
|
83289
|
+
throw new Error("Usage: zk-credits setup codex [--model <model>]");
|
|
83290
|
+
}
|
|
83291
|
+
async function runCliCommand(args, dependencies) {
|
|
83292
|
+
switch (args[0]) {
|
|
83293
|
+
case "env": {
|
|
83294
|
+
dependencies.write(formatOpenAiEnvironment(dependencies.loopbackBaseUrl, await dependencies.readToken()));
|
|
83295
|
+
return 0;
|
|
83296
|
+
}
|
|
83297
|
+
case "setup": {
|
|
83298
|
+
const model = setupModel(args);
|
|
83299
|
+
if (!await dependencies.isCredentialConfigured())
|
|
83300
|
+
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH before running zk-credits setup");
|
|
83301
|
+
await dependencies.validateSetupPrerequisites();
|
|
83302
|
+
await dependencies.ensureSidecar();
|
|
83303
|
+
await dependencies.configureCodex(model);
|
|
83304
|
+
dependencies.write("ZK Credits is ready for Codex.");
|
|
83305
|
+
dependencies.write("Run: zk-credits codex");
|
|
83306
|
+
return 0;
|
|
83307
|
+
}
|
|
83308
|
+
case "token": {
|
|
83309
|
+
dependencies.write(await dependencies.ensureSidecar());
|
|
83310
|
+
return 0;
|
|
83311
|
+
}
|
|
83312
|
+
case "status": {
|
|
83313
|
+
dependencies.write(`Credential export: ${await dependencies.isCredentialConfigured() ? "configured" : "missing"}`);
|
|
83314
|
+
dependencies.write(`Codex profile: ${await dependencies.isCodexProfileInstalled() ? "installed" : "missing"}`);
|
|
83315
|
+
dependencies.write(`Sidecar: ${await dependencies.isSidecarHealthy() ? "running" : "stopped"}`);
|
|
83316
|
+
return 0;
|
|
83317
|
+
}
|
|
83318
|
+
case "codex": {
|
|
83319
|
+
if (!await dependencies.isCodexProfileInstalled()) {
|
|
83320
|
+
throw new Error("Run zk-credits setup codex first");
|
|
83321
|
+
}
|
|
83322
|
+
await dependencies.ensureSidecar();
|
|
83323
|
+
return dependencies.launchCodex(args.slice(1));
|
|
83324
|
+
}
|
|
83325
|
+
case "cline": {
|
|
83326
|
+
if (!await dependencies.isCredentialConfigured())
|
|
83327
|
+
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH before running zk-credits cline");
|
|
83328
|
+
const localToken = await dependencies.ensureSidecar();
|
|
83329
|
+
return dependencies.launchCline(args.slice(1), localToken);
|
|
83330
|
+
}
|
|
83331
|
+
default:
|
|
83332
|
+
throw new Error("Usage: zk-credits <cline|setup codex|codex|status|token|serve|env>");
|
|
83333
|
+
}
|
|
83334
|
+
}
|
|
83335
|
+
|
|
83336
|
+
// dist/node-sidecar-lifecycle.js
|
|
83337
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
83338
|
+
import { chmod as chmod6, mkdir as mkdir8, open as open3 } from "node:fs/promises";
|
|
83339
|
+
import { dirname as dirname7 } from "node:path";
|
|
83340
|
+
var CHILD_ENVIRONMENT_KEYS = [
|
|
83341
|
+
"HOME",
|
|
83342
|
+
"PATH",
|
|
83343
|
+
"TMP",
|
|
83344
|
+
"TEMP",
|
|
83345
|
+
"TMPDIR",
|
|
83346
|
+
"LANG",
|
|
83347
|
+
"LC_ALL",
|
|
83348
|
+
"TZ",
|
|
83349
|
+
"SystemRoot",
|
|
83350
|
+
"WINDIR",
|
|
83351
|
+
"COMSPEC",
|
|
83352
|
+
"PATHEXT",
|
|
83353
|
+
"ZK_CREDITS_CREDENTIAL_PATH",
|
|
83354
|
+
"ZK_CREDITS_ARTIFACT_DIR",
|
|
83355
|
+
"ZK_CREDITS_WITNESS_PATH",
|
|
83356
|
+
"ZK_CREDITS_GATEWAY_URL",
|
|
83357
|
+
"BASE_RPC_URL",
|
|
83358
|
+
"BASE_PRIVATE_CREDIT_BOND_ADDRESS",
|
|
83359
|
+
"BASE_DEPLOYMENT_BLOCK",
|
|
83360
|
+
"BASE_CONFIRMATIONS"
|
|
83361
|
+
];
|
|
83362
|
+
function sidecarEnvironment(stateDirectory2, port) {
|
|
83363
|
+
const environment = {};
|
|
83364
|
+
for (const key of CHILD_ENVIRONMENT_KEYS) {
|
|
83365
|
+
const value = process.env[key];
|
|
83366
|
+
if (value !== void 0)
|
|
83367
|
+
environment[key] = value;
|
|
83368
|
+
}
|
|
83369
|
+
environment.ZK_CREDITS_HOME = stateDirectory2;
|
|
83370
|
+
environment.ZK_CREDITS_SIDECAR_PORT = port;
|
|
83371
|
+
return environment;
|
|
83372
|
+
}
|
|
83373
|
+
async function startDetachedProcess(specification) {
|
|
83374
|
+
await mkdir8(dirname7(specification.logPath), { recursive: true, mode: 448 });
|
|
83375
|
+
const log = await open3(specification.logPath, "a", 384);
|
|
83376
|
+
await chmod6(specification.logPath, 384);
|
|
83377
|
+
try {
|
|
83378
|
+
const child = spawn3(specification.executable, specification.args, {
|
|
83379
|
+
detached: true,
|
|
83380
|
+
env: specification.env,
|
|
83381
|
+
stdio: [specification.stdin === void 0 ? "ignore" : "pipe", log.fd, log.fd]
|
|
83382
|
+
});
|
|
83383
|
+
await new Promise((resolve4, reject) => {
|
|
83384
|
+
child.once("spawn", resolve4);
|
|
83385
|
+
child.once("error", reject);
|
|
83386
|
+
});
|
|
83387
|
+
if (specification.stdin !== void 0 && child.stdin) {
|
|
83388
|
+
child.stdin.on("error", () => void 0);
|
|
83389
|
+
child.stdin.end(specification.stdin);
|
|
83390
|
+
}
|
|
83391
|
+
child.unref();
|
|
83392
|
+
} finally {
|
|
83393
|
+
await log.close();
|
|
83394
|
+
}
|
|
83395
|
+
}
|
|
83396
|
+
var defaultRuntime = {
|
|
83397
|
+
fetchHealth: async (url) => fetch(url, { signal: AbortSignal.timeout(500) }),
|
|
83398
|
+
startDetachedProcess,
|
|
83399
|
+
wait: async (milliseconds) => new Promise((resolve4) => setTimeout(resolve4, milliseconds))
|
|
83400
|
+
};
|
|
83401
|
+
function createNodeSidecarLifecycle(options, runtime = defaultRuntime) {
|
|
83402
|
+
const url = new URL(options.loopbackBaseUrl);
|
|
83403
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port) {
|
|
83404
|
+
throw new Error("Sidecar lifecycle requires a 127.0.0.1 HTTP URL with an explicit port");
|
|
83405
|
+
}
|
|
83406
|
+
return {
|
|
83407
|
+
logPath: options.logPath,
|
|
83408
|
+
async isHealthy() {
|
|
83409
|
+
try {
|
|
83410
|
+
const response = await runtime.fetchHealth(`${url.origin}/health`);
|
|
83411
|
+
if (!response.ok)
|
|
83412
|
+
return false;
|
|
83413
|
+
const body = await response.json();
|
|
83414
|
+
return body.service === "zk-credits-sidecar" && body.status === "ok";
|
|
83415
|
+
} catch {
|
|
83416
|
+
return false;
|
|
83417
|
+
}
|
|
83418
|
+
},
|
|
83419
|
+
async startDetached() {
|
|
83420
|
+
if (!options.readCredentialPassword)
|
|
83421
|
+
throw new Error("Credential password prompt is unavailable");
|
|
83422
|
+
const password = await options.readCredentialPassword();
|
|
83423
|
+
await runtime.startDetachedProcess({
|
|
83424
|
+
executable: process.execPath,
|
|
83425
|
+
args: [options.cliEntryPath, "serve", "--port", url.port, "--credential-password-stdin"],
|
|
83426
|
+
env: sidecarEnvironment(options.stateDirectory, url.port),
|
|
83427
|
+
logPath: options.logPath,
|
|
83428
|
+
stdin: password
|
|
83429
|
+
});
|
|
83430
|
+
},
|
|
83431
|
+
readToken: () => readLoopbackToken(options.tokenPath),
|
|
83432
|
+
wait: runtime.wait
|
|
83433
|
+
};
|
|
83434
|
+
}
|
|
83435
|
+
|
|
83436
|
+
// dist/server-startup.js
|
|
83437
|
+
async function activateSidecarServer(activation) {
|
|
83438
|
+
const address2 = await activation.listen();
|
|
83439
|
+
await activation.publishToken();
|
|
83440
|
+
return address2;
|
|
83441
|
+
}
|
|
83442
|
+
|
|
83443
|
+
// dist/sidecar-lifecycle.js
|
|
83444
|
+
async function ensureSidecarReady(dependencies, options = {}) {
|
|
83445
|
+
if (await dependencies.isHealthy())
|
|
83446
|
+
return dependencies.readToken();
|
|
83447
|
+
await dependencies.startDetached();
|
|
83448
|
+
const attempts = options.attempts ?? 50;
|
|
83449
|
+
const intervalMs = options.intervalMs ?? 100;
|
|
83450
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
83451
|
+
await dependencies.wait(intervalMs);
|
|
83452
|
+
if (await dependencies.isHealthy())
|
|
83453
|
+
return dependencies.readToken();
|
|
83454
|
+
}
|
|
83455
|
+
throw new Error(`ZK Credits sidecar did not become ready; inspect ${dependencies.logPath}`);
|
|
83456
|
+
}
|
|
83457
|
+
|
|
83338
83458
|
// dist/base-registered-trial.js
|
|
83339
83459
|
import { x402Client } from "@x402/core/client";
|
|
83340
|
-
import { BASE_SEPOLIA_NETWORK, decodeHeader as decodeHeader2, encodeHeader, lifecycleFailure, lifecycleStage, PAYMENT_REQUIRED_HEADER as PAYMENT_REQUIRED_HEADER2, PAYMENT_RESPONSE_HEADER as PAYMENT_RESPONSE_HEADER3, PAYMENT_SIGNATURE_HEADER as PAYMENT_SIGNATURE_HEADER2, registerZkPrepaidClient, ZK_PREPAID_SCHEME } from "@zk-credits/x402-zk-prepaid";
|
|
83460
|
+
import { BASE_SEPOLIA_NETWORK as BASE_SEPOLIA_NETWORK2, decodeHeader as decodeHeader2, encodeHeader, lifecycleFailure, lifecycleStage, PAYMENT_REQUIRED_HEADER as PAYMENT_REQUIRED_HEADER2, PAYMENT_RESPONSE_HEADER as PAYMENT_RESPONSE_HEADER3, PAYMENT_SIGNATURE_HEADER as PAYMENT_SIGNATURE_HEADER2, registerZkPrepaidClient, ZK_PREPAID_SCHEME } from "@zk-credits/x402-zk-prepaid";
|
|
83461
|
+
function buildBaseRegisteredTrialRequestBody(task = "Reply with exactly: internal trial complete.") {
|
|
83462
|
+
if (typeof task !== "string" || task.trim().length === 0 || task.length > 4e3) {
|
|
83463
|
+
throw new Error("Task must contain between 1 and 4000 characters");
|
|
83464
|
+
}
|
|
83465
|
+
return JSON.stringify({
|
|
83466
|
+
model: "deepseek/deepseek-v4-flash",
|
|
83467
|
+
messages: [{ role: "user", content: task }]
|
|
83468
|
+
});
|
|
83469
|
+
}
|
|
83341
83470
|
function observe(options, event) {
|
|
83342
83471
|
try {
|
|
83343
83472
|
options.lifecycle?.(event);
|
|
@@ -83406,7 +83535,7 @@ async function runBaseRegisteredTrialExchange(options) {
|
|
|
83406
83535
|
} catch {
|
|
83407
83536
|
return withFailure(options, result, startingCommittedSlots, "challenge_invalid", "challenge_unreadable");
|
|
83408
83537
|
}
|
|
83409
|
-
if (required.x402Version !== 2 || !Array.isArray(required.accepts) || !required.accepts.some((accepted) => accepted.scheme === ZK_PREPAID_SCHEME && accepted.network ===
|
|
83538
|
+
if (required.x402Version !== 2 || !Array.isArray(required.accepts) || !required.accepts.some((accepted) => accepted.scheme === ZK_PREPAID_SCHEME && accepted.network === BASE_SEPOLIA_NETWORK2)) {
|
|
83410
83539
|
return withFailure(options, result, startingCommittedSlots, "challenge_unsupported", "challenge_unsupported");
|
|
83411
83540
|
}
|
|
83412
83541
|
const challengeUrl = required.resource?.url;
|
|
@@ -83417,7 +83546,7 @@ async function runBaseRegisteredTrialExchange(options) {
|
|
|
83417
83546
|
observe(options, lifecycleStage("challenge_received"));
|
|
83418
83547
|
const createPayment = createBasePaymentFactory(options);
|
|
83419
83548
|
const directAdapter = registerZkPrepaidClient(new x402Client((_version, accepts) => {
|
|
83420
|
-
const selected = accepts.find((accepted) => accepted.scheme === ZK_PREPAID_SCHEME && accepted.network ===
|
|
83549
|
+
const selected = accepts.find((accepted) => accepted.scheme === ZK_PREPAID_SCHEME && accepted.network === BASE_SEPOLIA_NETWORK2);
|
|
83421
83550
|
if (!selected)
|
|
83422
83551
|
throw new Error("zk_prepaid_challenge_missing");
|
|
83423
83552
|
return selected;
|
|
@@ -83458,7 +83587,7 @@ async function runBaseRegisteredTrialExchange(options) {
|
|
|
83458
83587
|
}
|
|
83459
83588
|
try {
|
|
83460
83589
|
const settlement = decodeHeader2(encodedPaymentResponse);
|
|
83461
|
-
if (settlement.success !== true || settlement.network !==
|
|
83590
|
+
if (settlement.success !== true || settlement.network !== BASE_SEPOLIA_NETWORK2 || settlement.transaction !== "") {
|
|
83462
83591
|
return withFailure(options, result, startingCommittedSlots, "payment_response_invalid", "settlement_failed");
|
|
83463
83592
|
}
|
|
83464
83593
|
} catch {
|
|
@@ -83471,12 +83600,16 @@ async function runBaseRegisteredTrialExchange(options) {
|
|
|
83471
83600
|
}
|
|
83472
83601
|
result.responseSucceeded = true;
|
|
83473
83602
|
observe(options, lifecycleStage("exchange_succeeded"));
|
|
83603
|
+
try {
|
|
83604
|
+
await options.onResponse?.(paidResponse.clone());
|
|
83605
|
+
} catch {
|
|
83606
|
+
}
|
|
83474
83607
|
result.committedSlotDelta = ledger.snapshot().committed - startingCommittedSlots;
|
|
83475
83608
|
return result;
|
|
83476
83609
|
}
|
|
83477
83610
|
|
|
83478
83611
|
// dist/cli.js
|
|
83479
|
-
import { BASE_SEPOLIA_NETWORK as
|
|
83612
|
+
import { BASE_SEPOLIA_NETWORK as BASE_SEPOLIA_NETWORK3 } from "@zk-credits/x402-zk-prepaid";
|
|
83480
83613
|
|
|
83481
83614
|
// dist/gateway-root-check.js
|
|
83482
83615
|
function isRecord5(value) {
|
|
@@ -83505,14 +83638,74 @@ async function requireGatewayKnownRoot(root, origin, fetcher = fetch) {
|
|
|
83505
83638
|
}
|
|
83506
83639
|
}
|
|
83507
83640
|
|
|
83641
|
+
// dist/gateway-trial-status.js
|
|
83642
|
+
var GATEWAY_READINESS_CHECK_NAMES = [
|
|
83643
|
+
"launchControl",
|
|
83644
|
+
"database",
|
|
83645
|
+
"baseRoot",
|
|
83646
|
+
"baseRpc",
|
|
83647
|
+
"verifierAssets",
|
|
83648
|
+
"provider"
|
|
83649
|
+
];
|
|
83650
|
+
var MAX_STATUS_AGE_MS = 12e4;
|
|
83651
|
+
var MAX_FUTURE_SKEW_MS = 3e4;
|
|
83652
|
+
function isRecord6(value) {
|
|
83653
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
83654
|
+
}
|
|
83655
|
+
function isGatewayStatusFresh(value, now = Date.now()) {
|
|
83656
|
+
if (typeof value !== "string")
|
|
83657
|
+
return false;
|
|
83658
|
+
const timestamp = Date.parse(value);
|
|
83659
|
+
if (!Number.isFinite(timestamp))
|
|
83660
|
+
return false;
|
|
83661
|
+
const age = now - timestamp;
|
|
83662
|
+
return age <= MAX_STATUS_AGE_MS && age >= -MAX_FUTURE_SKEW_MS;
|
|
83663
|
+
}
|
|
83664
|
+
function evaluateGatewayReadiness(status, body, now = Date.now()) {
|
|
83665
|
+
const report = isRecord6(body) ? body : void 0;
|
|
83666
|
+
const checks = Array.isArray(report?.checks) ? report.checks : void 0;
|
|
83667
|
+
const byName = /* @__PURE__ */ new Map();
|
|
83668
|
+
const failedChecks = [];
|
|
83669
|
+
let checksValid = Boolean(checks);
|
|
83670
|
+
for (const check of checks ?? []) {
|
|
83671
|
+
if (!isRecord6(check) || typeof check.name !== "string" || byName.has(check.name)) {
|
|
83672
|
+
checksValid = false;
|
|
83673
|
+
continue;
|
|
83674
|
+
}
|
|
83675
|
+
byName.set(check.name, check);
|
|
83676
|
+
if (!GATEWAY_READINESS_CHECK_NAMES.includes(check.name))
|
|
83677
|
+
checksValid = false;
|
|
83678
|
+
}
|
|
83679
|
+
checksValid = checksValid && byName.size === GATEWAY_READINESS_CHECK_NAMES.length && GATEWAY_READINESS_CHECK_NAMES.every((name) => byName.has(name) && byName.get(name)?.ok === true);
|
|
83680
|
+
for (const name of GATEWAY_READINESS_CHECK_NAMES) {
|
|
83681
|
+
if (byName.get(name)?.ok !== true)
|
|
83682
|
+
failedChecks.push(name);
|
|
83683
|
+
}
|
|
83684
|
+
if (!checksValid && failedChecks.length === 0)
|
|
83685
|
+
failedChecks.push("checks");
|
|
83686
|
+
if (report?.ready !== true)
|
|
83687
|
+
failedChecks.push("ready");
|
|
83688
|
+
if (report?.launchControl !== "enabled" && !failedChecks.includes("launchControl")) {
|
|
83689
|
+
failedChecks.push("launchControl");
|
|
83690
|
+
}
|
|
83691
|
+
const timestampFresh = isGatewayStatusFresh(report?.generatedAt, now);
|
|
83692
|
+
if (!timestampFresh)
|
|
83693
|
+
failedChecks.push("generatedAt");
|
|
83694
|
+
return {
|
|
83695
|
+
passed: status === 200 && report?.ready === true && report.launchControl === "enabled" && checksValid && timestampFresh,
|
|
83696
|
+
failedChecks,
|
|
83697
|
+
timestampFresh
|
|
83698
|
+
};
|
|
83699
|
+
}
|
|
83700
|
+
|
|
83508
83701
|
// dist/cli.js
|
|
83509
|
-
var
|
|
83510
|
-
var
|
|
83702
|
+
var DEFAULT_GATEWAY_URL2 = "https://zk-credits-gateway.onrender.com";
|
|
83703
|
+
var DEFAULT_PORT2 = 3210;
|
|
83511
83704
|
function stateDirectory() {
|
|
83512
|
-
return process.env.ZK_CREDITS_HOME ||
|
|
83705
|
+
return process.env.ZK_CREDITS_HOME || join8(homedir2(), ".zk-credits");
|
|
83513
83706
|
}
|
|
83514
83707
|
function setupConfigPath(directory = stateDirectory()) {
|
|
83515
|
-
return
|
|
83708
|
+
return join8(directory, "config.json");
|
|
83516
83709
|
}
|
|
83517
83710
|
async function applySavedSetupConfig(environment, directory = stateDirectory()) {
|
|
83518
83711
|
const config = await readSetupConfig(setupConfigPath(directory));
|
|
@@ -83520,7 +83713,7 @@ async function applySavedSetupConfig(environment, directory = stateDirectory())
|
|
|
83520
83713
|
applySetupConfig(environment, config);
|
|
83521
83714
|
}
|
|
83522
83715
|
function loopbackBaseUrl() {
|
|
83523
|
-
const port = Number(process.env.ZK_CREDITS_SIDECAR_PORT ||
|
|
83716
|
+
const port = Number(process.env.ZK_CREDITS_SIDECAR_PORT || DEFAULT_PORT2);
|
|
83524
83717
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
83525
83718
|
throw new Error("ZK_CREDITS_SIDECAR_PORT must be a port between 1 and 65535");
|
|
83526
83719
|
}
|
|
@@ -83555,11 +83748,11 @@ async function chooseSetupCandidate(kind, candidates) {
|
|
|
83555
83748
|
input.close();
|
|
83556
83749
|
}
|
|
83557
83750
|
}
|
|
83558
|
-
async function
|
|
83751
|
+
async function witnessProviderForSource2(source, cachePath) {
|
|
83559
83752
|
if (source.kind === "file") {
|
|
83560
83753
|
let value;
|
|
83561
83754
|
try {
|
|
83562
|
-
value = JSON.parse(await
|
|
83755
|
+
value = JSON.parse(await readFile8(source.path, "utf8"));
|
|
83563
83756
|
} catch {
|
|
83564
83757
|
throw new Error("The Base witness file could not be read as JSON");
|
|
83565
83758
|
}
|
|
@@ -83625,11 +83818,11 @@ async function readHiddenValue(prompt) {
|
|
|
83625
83818
|
});
|
|
83626
83819
|
}
|
|
83627
83820
|
async function readEncryptedCredential(path, password) {
|
|
83628
|
-
const parsed = JSON.parse(await
|
|
83821
|
+
const parsed = JSON.parse(await readFile8(path, "utf8"));
|
|
83629
83822
|
if (parsed.format !== "zk-credits-credential" || parsed.version !== 1 && parsed.version !== 2) {
|
|
83630
83823
|
throw new Error("Credential file is not a supported zk-credits export");
|
|
83631
83824
|
}
|
|
83632
|
-
return
|
|
83825
|
+
return decryptAnyCredentialExport2(parsed, password);
|
|
83633
83826
|
}
|
|
83634
83827
|
function printHelp() {
|
|
83635
83828
|
console.log(`Usage:
|
|
@@ -83637,16 +83830,25 @@ function printHelp() {
|
|
|
83637
83830
|
zk-credits setup codex [--model <model>]
|
|
83638
83831
|
zk-credits codex [codex arguments...]
|
|
83639
83832
|
zk-credits status
|
|
83640
|
-
zk-credits serve [--port <port>]
|
|
83641
|
-
zk-credits
|
|
83833
|
+
zk-credits serve [--port <port>] [--internal-trial-one-proof]
|
|
83834
|
+
zk-credits x402-agent
|
|
83835
|
+
zk-credits founder-demo-agent
|
|
83642
83836
|
eval "$(zk-credits env)"
|
|
83643
83837
|
|
|
83644
83838
|
"zk-credits cline" and the Codex companion configure and launch coding agents
|
|
83645
83839
|
against the x402 zk-prepaid loopback sidecar. The gateway spend path is
|
|
83646
83840
|
non-streaming POST /v1/chat/completions; Codex Responses requests pass through
|
|
83647
83841
|
the sidecar's bounded local compatibility bridge.
|
|
83648
|
-
"zk-credits
|
|
83649
|
-
|
|
83842
|
+
"zk-credits founder-demo-agent" asks for one local task and runs it through
|
|
83843
|
+
the request-aware x402 adapter and local proof engine. It requires explicit
|
|
83844
|
+
confirmation before one billable internal exchange; the task and response are
|
|
83845
|
+
displayed locally and never added to activation evidence.
|
|
83846
|
+
"zk-credits x402-agent" is a small task-running starter for the participant's
|
|
83847
|
+
own x402 agent loop. It asks for tasks locally and sends each through the same
|
|
83848
|
+
request-aware adapter and local proof engine; aggregate metrics stay on the
|
|
83849
|
+
loopback-only authenticated endpoint.
|
|
83850
|
+
"zk-credits serve --internal-trial-one-proof" limits this sidecar process to
|
|
83851
|
+
one authenticated, valid spend request and one local proof attempt.
|
|
83650
83852
|
Set ZK_CREDITS_CREDENTIAL_PATH and BASE_RPC_URL before setup. For Base Sepolia
|
|
83651
83853
|
V2, setup can download the immutable bundle pinned by the package manifest by
|
|
83652
83854
|
using this machine's authenticated GitHub CLI session, then synchronizes the
|
|
@@ -83665,18 +83867,20 @@ async function loadBaseClientRuntime(passwordInput) {
|
|
|
83665
83867
|
if (!artifactDirectory) {
|
|
83666
83868
|
throw new Error("Set ZK_CREDITS_ARTIFACT_DIR to the directory holding the installed pinned proving bundle");
|
|
83667
83869
|
}
|
|
83668
|
-
const
|
|
83669
|
-
|
|
83670
|
-
|
|
83671
|
-
|
|
83672
|
-
|
|
83673
|
-
|
|
83674
|
-
|
|
83870
|
+
const baseRpcUrl = process.env.BASE_RPC_URL;
|
|
83871
|
+
const baseContractAddress = process.env.BASE_PRIVATE_CREDIT_BOND_ADDRESS;
|
|
83872
|
+
const witnessProvider = witnessPath ? createFileWitnessProvider(JSON.parse(await readFile8(witnessPath, "utf8"))) : baseRpcUrl && baseContractAddress ? await witnessProviderForSource2({
|
|
83873
|
+
kind: "base-events",
|
|
83874
|
+
rpcUrl: baseRpcUrl,
|
|
83875
|
+
contractAddress: baseContractAddress,
|
|
83876
|
+
...process.env.BASE_DEPLOYMENT_BLOCK && /^\d+$/u.test(process.env.BASE_DEPLOYMENT_BLOCK) ? { deploymentBlock: process.env.BASE_DEPLOYMENT_BLOCK } : {},
|
|
83877
|
+
...process.env.BASE_CONFIRMATIONS && /^\d+$/u.test(process.env.BASE_CONFIRMATIONS) ? { confirmations: process.env.BASE_CONFIRMATIONS } : {}
|
|
83878
|
+
}, join8(stateDirectory(), "base-event-sync.json")) : (() => {
|
|
83675
83879
|
throw new Error("Set ZK_CREDITS_WITNESS_PATH or configure BASE_RPC_URL and BASE_PRIVATE_CREDIT_BOND_ADDRESS");
|
|
83676
83880
|
})();
|
|
83677
83881
|
const proofMetrics = createBaseProofMetrics();
|
|
83678
|
-
const exchangeMetrics =
|
|
83679
|
-
const slotLedger = await BaseSlotLedger.open({ path:
|
|
83882
|
+
const exchangeMetrics = createZkPrepaidLifecycleMetrics2();
|
|
83883
|
+
const slotLedger = await BaseSlotLedger.open({ path: join8(stateDirectory(), "base-slots.json") });
|
|
83680
83884
|
const prove = await createPinnedBaseProofGenerator({ artifactDirectory, metrics: proofMetrics });
|
|
83681
83885
|
validateBaseCreditWitness(await witnessProvider.witnessForCredential(credential));
|
|
83682
83886
|
return { credential, witnessProvider, slotLedger, proofMetrics, exchangeMetrics, prove };
|
|
@@ -83700,15 +83904,14 @@ var GATEWAY_COUNTER_NAMES = [
|
|
|
83700
83904
|
"request_rejected"
|
|
83701
83905
|
];
|
|
83702
83906
|
var GATEWAY_CLAIM_COUNT_NAMES = ["reserved", "ready", "committed", "cancelled"];
|
|
83703
|
-
|
|
83704
|
-
function isRecord6(value) {
|
|
83907
|
+
function isRecord7(value) {
|
|
83705
83908
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
83706
83909
|
}
|
|
83707
83910
|
function safeCount(value) {
|
|
83708
83911
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
83709
83912
|
}
|
|
83710
83913
|
function gatewayOrigin() {
|
|
83711
|
-
const origin = new URL(process.env.ZK_CREDITS_GATEWAY_URL ||
|
|
83914
|
+
const origin = new URL(process.env.ZK_CREDITS_GATEWAY_URL || DEFAULT_GATEWAY_URL2);
|
|
83712
83915
|
if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/") {
|
|
83713
83916
|
throw new Error("The internal trial requires a plain HTTPS gateway origin");
|
|
83714
83917
|
}
|
|
@@ -83733,14 +83936,10 @@ async function requireGatewayKnownRoot2(root) {
|
|
|
83733
83936
|
}
|
|
83734
83937
|
async function gatewayReadiness(origin) {
|
|
83735
83938
|
const response = await readGatewayJson(new URL("/ready", origin), { accept: "application/json" });
|
|
83736
|
-
const
|
|
83737
|
-
const checks = Array.isArray(report?.checks) ? report.checks : [];
|
|
83738
|
-
const failedChecks = checks.flatMap((check) => isRecord6(check) && check.ok === true ? [] : [isRecord6(check) && typeof check.name === "string" && GATEWAY_READINESS_CHECK_NAMES.has(check.name) ? check.name : "unknown"]);
|
|
83739
|
-
const hasLaunchCheck = checks.some((check) => isRecord6(check) && check.name === "launchControl" && check.ok === true);
|
|
83939
|
+
const gate = evaluateGatewayReadiness(response.status, response.body);
|
|
83740
83940
|
return {
|
|
83741
83941
|
status: response.status,
|
|
83742
|
-
|
|
83743
|
-
failedChecks
|
|
83942
|
+
...gate
|
|
83744
83943
|
};
|
|
83745
83944
|
}
|
|
83746
83945
|
async function gatewayTrialSnapshot(origin, token) {
|
|
@@ -83748,12 +83947,12 @@ async function gatewayTrialSnapshot(origin, token) {
|
|
|
83748
83947
|
accept: "application/json",
|
|
83749
83948
|
authorization: `Bearer ${token}`
|
|
83750
83949
|
});
|
|
83751
|
-
const body =
|
|
83752
|
-
const launch =
|
|
83753
|
-
const base =
|
|
83754
|
-
const spend =
|
|
83755
|
-
const rawMetrics =
|
|
83756
|
-
const rawClaims =
|
|
83950
|
+
const body = isRecord7(response.body) ? response.body : void 0;
|
|
83951
|
+
const launch = isRecord7(body?.launchControl) ? body.launchControl : void 0;
|
|
83952
|
+
const base = isRecord7(body?.base) ? body.base : void 0;
|
|
83953
|
+
const spend = isRecord7(body?.spend) ? body.spend : void 0;
|
|
83954
|
+
const rawMetrics = isRecord7(body?.metrics) ? body.metrics : void 0;
|
|
83955
|
+
const rawClaims = isRecord7(body?.claims) ? body.claims : void 0;
|
|
83757
83956
|
const metrics = {};
|
|
83758
83957
|
const claims = {};
|
|
83759
83958
|
let countersValid = Boolean(rawMetrics && rawClaims);
|
|
@@ -83779,7 +83978,7 @@ async function gatewayTrialSnapshot(origin, token) {
|
|
|
83779
83978
|
return {
|
|
83780
83979
|
status: response.status,
|
|
83781
83980
|
...snapshot ? { snapshot } : {},
|
|
83782
|
-
gatePassed: response.status === 200 && body?.network ===
|
|
83981
|
+
gatePassed: response.status === 200 && isGatewayStatusFresh(body?.generatedAt) && body?.network === BASE_SEPOLIA_NETWORK3 && launch?.state === "enabled" && knownRoot && safeCount(base?.knownRootCount) !== void 0 && (safeCount(base?.knownRootCount) ?? 0) > 0 && lag !== void 0 && lag <= 300n && headroom(spend?.dailyHeadroomMicroUsd) && headroom(spend?.rollingHeadroomMicroUsd) && countersValid
|
|
83783
83982
|
};
|
|
83784
83983
|
}
|
|
83785
83984
|
async function confirmDirectTrial() {
|
|
@@ -83793,27 +83992,110 @@ async function confirmDirectTrial() {
|
|
|
83793
83992
|
input.close();
|
|
83794
83993
|
}
|
|
83795
83994
|
}
|
|
83995
|
+
async function readFounderDemoTask() {
|
|
83996
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
83997
|
+
throw new Error("the founder demo requires a local interactive terminal");
|
|
83998
|
+
}
|
|
83999
|
+
const input = createInterface({ input: process.stdin, output: process.stdout });
|
|
84000
|
+
try {
|
|
84001
|
+
const task = (await input.question("Task for the founder x402 demo agent (up to 4000 characters): ")).trim();
|
|
84002
|
+
if (task.length === 0 || task.length > 4e3) {
|
|
84003
|
+
throw new Error("Task must contain between 1 and 4000 characters");
|
|
84004
|
+
}
|
|
84005
|
+
return task;
|
|
84006
|
+
} finally {
|
|
84007
|
+
input.close();
|
|
84008
|
+
}
|
|
84009
|
+
}
|
|
84010
|
+
async function readX402AgentTask() {
|
|
84011
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
84012
|
+
throw new Error("the x402 starter agent requires a local interactive terminal");
|
|
84013
|
+
}
|
|
84014
|
+
const input = createInterface({ input: process.stdin, output: process.stdout });
|
|
84015
|
+
try {
|
|
84016
|
+
const task = (await input.question("Task for your x402 agent (or :quit): ")).trim();
|
|
84017
|
+
if (task === ":quit")
|
|
84018
|
+
return null;
|
|
84019
|
+
if (task.length === 0 || task.length > 4e3) {
|
|
84020
|
+
throw new Error("Task must contain between 1 and 4000 characters");
|
|
84021
|
+
}
|
|
84022
|
+
return task;
|
|
84023
|
+
} finally {
|
|
84024
|
+
input.close();
|
|
84025
|
+
}
|
|
84026
|
+
}
|
|
84027
|
+
async function runX402Agent() {
|
|
84028
|
+
const gateway = gatewayOrigin();
|
|
84029
|
+
const runtime = await createLocalX402Agent({
|
|
84030
|
+
credentialPassword: await readHiddenValue("Credential backup password: ")
|
|
84031
|
+
});
|
|
84032
|
+
const url = new URL("/v1/chat/completions", gateway).toString();
|
|
84033
|
+
console.log(`Local aggregate metrics: ${runtime.metricsUrl}`);
|
|
84034
|
+
console.log("Enter one task at a time. Each task can spend one founder-provisioned test credit.");
|
|
84035
|
+
try {
|
|
84036
|
+
while (true) {
|
|
84037
|
+
const task = await readX402AgentTask();
|
|
84038
|
+
if (task === null)
|
|
84039
|
+
break;
|
|
84040
|
+
const response = await runtime.client.fetch(url, {
|
|
84041
|
+
method: "POST",
|
|
84042
|
+
headers: { "content-type": "application/json" },
|
|
84043
|
+
body: buildBaseRegisteredTrialRequestBody(task)
|
|
84044
|
+
});
|
|
84045
|
+
await displayAgentResponse(response);
|
|
84046
|
+
if (!response.ok)
|
|
84047
|
+
console.log(`Request ended with HTTP ${response.status}.`);
|
|
84048
|
+
}
|
|
84049
|
+
} finally {
|
|
84050
|
+
await runtime.close();
|
|
84051
|
+
}
|
|
84052
|
+
}
|
|
84053
|
+
async function displayAgentResponse(response) {
|
|
84054
|
+
let content;
|
|
84055
|
+
try {
|
|
84056
|
+
const body = await response.json();
|
|
84057
|
+
if (isRecord7(body) && Array.isArray(body.choices) && isRecord7(body.choices[0])) {
|
|
84058
|
+
const message = body.choices[0].message;
|
|
84059
|
+
if (isRecord7(message))
|
|
84060
|
+
content = message.content;
|
|
84061
|
+
}
|
|
84062
|
+
} catch {
|
|
84063
|
+
}
|
|
84064
|
+
console.log("\nAgent response (shown locally only):");
|
|
84065
|
+
if (typeof content === "string") {
|
|
84066
|
+
console.log(content);
|
|
84067
|
+
return;
|
|
84068
|
+
}
|
|
84069
|
+
if (Array.isArray(content)) {
|
|
84070
|
+
const textParts = content.filter((part) => isRecord7(part)).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text);
|
|
84071
|
+
if (textParts.length > 0) {
|
|
84072
|
+
console.log(textParts.join("\n"));
|
|
84073
|
+
return;
|
|
84074
|
+
}
|
|
84075
|
+
}
|
|
84076
|
+
console.log("[The response completed, but its text content was not available for local display.]");
|
|
84077
|
+
}
|
|
83796
84078
|
function gatewayCounterDelta(before, after) {
|
|
83797
84079
|
return {
|
|
83798
84080
|
metrics: Object.fromEntries(GATEWAY_COUNTER_NAMES.map((name) => [name, after.metrics[name] - before.metrics[name]])),
|
|
83799
84081
|
claims: Object.fromEntries(GATEWAY_CLAIM_COUNT_NAMES.map((name) => [name, after.claims[name] - before.claims[name]]))
|
|
83800
84082
|
};
|
|
83801
84083
|
}
|
|
83802
|
-
async function trialRegisteredAdapter() {
|
|
84084
|
+
async function trialRegisteredAdapter(task) {
|
|
83803
84085
|
if (!await confirmDirectTrial()) {
|
|
83804
|
-
console.log(JSON.stringify({ path: "
|
|
84086
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "not_run" }));
|
|
83805
84087
|
return;
|
|
83806
84088
|
}
|
|
83807
84089
|
try {
|
|
83808
84090
|
const runtime = await loadBaseClientRuntime();
|
|
83809
84091
|
if (runtime.credential.tierId !== 0 || runtime.credential.deploymentDomain !== "84532" || runtime.credential.expiry <= Math.floor(Date.now() / 1e3)) {
|
|
83810
|
-
console.log(JSON.stringify({ path: "
|
|
84092
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "stopped", failurePhase: "credential_gate" }));
|
|
83811
84093
|
return;
|
|
83812
84094
|
}
|
|
83813
84095
|
const startingSlots = runtime.slotLedger.snapshot();
|
|
83814
84096
|
if (startingSlots.committed >= startingSlots.capacity) {
|
|
83815
84097
|
console.log(JSON.stringify({
|
|
83816
|
-
path: "
|
|
84098
|
+
path: "founder-demo-agent",
|
|
83817
84099
|
status: "stopped",
|
|
83818
84100
|
failurePhase: "local_credit_gate",
|
|
83819
84101
|
localCredits: { capacity: startingSlots.capacity, committed: startingSlots.committed, available: 0 }
|
|
@@ -83823,7 +84105,7 @@ async function trialRegisteredAdapter() {
|
|
|
83823
84105
|
const gateway = gatewayOrigin();
|
|
83824
84106
|
const adminToken = process.env.BILLING_INTERNAL_TOKEN || await readHiddenValue("Gateway admin token: ");
|
|
83825
84107
|
if (!adminToken.trim()) {
|
|
83826
|
-
console.log(JSON.stringify({ path: "
|
|
84108
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "stopped", failurePhase: "admin_auth" }));
|
|
83827
84109
|
return;
|
|
83828
84110
|
}
|
|
83829
84111
|
const lifecycle = createNodeSidecarLifecycle({
|
|
@@ -83833,40 +84115,36 @@ async function trialRegisteredAdapter() {
|
|
|
83833
84115
|
logPath: sidecarStatePaths(stateDirectory()).logPath,
|
|
83834
84116
|
cliEntryPath: process.argv[1] ?? ""
|
|
83835
84117
|
});
|
|
83836
|
-
const codexHome = resolveCodexHome(process.env,
|
|
84118
|
+
const codexHome = resolveCodexHome(process.env, homedir2());
|
|
83837
84119
|
const [sidecarRunning, codexProfileInstalled] = await Promise.all([
|
|
83838
84120
|
lifecycle.isHealthy(),
|
|
83839
84121
|
isCodexProfileInstalled(codexHome)
|
|
83840
84122
|
]);
|
|
83841
84123
|
const launcherStatus = { codexProfileInstalled, sidecarRunning };
|
|
83842
84124
|
if (sidecarRunning) {
|
|
83843
|
-
console.log(JSON.stringify({ path: "
|
|
84125
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "stopped", failurePhase: "sidecar_running", launcherStatus }));
|
|
83844
84126
|
return;
|
|
83845
84127
|
}
|
|
83846
84128
|
const witness = await runtime.witnessProvider.witnessForCredential(runtime.credential);
|
|
83847
84129
|
const readiness = await gatewayReadiness(gateway);
|
|
83848
84130
|
if (!readiness.passed) {
|
|
83849
|
-
console.log(JSON.stringify({ path: "
|
|
84131
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "stopped", failurePhase: "readiness", launcherStatus, readiness }));
|
|
83850
84132
|
return;
|
|
83851
84133
|
}
|
|
83852
84134
|
const adminBefore = await gatewayTrialSnapshot(gateway, adminToken);
|
|
83853
84135
|
if (!adminBefore.gatePassed || !adminBefore.snapshot) {
|
|
83854
|
-
console.log(JSON.stringify({ path: "
|
|
84136
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "stopped", failurePhase: "admin_status", launcherStatus, readiness, adminStatus: adminBefore.status }));
|
|
83855
84137
|
return;
|
|
83856
84138
|
}
|
|
83857
84139
|
if (witness.root !== adminBefore.snapshot.currentRoot) {
|
|
83858
|
-
console.log(JSON.stringify({ path: "
|
|
84140
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "stopped", failurePhase: "root_mismatch", launcherStatus, readiness, adminStatus: adminBefore.status }));
|
|
83859
84141
|
return;
|
|
83860
84142
|
}
|
|
83861
84143
|
const baselineSlots = runtime.slotLedger.snapshot();
|
|
83862
84144
|
const baselineProof = runtime.proofMetrics.snapshot();
|
|
83863
84145
|
const baselineLifecycle = runtime.exchangeMetrics.snapshot();
|
|
83864
84146
|
const requestUrl = new URL("/v1/chat/completions", gateway).toString();
|
|
83865
|
-
const requestBody =
|
|
83866
|
-
model: "deepseek/deepseek-v4-flash",
|
|
83867
|
-
messages: [{ role: "user", content: "Reply with exactly: internal trial complete." }],
|
|
83868
|
-
stream: false
|
|
83869
|
-
});
|
|
84147
|
+
const requestBody = buildBaseRegisteredTrialRequestBody(task);
|
|
83870
84148
|
const exchange = await runBaseRegisteredTrialExchange({
|
|
83871
84149
|
url: requestUrl,
|
|
83872
84150
|
body: requestBody,
|
|
@@ -83875,7 +84153,8 @@ async function trialRegisteredAdapter() {
|
|
|
83875
84153
|
witnessProvider: runtime.witnessProvider,
|
|
83876
84154
|
prove: runtime.prove,
|
|
83877
84155
|
slotLedger: runtime.slotLedger,
|
|
83878
|
-
lifecycle: runtime.exchangeMetrics.observe
|
|
84156
|
+
lifecycle: runtime.exchangeMetrics.observe,
|
|
84157
|
+
onResponse: displayAgentResponse
|
|
83879
84158
|
});
|
|
83880
84159
|
const adminAfter = await gatewayTrialSnapshot(gateway, adminToken);
|
|
83881
84160
|
const proofAfter = runtime.proofMetrics.snapshot();
|
|
@@ -83897,7 +84176,7 @@ async function trialRegisteredAdapter() {
|
|
|
83897
84176
|
const gatewayCountersMatch = Boolean(counterDelta) && expectedGatewayCounters.every((name) => counterDelta.metrics[name] === 1) && Object.entries(counterDelta?.metrics ?? {}).every(([name, value]) => expectedGatewayCounters.includes(name) || value === 0) && counterDelta?.claims.committed === 1 && Object.entries(counterDelta?.claims ?? {}).every(([name, value]) => name === "committed" || value === 0);
|
|
83898
84177
|
const failurePhase = exchange.failurePhase ?? (!exchange.responseSucceeded ? "response_not_ok" : void 0) ?? (adminAfter.status !== 200 || !adminAfter.snapshot ? "postflight_admin_status" : void 0) ?? (!gatewayCountersMatch ? "gateway_counter_delta" : void 0);
|
|
83899
84178
|
console.log(JSON.stringify({
|
|
83900
|
-
path: "
|
|
84179
|
+
path: "founder-demo-agent",
|
|
83901
84180
|
readiness: { status: readiness.status, passed: readiness.passed, failedChecks: readiness.failedChecks },
|
|
83902
84181
|
launcherStatus,
|
|
83903
84182
|
adminStatus: { before: adminBefore.status, after: adminAfter.status },
|
|
@@ -83924,11 +84203,12 @@ async function trialRegisteredAdapter() {
|
|
|
83924
84203
|
failurePhase
|
|
83925
84204
|
}));
|
|
83926
84205
|
} catch {
|
|
83927
|
-
console.log(JSON.stringify({ path: "
|
|
84206
|
+
console.log(JSON.stringify({ path: "founder-demo-agent", status: "stopped", failurePhase: "local_setup" }));
|
|
83928
84207
|
}
|
|
83929
84208
|
}
|
|
83930
84209
|
async function serve(args, passwordInput) {
|
|
83931
84210
|
const port = readPort(args);
|
|
84211
|
+
const internalTrialOneProof = args.includes("--internal-trial-one-proof");
|
|
83932
84212
|
const statePaths = sidecarStatePaths(stateDirectory());
|
|
83933
84213
|
const localToken = createLoopbackToken();
|
|
83934
84214
|
const { credential, witnessProvider, proofMetrics, exchangeMetrics, slotLedger, prove } = await loadBaseClientRuntime(passwordInput);
|
|
@@ -83937,13 +84217,15 @@ async function serve(args, passwordInput) {
|
|
|
83937
84217
|
witnessProvider,
|
|
83938
84218
|
prove,
|
|
83939
84219
|
slotLedger,
|
|
84220
|
+
internalTrialOneProof,
|
|
83940
84221
|
lifecycle: exchangeMetrics.observe
|
|
83941
84222
|
});
|
|
83942
|
-
const gatewayBaseUrl = process.env.ZK_CREDITS_GATEWAY_URL ||
|
|
84223
|
+
const gatewayBaseUrl = process.env.ZK_CREDITS_GATEWAY_URL || DEFAULT_GATEWAY_URL2;
|
|
83943
84224
|
const sidecar = createSidecarServer({
|
|
83944
84225
|
localToken,
|
|
83945
84226
|
gatewayBaseUrl,
|
|
83946
84227
|
prepaidClient: prepaid.client,
|
|
84228
|
+
internalTrialOneProof,
|
|
83947
84229
|
metrics: () => ({ ...proofMetrics.snapshot(), exchange: exchangeMetrics.snapshot() })
|
|
83948
84230
|
});
|
|
83949
84231
|
let address2;
|
|
@@ -83984,12 +84266,21 @@ async function main() {
|
|
|
83984
84266
|
await serve(args.slice(1).filter((argument) => argument !== "--credential-password-stdin"), passwordFromStdin);
|
|
83985
84267
|
return;
|
|
83986
84268
|
}
|
|
83987
|
-
if (args[0] === "
|
|
83988
|
-
|
|
84269
|
+
if (args[0] === "founder-demo-agent") {
|
|
84270
|
+
if (args.length !== 1)
|
|
84271
|
+
throw new Error("founder-demo-agent does not accept arguments; it reads the task locally");
|
|
84272
|
+
const task = await readFounderDemoTask();
|
|
84273
|
+
await trialRegisteredAdapter(task);
|
|
84274
|
+
return;
|
|
84275
|
+
}
|
|
84276
|
+
if (args[0] === "x402-agent") {
|
|
84277
|
+
if (args.length !== 1)
|
|
84278
|
+
throw new Error("x402-agent does not accept arguments; it reads tasks locally");
|
|
84279
|
+
await runX402Agent();
|
|
83989
84280
|
return;
|
|
83990
84281
|
}
|
|
83991
84282
|
const statePaths = sidecarStatePaths(sidecarHome);
|
|
83992
|
-
const codexHome = resolveCodexHome(process.env,
|
|
84283
|
+
const codexHome = resolveCodexHome(process.env, homedir2());
|
|
83993
84284
|
const cliEntryPath = process.argv[1];
|
|
83994
84285
|
if (!cliEntryPath)
|
|
83995
84286
|
throw new Error("Unable to resolve the zk-credits executable path");
|
|
@@ -84018,7 +84309,7 @@ async function main() {
|
|
|
84018
84309
|
if (!path)
|
|
84019
84310
|
return false;
|
|
84020
84311
|
try {
|
|
84021
|
-
await
|
|
84312
|
+
await readFile8(path);
|
|
84022
84313
|
return true;
|
|
84023
84314
|
} catch {
|
|
84024
84315
|
return false;
|
|
@@ -84033,12 +84324,12 @@ async function main() {
|
|
|
84033
84324
|
const manifest = await loadCircuitManifest();
|
|
84034
84325
|
const config = await resolveSetupInputs({
|
|
84035
84326
|
environment: process.env,
|
|
84036
|
-
homeDirectory:
|
|
84327
|
+
homeDirectory: homedir2(),
|
|
84037
84328
|
stateDirectory: sidecarHome,
|
|
84038
84329
|
configPath: setupConfigPath(sidecarHome),
|
|
84039
84330
|
manifest,
|
|
84040
84331
|
validateWitness: async (source) => {
|
|
84041
|
-
const provider = await
|
|
84332
|
+
const provider = await witnessProviderForSource2(source, join8(stateDirectory(), "base-event-sync.json"));
|
|
84042
84333
|
const witness = validateBaseCreditWitness(await provider.witnessForCredential(credential));
|
|
84043
84334
|
if (manifest.deployment)
|
|
84044
84335
|
await requireGatewayKnownRoot2(witness.root);
|