@relyon/kit 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +75 -0
- package/CHANGELOG.md +1053 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +239 -0
- package/README.md +117 -2
- package/dist/adapters/express.d.ts +39 -0
- package/dist/adapters/express.js +106 -0
- package/dist/adapters/hono.d.ts +16 -0
- package/dist/adapters/hono.js +15 -0
- package/dist/adapters/next.d.ts +29 -0
- package/dist/adapters/next.js +38 -0
- package/dist/agent-card.d.ts +14 -0
- package/dist/agent-card.js +58 -0
- package/dist/agent-docs.d.ts +36 -0
- package/dist/agent-docs.js +78 -0
- package/dist/agent-hooks.d.ts +66 -0
- package/dist/agent-hooks.js +280 -0
- package/dist/agents.d.ts +24 -0
- package/dist/agents.js +120 -0
- package/dist/api-key.d.ts +6 -0
- package/dist/api-key.js +33 -0
- package/dist/cache.d.ts +46 -0
- package/dist/cache.js +86 -0
- package/dist/cart-tokens.d.ts +31 -0
- package/dist/cart-tokens.js +58 -0
- package/dist/cart-transfer.d.ts +95 -0
- package/dist/cart-transfer.js +387 -0
- package/dist/catalog-enrichment.d.ts +6 -0
- package/dist/catalog-enrichment.js +71 -0
- package/dist/catalog-reads.d.ts +126 -0
- package/dist/catalog-reads.js +104 -0
- package/dist/catalog.d.ts +78 -0
- package/dist/catalog.js +288 -0
- package/dist/charge-claims.d.ts +11 -0
- package/dist/charge-claims.js +47 -0
- package/dist/check.d.ts +44 -0
- package/dist/check.js +152 -0
- package/dist/checklist-manifest.d.ts +72 -0
- package/dist/checklist-manifest.js +341 -0
- package/dist/checkout.d.ts +222 -0
- package/dist/checkout.js +353 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +727 -0
- package/dist/confirmation.d.ts +78 -0
- package/dist/confirmation.js +124 -0
- package/dist/context.d.ts +81 -0
- package/dist/context.js +10 -0
- package/dist/discovery.d.ts +151 -0
- package/dist/discovery.js +346 -0
- package/dist/doctor-cart-transfer.d.ts +33 -0
- package/dist/doctor-cart-transfer.js +186 -0
- package/dist/doctor-catalog.d.ts +8 -0
- package/dist/doctor-catalog.js +47 -0
- package/dist/doctor-evidence.d.ts +22 -0
- package/dist/doctor-evidence.js +57 -0
- package/dist/doctor-merchant.d.ts +48 -0
- package/dist/doctor-merchant.js +74 -0
- package/dist/doctor-source.d.ts +5 -0
- package/dist/doctor-source.js +142 -0
- package/dist/doctor-variants.d.ts +70 -0
- package/dist/doctor-variants.js +102 -0
- package/dist/doctor.d.ts +215 -0
- package/dist/doctor.js +1689 -0
- package/dist/events.d.ts +95 -0
- package/dist/events.js +200 -0
- package/dist/feed-mapping.d.ts +114 -0
- package/dist/feed-mapping.js +152 -0
- package/dist/feed-values.d.ts +13 -0
- package/dist/feed-values.js +40 -0
- package/dist/feeds.d.ts +104 -0
- package/dist/feeds.js +366 -0
- package/dist/identify.d.ts +102 -0
- package/dist/identify.js +124 -0
- package/dist/identity.d.ts +37 -0
- package/dist/identity.js +54 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +41 -0
- package/dist/init.d.ts +157 -0
- package/dist/init.js +912 -0
- package/dist/kit-config.d.ts +19 -0
- package/dist/kit-config.js +43 -0
- package/dist/kit-environment.d.ts +20 -0
- package/dist/kit-environment.js +32 -0
- package/dist/kit-updates.d.ts +47 -0
- package/dist/kit-updates.js +77 -0
- package/dist/kit-version-project.d.ts +18 -0
- package/dist/kit-version-project.js +214 -0
- package/dist/kit-version.d.ts +37 -0
- package/dist/kit-version.js +162 -0
- package/dist/kit.d.ts +516 -0
- package/dist/kit.js +1309 -0
- package/dist/layers/pages.d.ts +3 -0
- package/dist/layers/pages.js +5 -0
- package/dist/layers/payments.d.ts +7 -0
- package/dist/layers/payments.js +9 -0
- package/dist/layers/products.d.ts +10 -0
- package/dist/layers/products.js +13 -0
- package/dist/live.d.ts +13 -0
- package/dist/live.js +52 -0
- package/dist/mcp.d.ts +270 -0
- package/dist/mcp.js +312 -0
- package/dist/next-steps.d.ts +101 -0
- package/dist/next-steps.js +257 -0
- package/dist/order-pending.d.ts +57 -0
- package/dist/order-pending.js +127 -0
- package/dist/orders.d.ts +12 -0
- package/dist/orders.js +21 -0
- package/dist/payments-init.d.ts +19 -0
- package/dist/payments-init.js +70 -0
- package/dist/payments-routes.d.ts +54 -0
- package/dist/payments-routes.js +123 -0
- package/dist/payments.d.ts +165 -0
- package/dist/payments.js +192 -0
- package/dist/pnpm-workspace.d.ts +58 -0
- package/dist/pnpm-workspace.js +250 -0
- package/dist/policies.d.ts +111 -0
- package/dist/policies.js +317 -0
- package/dist/preview-hosts.d.ts +64 -0
- package/dist/preview-hosts.js +175 -0
- package/dist/private-config.d.ts +169 -0
- package/dist/private-config.js +820 -0
- package/dist/progress.d.ts +54 -0
- package/dist/progress.js +153 -0
- package/dist/protocol-inputs.d.ts +22 -0
- package/dist/protocol-inputs.js +151 -0
- package/dist/public-origin.d.ts +50 -0
- package/dist/public-origin.js +180 -0
- package/dist/refusals.d.ts +86 -0
- package/dist/refusals.js +157 -0
- package/dist/relay.d.ts +107 -0
- package/dist/relay.js +655 -0
- package/dist/release-notes.d.ts +2 -0
- package/dist/release-notes.js +290 -0
- package/dist/relyon-cart-tokens.d.ts +101 -0
- package/dist/relyon-cart-tokens.js +521 -0
- package/dist/relyon.d.ts +141 -0
- package/dist/relyon.js +238 -0
- package/dist/robots.d.ts +27 -0
- package/dist/robots.js +127 -0
- package/dist/rules.d.ts +144 -0
- package/dist/rules.js +347 -0
- package/dist/sdk/generated/public-api.d.ts +4816 -0
- package/dist/sdk/generated/public-api.js +1 -0
- package/dist/sdk/index.d.ts +24 -0
- package/dist/sdk/index.js +34 -0
- package/dist/sdk/signatures.d.ts +17 -0
- package/dist/sdk/signatures.js +33 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.js +94 -0
- package/dist/signatures.d.ts +112 -0
- package/dist/signatures.js +443 -0
- package/dist/state.d.ts +185 -0
- package/dist/state.js +96 -0
- package/dist/store-payments.d.ts +48 -0
- package/dist/store-payments.js +143 -0
- package/dist/structured-fields.d.ts +26 -0
- package/dist/structured-fields.js +200 -0
- package/dist/templates.d.ts +19 -0
- package/dist/templates.js +193 -0
- package/dist/test-checkout-command.d.ts +32 -0
- package/dist/test-checkout-command.js +161 -0
- package/dist/test-checkout.d.ts +88 -0
- package/dist/test-checkout.js +292 -0
- package/dist/types.d.ts +103 -0
- package/dist/types.js +18 -0
- package/dist/ucp-versions.d.ts +57 -0
- package/dist/ucp-versions.js +129 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.js +68 -0
- package/dist/variants.d.ts +67 -0
- package/dist/variants.js +146 -0
- package/dist/version.d.ts +9 -0
- package/dist/version.js +10 -0
- package/dist/waiting.d.ts +43 -0
- package/dist/waiting.js +57 -0
- package/dist/webhook-command.d.ts +48 -0
- package/dist/webhook-command.js +367 -0
- package/dist/webhook-registration.d.ts +47 -0
- package/dist/webhook-registration.js +69 -0
- package/dist/webmcp-schema.d.ts +14 -0
- package/dist/webmcp-schema.js +140 -0
- package/dist/webmcp-script.d.ts +3 -0
- package/dist/webmcp-script.js +176 -0
- package/dist/webmcp-store.d.ts +102 -0
- package/dist/webmcp-store.js +116 -0
- package/dist/webmcp.d.ts +242 -0
- package/dist/webmcp.js +866 -0
- package/dist/wire-names.d.ts +85 -0
- package/dist/wire-names.js +109 -0
- package/package.json +118 -4
- package/release-notes.json +290 -0
- package/scripts/install-notice.cjs +7 -0
- package/skills/relyon-agents/SKILL.md +327 -0
- package/skills/relyon-catalog/SKILL.md +499 -0
- package/skills/relyon-catalog/references/example-store.md +218 -0
- package/skills/relyon-checkout/SKILL.md +603 -0
- package/skills/relyon-checkout/references/checkout-flow.md +257 -0
- package/skills/relyon-checkout/references/checkout-page.md +315 -0
- package/skills/relyon-go-live/SKILL.md +344 -0
- package/skills/relyon-orders/SKILL.md +191 -0
- package/skills/relyon-orders/references/webhook-receiver.md +113 -0
- package/skills/relyon-payments/SKILL.md +117 -0
- package/skills/relyon-setup/SKILL.md +1061 -0
- package/skills/relyon-setup/references/QUICKSTART.md +239 -0
- package/skills/relyon-setup/references/durable-state.md +209 -0
- package/skills/relyon-setup/references/express-server.md +388 -0
- package/skills/relyon-setup/references/next-app-router.md +251 -0
- package/templates/common/STORE-README.md +67 -0
- package/templates/common/gitignore +8 -0
- package/templates/common/scripts/check-pricing.ts +22 -0
- package/templates/common/scripts/serve.mjs +13 -0
- package/templates/common/server/catalog.ts +79 -0
- package/templates/common/server/checkout-flow.d.ts +34 -0
- package/templates/common/server/pages.ts +184 -0
- package/templates/common/server/storage.ts +114 -0
- package/templates/common/server/store.ts +67 -0
- package/templates/express/server/express.ts +20 -0
- package/templates/express/tsconfig.build.json +6 -0
- package/templates/express/tsconfig.json +9 -0
- package/templates/next/app/[[...path]]/route.ts +24 -0
- package/templates/next/next.config.mjs +19 -0
- package/templates/next/tsconfig.json +12 -0
- package/templates/payments/express.ts +39 -0
- package/templates/payments/next.ts +38 -0
- package/templates/payments/node.ts +39 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// `/.well-known/agent-card.json`: an A2A-style agent card that tells shopping
|
|
2
|
+
// agents how this store sells, claiming only what works today. The store
|
|
3
|
+
// runs no A2A message endpoint; the card points at the protocols it does
|
|
4
|
+
// serve (UCP, ACP and MCP) and declares the AP2 extension because Relyon
|
|
5
|
+
// verifies an AP2 checkout mandate an agent presents on UCP checkout.
|
|
6
|
+
import { KIT_VERSION } from "./version.js";
|
|
7
|
+
/** The AP2 extension URI agent cards declare (AP2 v0.1). */
|
|
8
|
+
export const AP2_EXTENSION_URI = "https://github.com/google-agentic-commerce/ap2/tree/v0.1";
|
|
9
|
+
export function agentCard(input) {
|
|
10
|
+
const { origin, paths, livemode } = input;
|
|
11
|
+
const mode = livemode
|
|
12
|
+
? "Live: real payments, only where Relyon has approved the store and the agent's channel."
|
|
13
|
+
: "Test mode: no real charges.";
|
|
14
|
+
const payment = `Payment always happens on the store's own checkout page (${origin}${paths.checkout}): agents never send card details. ${mode}`;
|
|
15
|
+
return {
|
|
16
|
+
protocolVersion: "0.3.0",
|
|
17
|
+
name: input.store.name,
|
|
18
|
+
description: `${input.store.description ? `${input.store.description} ` : ""}How shopping agents buy from this store. This store has no A2A message endpoint: agents use UCP, ACP or MCP at the URLs below.`,
|
|
19
|
+
url: `${origin}/`,
|
|
20
|
+
version: KIT_VERSION,
|
|
21
|
+
documentationUrl: `${origin}${paths.llmsTxt}`,
|
|
22
|
+
provider: { organization: input.store.name, url: `${origin}/` },
|
|
23
|
+
capabilities: {
|
|
24
|
+
streaming: false,
|
|
25
|
+
pushNotifications: false,
|
|
26
|
+
extensions: [{
|
|
27
|
+
uri: AP2_EXTENSION_URI,
|
|
28
|
+
description: "AP2 checkout mandates on UCP checkout: Relyon verifies a checkout mandate an agent presents when it completes a UCP checkout. A mandate is required only when the store's agent rules say so; the UCP profile then lists dev.ucp.common.payment.ap2_mandate.",
|
|
29
|
+
required: false,
|
|
30
|
+
params: { roles: ["merchant"] },
|
|
31
|
+
}],
|
|
32
|
+
},
|
|
33
|
+
defaultInputModes: ["application/json"],
|
|
34
|
+
defaultOutputModes: ["application/json"],
|
|
35
|
+
skills: [
|
|
36
|
+
{
|
|
37
|
+
id: "browse-products", name: "Browse products",
|
|
38
|
+
description: `Search and read the catalog: MCP tools search_products and get_product at ${origin}${paths.mcp}, the product sitemap at ${origin}${paths.sitemap}${input.feedUrls?.length ? ", and the product feeds listed in llms.txt" : ""}.`,
|
|
39
|
+
tags: ["catalog", "mcp"],
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
id: "ucp-checkout", name: "UCP checkout",
|
|
43
|
+
description: `Checkout through UCP; the business profile is at ${origin}/.well-known/ucp. ${payment}`,
|
|
44
|
+
tags: ["checkout", "ucp", "ap2"],
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
id: "acp-checkout", name: "ACP checkout",
|
|
48
|
+
description: `Agentic Commerce Protocol checkout sessions at ${origin}${paths.acp}/checkout_sessions, for agents with an ACP credential. ${payment}`,
|
|
49
|
+
tags: ["checkout", "acp"],
|
|
50
|
+
},
|
|
51
|
+
...(livemode ? [] : [{
|
|
52
|
+
id: "mcp-checkout", name: "MCP checkout",
|
|
53
|
+
description: `MCP checkout tools at ${origin}${paths.mcp}: complete_checkout hands the shopper a link to the store's checkout page, where they pay and the order is created. Test mode only. Checkout tools need this store's agent credential (Authorization: Bearer agt_…), which the merchant issues in the Relyon dashboard under AI agents → Credentials.`,
|
|
54
|
+
tags: ["checkout", "mcp"],
|
|
55
|
+
}]),
|
|
56
|
+
],
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export declare const DONE_BEGIN = "<!-- BEGIN relyon-done (managed by npx @relyon/store-kit init; edit outside this block) -->";
|
|
2
|
+
export declare const DONE_END = "<!-- END relyon-done -->";
|
|
3
|
+
/** Every BEGIN line of this block starts with this, whatever follows it. */
|
|
4
|
+
export declare const DONE_BEGIN_PREFIX = "<!-- BEGIN relyon-done";
|
|
5
|
+
/** The files that carry the block: Codex and most agents, Claude Code, Replit Agent. */
|
|
6
|
+
export declare const DONE_FILES: readonly ["AGENTS.md", "CLAUDE.md", "replit.md"];
|
|
7
|
+
/** Host detection affects instructions only, never credential persistence. */
|
|
8
|
+
export declare function doneFiles(env: NodeJS.ProcessEnv): readonly string[];
|
|
9
|
+
/** The exact block, without a trailing newline. */
|
|
10
|
+
export declare const DONE_BLOCK: string;
|
|
11
|
+
/**
|
|
12
|
+
* The one marked done block, as character offsets: exactly one exact BEGIN line
|
|
13
|
+
* followed by exactly one END line, each on its own line, not overlapping the
|
|
14
|
+
* pointer block. null when there is no marker at all; "ambiguous" otherwise.
|
|
15
|
+
*/
|
|
16
|
+
export declare function doneBlock(text: string): {
|
|
17
|
+
begin: number;
|
|
18
|
+
end: number;
|
|
19
|
+
} | null | "ambiguous";
|
|
20
|
+
export type DonePlan = {
|
|
21
|
+
kind: "write";
|
|
22
|
+
content: string;
|
|
23
|
+
} | {
|
|
24
|
+
kind: "unchanged";
|
|
25
|
+
} | {
|
|
26
|
+
kind: "conflict";
|
|
27
|
+
reason: string;
|
|
28
|
+
};
|
|
29
|
+
/** The reason init gives when it can't place the block safely. */
|
|
30
|
+
export declare const DONE_CONFLICT = "has an incomplete, repeated or misplaced relyon-done marker; fix it by hand (init never guesses)";
|
|
31
|
+
/**
|
|
32
|
+
* What a file should hold with the done block: `current` is its text (or what
|
|
33
|
+
* init already plans to write there), null when the file is missing. Text that
|
|
34
|
+
* isn't valid UTF-8 is the caller's to refuse before this.
|
|
35
|
+
*/
|
|
36
|
+
export declare function planDoneBlock(current: string | null): DonePlan;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// The managed "definition of done" block init keeps in AGENTS.md, CLAUDE.md and
|
|
2
|
+
// replit.md. It is a second, separately marked block next to the Relyon pointer
|
|
3
|
+
// block, with the same rules: only the marked block is ever replaced, a file
|
|
4
|
+
// without it gets it appended, every other line stays byte for byte, and
|
|
5
|
+
// anything ambiguous is a conflict instead of a guess.
|
|
6
|
+
import { forKitPackage } from "./identity.js";
|
|
7
|
+
export const DONE_BEGIN = "<!-- BEGIN relyon-done (managed by npx @relyon/store-kit init; edit outside this block) -->";
|
|
8
|
+
export const DONE_END = "<!-- END relyon-done -->";
|
|
9
|
+
/** Every BEGIN line of this block starts with this, whatever follows it. */
|
|
10
|
+
export const DONE_BEGIN_PREFIX = "<!-- BEGIN relyon-done";
|
|
11
|
+
/** The files that carry the block: Codex and most agents, Claude Code, Replit Agent. */
|
|
12
|
+
export const DONE_FILES = ["AGENTS.md", "CLAUDE.md", "replit.md"];
|
|
13
|
+
/** Host detection affects instructions only, never credential persistence. */
|
|
14
|
+
export function doneFiles(env) {
|
|
15
|
+
return env.REPL_ID || env.REPLIT_DEV_DOMAIN ? DONE_FILES : DONE_FILES.filter(file => file !== "replit.md");
|
|
16
|
+
}
|
|
17
|
+
/** The exact block, without a trailing newline. */
|
|
18
|
+
export const DONE_BLOCK = forKitPackage([
|
|
19
|
+
DONE_BEGIN,
|
|
20
|
+
"## Relyon Core: definition of done",
|
|
21
|
+
"You are not done until `npx @relyon/store-kit doctor` prints DONE (exit code 0):",
|
|
22
|
+
"- a Test key is present (RELYON_API_KEY, set by init; never print it);",
|
|
23
|
+
"- doctor passes with no FAIL;",
|
|
24
|
+
"- one Test checkout has completed and Relyon has confirmed it;",
|
|
25
|
+
"- the product feeds are live.",
|
|
26
|
+
"If doctor prints NOT DONE, do the \"Do this next\" steps in order and rerun doctor.",
|
|
27
|
+
DONE_END,
|
|
28
|
+
].join("\n"));
|
|
29
|
+
/** The same pointer-block markers init.ts uses, to keep the two blocks apart. */
|
|
30
|
+
const POINTER_BEGIN_PREFIX = "<!-- BEGIN relyon (";
|
|
31
|
+
const POINTER_END = "<!-- END relyon -->";
|
|
32
|
+
const count = (text, needle) => text.split(needle).length - 1;
|
|
33
|
+
const ownLine = (text, at, length) => (at === 0 || text[at - 1] === "\n")
|
|
34
|
+
&& (at + length === text.length || text[at + length] === "\n" || text.startsWith("\r\n", at + length));
|
|
35
|
+
/**
|
|
36
|
+
* The one marked done block, as character offsets: exactly one exact BEGIN line
|
|
37
|
+
* followed by exactly one END line, each on its own line, not overlapping the
|
|
38
|
+
* pointer block. null when there is no marker at all; "ambiguous" otherwise.
|
|
39
|
+
*/
|
|
40
|
+
export function doneBlock(text) {
|
|
41
|
+
const begins = count(text, DONE_BEGIN_PREFIX), ends = count(text, DONE_END);
|
|
42
|
+
if (!begins && !ends)
|
|
43
|
+
return null;
|
|
44
|
+
if (begins !== 1 || ends !== 1 || count(text, DONE_BEGIN) !== 1)
|
|
45
|
+
return "ambiguous";
|
|
46
|
+
const begin = text.indexOf(DONE_BEGIN), endAt = text.indexOf(DONE_END);
|
|
47
|
+
if (endAt < begin || !ownLine(text, begin, DONE_BEGIN.length) || !ownLine(text, endAt, DONE_END.length))
|
|
48
|
+
return "ambiguous";
|
|
49
|
+
const end = endAt + DONE_END.length;
|
|
50
|
+
// A pointer marker inside the done block (or the done block inside the pointer block) is never guessed at.
|
|
51
|
+
const inner = text.slice(begin, end);
|
|
52
|
+
if (inner.includes(POINTER_BEGIN_PREFIX) || inner.includes(POINTER_END))
|
|
53
|
+
return "ambiguous";
|
|
54
|
+
const pointerBegin = text.indexOf(POINTER_BEGIN_PREFIX), pointerEnd = text.indexOf(POINTER_END);
|
|
55
|
+
if (pointerBegin !== -1 && pointerEnd !== -1 && pointerBegin < begin && end <= pointerEnd)
|
|
56
|
+
return "ambiguous";
|
|
57
|
+
return { begin, end };
|
|
58
|
+
}
|
|
59
|
+
/** The reason init gives when it can't place the block safely. */
|
|
60
|
+
export const DONE_CONFLICT = "has an incomplete, repeated or misplaced relyon-done marker; fix it by hand (init never guesses)";
|
|
61
|
+
/**
|
|
62
|
+
* What a file should hold with the done block: `current` is its text (or what
|
|
63
|
+
* init already plans to write there), null when the file is missing. Text that
|
|
64
|
+
* isn't valid UTF-8 is the caller's to refuse before this.
|
|
65
|
+
*/
|
|
66
|
+
export function planDoneBlock(current) {
|
|
67
|
+
if (current === null)
|
|
68
|
+
return { kind: "write", content: `${DONE_BLOCK}\n` };
|
|
69
|
+
const found = doneBlock(current);
|
|
70
|
+
if (found === "ambiguous")
|
|
71
|
+
return { kind: "conflict", reason: DONE_CONFLICT };
|
|
72
|
+
if (found) {
|
|
73
|
+
if (current.slice(found.begin, found.end) === DONE_BLOCK)
|
|
74
|
+
return { kind: "unchanged" };
|
|
75
|
+
return { kind: "write", content: `${current.slice(0, found.begin)}${DONE_BLOCK}${current.slice(found.end)}` };
|
|
76
|
+
}
|
|
77
|
+
return { kind: "write", content: `${current}${current.endsWith("\n") || !current ? "" : "\n"}${current ? "\n" : ""}${DONE_BLOCK}\n` };
|
|
78
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type DoctorVerdict } from "./next-steps.js";
|
|
2
|
+
export declare const AGENT_HOOK_TOOLS: readonly ["claude", "cursor", "copilot"];
|
|
3
|
+
export type AgentHookTool = typeof AGENT_HOOK_TOOLS[number];
|
|
4
|
+
/** The most times a hook asks the agent to continue in one session. */
|
|
5
|
+
export declare const MAX_BLOCKS = 3;
|
|
6
|
+
/** Per-request doctor timeout inside a hook, and the hook's overall budget, in milliseconds. */
|
|
7
|
+
export declare const HOOK_REQUEST_TIMEOUT_MS = 2500;
|
|
8
|
+
export declare const HOOK_DEADLINE_MS = 20000;
|
|
9
|
+
/** What the tools are told to allow for the hook, in seconds. */
|
|
10
|
+
export declare const HOOK_TIMEOUT_SECONDS = 30;
|
|
11
|
+
/** Where each tool reads project hooks (Copilot: https://docs.github.com/en/copilot/reference/hooks-reference). */
|
|
12
|
+
export declare const HOOK_FILES: Record<AgentHookTool, string>;
|
|
13
|
+
/** The hook command; `--no-install` never downloads anything when the hook fires. */
|
|
14
|
+
export declare function hookCommand(tool: AgentHookTool): string;
|
|
15
|
+
export declare function isAgentHookTool(value: unknown): value is AgentHookTool;
|
|
16
|
+
export type HookConfigPlan = {
|
|
17
|
+
kind: "write";
|
|
18
|
+
content: string;
|
|
19
|
+
} | {
|
|
20
|
+
kind: "unchanged";
|
|
21
|
+
} | {
|
|
22
|
+
kind: "conflict";
|
|
23
|
+
reason: string;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Adds the Relyon stop hook to a tool's configuration, keeping every other key
|
|
27
|
+
* and hook. `existing` is the file's text, null when it is missing. Invalid JSON
|
|
28
|
+
* or an unexpected shape is a conflict: nothing is written.
|
|
29
|
+
*/
|
|
30
|
+
export declare function mergeHookConfig(tool: AgentHookTool, existing: string | null): HookConfigPlan;
|
|
31
|
+
export interface AgentHookIo {
|
|
32
|
+
/** The hook's stdin text (the tool's JSON event). */
|
|
33
|
+
stdin: string;
|
|
34
|
+
env: NodeJS.ProcessEnv;
|
|
35
|
+
/** The project directory (the hook's working directory). */
|
|
36
|
+
cwd: string;
|
|
37
|
+
/** Where the per-session counter lives. Default: an owner-only folder in the OS temp directory. */
|
|
38
|
+
stateDir?: string | undefined;
|
|
39
|
+
/** Test seam: computes the verdict. Default: the doctor with a short timeout. */
|
|
40
|
+
verdict?: ((context: {
|
|
41
|
+
env: NodeJS.ProcessEnv;
|
|
42
|
+
cwd: string;
|
|
43
|
+
}) => Promise<{
|
|
44
|
+
verdict: DoctorVerdict;
|
|
45
|
+
secrets: string[];
|
|
46
|
+
}>) | undefined;
|
|
47
|
+
/** Overall budget in milliseconds. Default HOOK_DEADLINE_MS. */
|
|
48
|
+
deadlineMs?: number | undefined;
|
|
49
|
+
}
|
|
50
|
+
export interface AgentHookAnswer {
|
|
51
|
+
/** What the hook prints on stdout (may be empty). */
|
|
52
|
+
stdout: string;
|
|
53
|
+
/** Printed on stderr: a short note for the person, never a secret. */
|
|
54
|
+
stderr: string;
|
|
55
|
+
/** Always 0: a hook never fails the agent's run. */
|
|
56
|
+
exitCode: 0;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Answers one stop event in the tool's own format. Never throws: any internal
|
|
60
|
+
* error, timeout or unreadable state allows the stop.
|
|
61
|
+
*/
|
|
62
|
+
export declare function runAgentHook(tool: AgentHookTool, io: AgentHookIo): Promise<AgentHookAnswer>;
|
|
63
|
+
/** Reads the hook's stdin: at most 1 MiB, and never waits on a terminal or longer than `timeoutMs`. */
|
|
64
|
+
export declare function readHookStdin(input?: NodeJS.ReadStream, timeoutMs?: number): Promise<string>;
|
|
65
|
+
/** Kept for tests: the counter file a session uses. */
|
|
66
|
+
export declare function hookCounterFile(tool: AgentHookTool, session: string, project: string, stateDir: string): Promise<string>;
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { forKitPackage } from "./identity.js";
|
|
2
|
+
import { publicUrlFromEnv } from "./kit-environment.js";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { constants } from "node:fs";
|
|
5
|
+
import { lstat, mkdir, open, rename, rm, realpath } from "node:fs/promises";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { usableApiKey } from "./api-key.js";
|
|
9
|
+
import { DEFAULT_RELYON_BASE_URL, redactSecrets } from "./doctor.js";
|
|
10
|
+
import { formatNextSteps, runDoctorReport } from "./next-steps.js";
|
|
11
|
+
import { loadTestConfig } from "./private-config.js";
|
|
12
|
+
// Optional stop hooks (`init --agent-hooks`, default off). When a coding agent
|
|
13
|
+
// tries to stop, the hidden `doctor --agent-hook <tool>` runs the doctor and,
|
|
14
|
+
// while it says NOT DONE, asks the agent to keep going with the "Do this next"
|
|
15
|
+
// steps: at most MAX_BLOCKS times per session, counted outside the project.
|
|
16
|
+
// The hook never prints a secret and allows the stop on any internal error.
|
|
17
|
+
export const AGENT_HOOK_TOOLS = ["claude", "cursor", "copilot"];
|
|
18
|
+
/** The most times a hook asks the agent to continue in one session. */
|
|
19
|
+
export const MAX_BLOCKS = 3;
|
|
20
|
+
/** Per-request doctor timeout inside a hook, and the hook's overall budget, in milliseconds. */
|
|
21
|
+
export const HOOK_REQUEST_TIMEOUT_MS = 2500;
|
|
22
|
+
export const HOOK_DEADLINE_MS = 20_000;
|
|
23
|
+
/** What the tools are told to allow for the hook, in seconds. */
|
|
24
|
+
export const HOOK_TIMEOUT_SECONDS = 30;
|
|
25
|
+
/** Where each tool reads project hooks (Copilot: https://docs.github.com/en/copilot/reference/hooks-reference). */
|
|
26
|
+
export const HOOK_FILES = {
|
|
27
|
+
claude: ".claude/settings.json",
|
|
28
|
+
cursor: ".cursor/hooks.json",
|
|
29
|
+
copilot: ".github/hooks/relyon.json",
|
|
30
|
+
};
|
|
31
|
+
/** The hook command; `--no-install` never downloads anything when the hook fires. */
|
|
32
|
+
export function hookCommand(tool) {
|
|
33
|
+
return forKitPackage(`npx --no-install @relyon/store-kit doctor --agent-hook ${tool}`);
|
|
34
|
+
}
|
|
35
|
+
export function isAgentHookTool(value) {
|
|
36
|
+
return typeof value === "string" && AGENT_HOOK_TOOLS.includes(value);
|
|
37
|
+
}
|
|
38
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
39
|
+
const RELYON_HOOK = /@relyon\/(?:store-)?kit doctor --agent-hook /;
|
|
40
|
+
/** True when a hook entry is a Relyon stop hook (identified by its command). */
|
|
41
|
+
function relyonEntry(entry) {
|
|
42
|
+
if (!isObject(entry))
|
|
43
|
+
return false;
|
|
44
|
+
return [entry.command, entry.bash, entry.powershell].some((value) => typeof value === "string" && RELYON_HOOK.test(value));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Adds the Relyon stop hook to a tool's configuration, keeping every other key
|
|
48
|
+
* and hook. `existing` is the file's text, null when it is missing. Invalid JSON
|
|
49
|
+
* or an unexpected shape is a conflict: nothing is written.
|
|
50
|
+
*/
|
|
51
|
+
export function mergeHookConfig(tool, existing) {
|
|
52
|
+
let config = {};
|
|
53
|
+
// Only a missing file starts empty; a blank file is invalid JSON like any other.
|
|
54
|
+
if (existing !== null) {
|
|
55
|
+
let parsed;
|
|
56
|
+
try {
|
|
57
|
+
parsed = JSON.parse(existing);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return { kind: "conflict", reason: "isn't valid JSON, so init won't edit it; fix it or add the Relyon hook by hand" };
|
|
61
|
+
}
|
|
62
|
+
if (!isObject(parsed))
|
|
63
|
+
return { kind: "conflict", reason: "isn't a JSON object, so init won't edit it" };
|
|
64
|
+
config = parsed;
|
|
65
|
+
}
|
|
66
|
+
if (config.hooks !== undefined && !isObject(config.hooks))
|
|
67
|
+
return { kind: "conflict", reason: "has a \"hooks\" value that isn't an object, so init won't edit it" };
|
|
68
|
+
const hooks = isObject(config.hooks) ? config.hooks : {};
|
|
69
|
+
const event = tool === "claude" ? "Stop" : tool === "cursor" ? "stop" : "agentStop";
|
|
70
|
+
if (hooks[event] !== undefined && !Array.isArray(hooks[event]))
|
|
71
|
+
return { kind: "conflict", reason: `has a "hooks.${event}" value that isn't a list, so init won't edit it` };
|
|
72
|
+
const list = hooks[event] ?? [];
|
|
73
|
+
const command = hookCommand(tool);
|
|
74
|
+
const present = tool === "claude"
|
|
75
|
+
? list.some((group) => isObject(group) && Array.isArray(group.hooks) && group.hooks.some(relyonEntry))
|
|
76
|
+
: list.some(relyonEntry);
|
|
77
|
+
if (present)
|
|
78
|
+
return { kind: "unchanged" };
|
|
79
|
+
const entry = tool === "claude"
|
|
80
|
+
? { hooks: [{ type: "command", command, timeout: HOOK_TIMEOUT_SECONDS }] }
|
|
81
|
+
: tool === "cursor"
|
|
82
|
+
? { command, loop_limit: MAX_BLOCKS }
|
|
83
|
+
: { type: "command", bash: command, powershell: command, timeoutSec: HOOK_TIMEOUT_SECONDS };
|
|
84
|
+
const merged = { ...config };
|
|
85
|
+
if (tool !== "claude" && merged.version === undefined)
|
|
86
|
+
merged.version = 1;
|
|
87
|
+
merged.hooks = { ...hooks, [event]: [...list, entry] };
|
|
88
|
+
// Cursor and Copilot name the version first; keep that order for new files.
|
|
89
|
+
const ordered = tool !== "claude" && existing === null ? { version: merged.version, ...merged } : merged;
|
|
90
|
+
return { kind: "write", content: `${JSON.stringify(ordered, null, 2)}\n` };
|
|
91
|
+
}
|
|
92
|
+
const allow = (tool, stderr = "") => ({ stdout: tool === "cursor" ? "{}\n" : "", stderr, exitCode: 0 });
|
|
93
|
+
function sessionOf(tool, event) {
|
|
94
|
+
const value = tool === "cursor" ? event.conversation_id : tool === "copilot" ? event.sessionId ?? event.session_id : event.session_id;
|
|
95
|
+
return typeof value === "string" && value.length <= 512 ? value : "unknown-session";
|
|
96
|
+
}
|
|
97
|
+
/** The owner-only counter folder, refusing links and anything not owned by this user. */
|
|
98
|
+
async function stateDirectory(given) {
|
|
99
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
|
|
100
|
+
const dir = given ?? path.join(os.tmpdir(), `relyon-agent-hooks-${uid ?? "user"}`);
|
|
101
|
+
try {
|
|
102
|
+
await mkdir(dir, { mode: 0o700 });
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error.code !== "EEXIST")
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const stat = await lstat(dir);
|
|
109
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
110
|
+
throw new Error("hook state folder is not a directory");
|
|
111
|
+
if (uid !== undefined && (stat.uid !== uid || (stat.mode & 0o077) !== 0))
|
|
112
|
+
throw new Error("hook state folder is not private");
|
|
113
|
+
return dir;
|
|
114
|
+
}
|
|
115
|
+
async function readCount(file) {
|
|
116
|
+
let handle;
|
|
117
|
+
try {
|
|
118
|
+
handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (error.code === "ENOENT")
|
|
122
|
+
return 0;
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
const value = Number.parseInt((await handle.readFile("utf8")).trim(), 10);
|
|
127
|
+
return Number.isFinite(value) && value >= 0 ? value : MAX_BLOCKS + 1;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
await handle.close();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function writeCount(file, value) {
|
|
134
|
+
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
135
|
+
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
136
|
+
try {
|
|
137
|
+
await handle.writeFile(String(value));
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
await handle.close();
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
await rename(temporary, file);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
await rm(temporary, { force: true });
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** STORE_PUBLIC_URL from the environment, else from the project's .env (a small regular file, never a link). */
|
|
151
|
+
async function storeUrlFor(env, cwd) {
|
|
152
|
+
const publicUrl = publicUrlFromEnv(env);
|
|
153
|
+
if (publicUrl)
|
|
154
|
+
return publicUrl;
|
|
155
|
+
const file = path.join(cwd, ".env");
|
|
156
|
+
try {
|
|
157
|
+
const stat = await lstat(file);
|
|
158
|
+
if (!stat.isFile() || stat.size > 65536)
|
|
159
|
+
return undefined;
|
|
160
|
+
const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
161
|
+
let text;
|
|
162
|
+
try {
|
|
163
|
+
text = await handle.readFile("utf8");
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
await handle.close();
|
|
167
|
+
}
|
|
168
|
+
let found;
|
|
169
|
+
for (const line of text.split(/\r?\n/)) {
|
|
170
|
+
const match = /^\s*(?:export\s+)?STORE_PUBLIC_URL\s*=\s*(.*)$/.exec(line);
|
|
171
|
+
if (match)
|
|
172
|
+
found = match[1].trim().replace(/^(["'])(.*)\1$/, "$2").replace(/\s+#.*$/, "") || undefined;
|
|
173
|
+
}
|
|
174
|
+
return found;
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/** The doctor's verdict for the hook: the same key rules as `doctor` (no saved key in Live), short timeouts. */
|
|
181
|
+
async function defaultVerdict({ env, cwd }) {
|
|
182
|
+
const storeUrl = await storeUrlFor(env, cwd);
|
|
183
|
+
const live = env.RELYON_LIVE?.trim().toLowerCase() === "true";
|
|
184
|
+
const envKey = usableApiKey(env.RELYON_API_KEY);
|
|
185
|
+
let apiKey = envKey, keySource = envKey ? "env" : undefined;
|
|
186
|
+
if (!apiKey && !live) {
|
|
187
|
+
const saved = await loadTestConfig({ project: cwd, env }).catch(() => ({}));
|
|
188
|
+
if (saved.apiKey) {
|
|
189
|
+
apiKey = saved.apiKey;
|
|
190
|
+
keySource = "saved";
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const secrets = [env.RELYON_API_KEY, apiKey].filter((value) => !!value);
|
|
194
|
+
if (!storeUrl) {
|
|
195
|
+
return { secrets, verdict: {
|
|
196
|
+
status: "not_done", live, required: live ? 3 : 4, remaining: live ? 3 : 4,
|
|
197
|
+
conditions: { testKey: !!apiKey, doctorPasses: false, checkoutConfirmed: false, feedsLive: false },
|
|
198
|
+
confirmed: { test_key_used: false, test_checkout_completed: false },
|
|
199
|
+
nextSteps: [
|
|
200
|
+
{ order: 1, action: "Set STORE_PUBLIC_URL (in the environment or .env) to the store's public origin, such as https://shop.example.com, so doctor can check it." },
|
|
201
|
+
{ order: 2, action: "Then run: npx @relyon/store-kit doctor", command: "npx @relyon/store-kit doctor" },
|
|
202
|
+
],
|
|
203
|
+
} };
|
|
204
|
+
}
|
|
205
|
+
const report = await runDoctorReport({
|
|
206
|
+
storeUrl, apiKey, keySource, live, projectDir: cwd, timeoutMs: HOOK_REQUEST_TIMEOUT_MS,
|
|
207
|
+
baseUrl: env.RELYON_BASE_URL?.trim() || DEFAULT_RELYON_BASE_URL,
|
|
208
|
+
});
|
|
209
|
+
return { verdict: report.verdict, secrets };
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Answers one stop event in the tool's own format. Never throws: any internal
|
|
213
|
+
* error, timeout or unreadable state allows the stop.
|
|
214
|
+
*/
|
|
215
|
+
export async function runAgentHook(tool, io) {
|
|
216
|
+
try {
|
|
217
|
+
let event = {};
|
|
218
|
+
try {
|
|
219
|
+
const parsed = JSON.parse(io.stdin || "{}");
|
|
220
|
+
if (isObject(parsed))
|
|
221
|
+
event = parsed;
|
|
222
|
+
}
|
|
223
|
+
catch { /* an unreadable event is an empty one */ }
|
|
224
|
+
// Claude Code (and Copilot's compatible input): the agent is already continuing because of a stop hook; never loop.
|
|
225
|
+
if (tool !== "cursor" && (event.stop_hook_active === true || event.stopHookActive === true))
|
|
226
|
+
return allow(tool);
|
|
227
|
+
const project = await realpath(io.cwd);
|
|
228
|
+
const dir = await stateDirectory(io.stateDir);
|
|
229
|
+
const counter = path.join(dir, createHash("sha256").update(`${tool}\0${sessionOf(tool, event)}\0${project}`).digest("hex").slice(0, 40));
|
|
230
|
+
const count = await readCount(counter);
|
|
231
|
+
if (count > MAX_BLOCKS)
|
|
232
|
+
return allow(tool);
|
|
233
|
+
const deadline = io.deadlineMs ?? HOOK_DEADLINE_MS;
|
|
234
|
+
let timer;
|
|
235
|
+
const timedOut = new Promise((resolve) => { timer = setTimeout(() => resolve(null), deadline); });
|
|
236
|
+
const outcome = await Promise.race([(io.verdict ?? defaultVerdict)({ env: io.env, cwd: project }), timedOut]).finally(() => clearTimeout(timer));
|
|
237
|
+
if (!outcome)
|
|
238
|
+
return allow(tool, "Relyon doctor did not finish in time; the stop is allowed.\n");
|
|
239
|
+
const { verdict, secrets } = outcome;
|
|
240
|
+
if (verdict.status === "done")
|
|
241
|
+
return allow(tool);
|
|
242
|
+
const steps = redactSecrets(formatNextSteps(verdict), secrets).trimEnd();
|
|
243
|
+
if (count >= MAX_BLOCKS) {
|
|
244
|
+
// The cap is reached: allow the stop and show the remaining steps once.
|
|
245
|
+
await writeCount(counter, count + 1);
|
|
246
|
+
const note = `Relyon setup is still NOT DONE after ${MAX_BLOCKS} reminders; stopping is allowed.\n${steps}`;
|
|
247
|
+
if (tool === "claude")
|
|
248
|
+
return { stdout: `${JSON.stringify({ systemMessage: note })}\n`, stderr: "", exitCode: 0 };
|
|
249
|
+
return allow(tool, `${note}\n`);
|
|
250
|
+
}
|
|
251
|
+
// Counted before answering, so a counter that can't be written allows the stop (via the catch).
|
|
252
|
+
await writeCount(counter, count + 1);
|
|
253
|
+
const reason = `${steps}\n(Relyon stop hook, reminder ${count + 1} of ${MAX_BLOCKS}.)`;
|
|
254
|
+
if (tool === "cursor")
|
|
255
|
+
return { stdout: `${JSON.stringify({ followup_message: reason })}\n`, stderr: "", exitCode: 0 };
|
|
256
|
+
return { stdout: `${JSON.stringify({ decision: "block", reason })}\n`, stderr: "", exitCode: 0 };
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return allow(tool);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/** Reads the hook's stdin: at most 1 MiB, and never waits on a terminal or longer than `timeoutMs`. */
|
|
263
|
+
export async function readHookStdin(input = process.stdin, timeoutMs = 2000) {
|
|
264
|
+
if (input.isTTY)
|
|
265
|
+
return "";
|
|
266
|
+
return new Promise((resolve) => {
|
|
267
|
+
let text = "";
|
|
268
|
+
const finish = () => { clearTimeout(timer); input.removeAllListeners("data"); input.pause(); resolve(text.length > 1024 * 1024 ? "" : text); };
|
|
269
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
270
|
+
input.setEncoding("utf8");
|
|
271
|
+
input.on("data", (chunk) => { text += chunk; if (text.length > 1024 * 1024)
|
|
272
|
+
finish(); });
|
|
273
|
+
input.once("end", finish);
|
|
274
|
+
input.once("error", finish);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
/** Kept for tests: the counter file a session uses. */
|
|
278
|
+
export async function hookCounterFile(tool, session, project, stateDir) {
|
|
279
|
+
return path.join(stateDir, createHash("sha256").update(`${tool}\0${session}\0${await realpath(project)}`).digest("hex").slice(0, 40));
|
|
280
|
+
}
|
package/dist/agents.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { AgentName, AgentRuleAgent } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Who a request says it comes from. Everything here is a claim the request
|
|
4
|
+
* makes about itself (user agent, signature headers, profile URLs, MCP client
|
|
5
|
+
* info); the kit never verifies it. It is used for one thing only: matching
|
|
6
|
+
* `blocked_agents` at the edge. Relyon verifies identity on every decision.
|
|
7
|
+
*/
|
|
8
|
+
export interface AgentClaim {
|
|
9
|
+
/** null when nothing in the request claims to be an agent (a person's browser). */
|
|
10
|
+
name: AgentName | null;
|
|
11
|
+
network?: "visa_tap" | "mastercard_agent_pay" | "relyon";
|
|
12
|
+
keyId?: string;
|
|
13
|
+
/** What the claim was read from, for logs. */
|
|
14
|
+
signals: string[];
|
|
15
|
+
}
|
|
16
|
+
/** Names the agent a request claims to be. */
|
|
17
|
+
export declare function claimAgent(headers: Headers, mcpClientName?: string): AgentClaim;
|
|
18
|
+
/**
|
|
19
|
+
* The blocked entry this claim matches, if any. `name: unknown` entries are
|
|
20
|
+
* not applied at the edge: "unknown" means Relyon could not identify the agent
|
|
21
|
+
* from verified signals, which the kit can't establish from claims. Relyon
|
|
22
|
+
* still applies them to every checkout step and payment.
|
|
23
|
+
*/
|
|
24
|
+
export declare function blockedEntry(claim: AgentClaim, blocked: readonly unknown[]): AgentRuleAgent | null;
|
package/dist/agents.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
const USER_AGENTS = [
|
|
2
|
+
[/ChatGPT|OAI-SearchBot|GPTBot|OpenAI/i, "chatgpt"],
|
|
3
|
+
[/Claude|Anthropic/i, "claude"],
|
|
4
|
+
[/Google-Agent|Gemini|Google-Extended|Project ?Mariner/i, "gemini"],
|
|
5
|
+
[/Copilot/i, "copilot"],
|
|
6
|
+
[/Perplexity|\bComet\//i, "perplexity"],
|
|
7
|
+
[/Meta-External|MuseAgent|\bMuse\b/i, "muse"],
|
|
8
|
+
// Browser agents without their own rule name yet: Grok and Amazon Buy for Me.
|
|
9
|
+
[/\bGrok(Bot)?\b|xAI-Agent/i, "other_known"],
|
|
10
|
+
[/Amazon-?Buy-?For-?Me|AmazonBuyForMe/i, "other_known"],
|
|
11
|
+
[/Googlebot|bingbot|Applebot|Amazonbot|Bytespider|CCBot|DuckAssistBot|YouBot|cohere-ai|MistralAI|AI2Bot|Diffbot/i, "other_known"],
|
|
12
|
+
];
|
|
13
|
+
const HOSTS = [
|
|
14
|
+
[/(^|\.)(chatgpt\.com|openai\.com)$/i, "chatgpt"],
|
|
15
|
+
[/(^|\.)(claude\.ai|anthropic\.com)$/i, "claude"],
|
|
16
|
+
[/(^|\.)(google\.com|gemini\.google\.com|googleapis\.com)$/i, "gemini"],
|
|
17
|
+
[/(^|\.)(copilot\.microsoft\.com|bing\.com|microsoft\.com)$/i, "copilot"],
|
|
18
|
+
[/(^|\.)perplexity\.ai$/i, "perplexity"],
|
|
19
|
+
[/(^|\.)(meta\.com|facebook\.com)$/i, "muse"],
|
|
20
|
+
];
|
|
21
|
+
const MCP_CLIENTS = [
|
|
22
|
+
[/chatgpt|openai/i, "chatgpt"],
|
|
23
|
+
[/claude|anthropic/i, "claude"],
|
|
24
|
+
[/gemini|google/i, "gemini"],
|
|
25
|
+
[/copilot/i, "copilot"],
|
|
26
|
+
[/perplexity/i, "perplexity"],
|
|
27
|
+
];
|
|
28
|
+
function hostOf(value) {
|
|
29
|
+
const match = /https?:\/\/[^\s"',;]+/i.exec(value);
|
|
30
|
+
if (!match)
|
|
31
|
+
return null;
|
|
32
|
+
try {
|
|
33
|
+
return new URL(match[0]).hostname;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function byHost(value) {
|
|
40
|
+
if (!value)
|
|
41
|
+
return null;
|
|
42
|
+
const host = hostOf(value) ?? value.replace(/^"|"$/g, "");
|
|
43
|
+
for (const [pattern, name] of HOSTS)
|
|
44
|
+
if (pattern.test(host))
|
|
45
|
+
return name;
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
/** Names the agent a request claims to be. */
|
|
49
|
+
export function claimAgent(headers, mcpClientName) {
|
|
50
|
+
const signals = [];
|
|
51
|
+
let name = null;
|
|
52
|
+
const signatureAgent = headers.get("signature-agent");
|
|
53
|
+
const signatureInput = headers.get("signature-input");
|
|
54
|
+
const ucpAgent = headers.get("ucp-agent");
|
|
55
|
+
const userAgent = headers.get("user-agent") ?? "";
|
|
56
|
+
if (signatureAgent) {
|
|
57
|
+
signals.push("signature-agent");
|
|
58
|
+
name = byHost(signatureAgent);
|
|
59
|
+
}
|
|
60
|
+
if (!name && ucpAgent) {
|
|
61
|
+
signals.push("ucp-agent");
|
|
62
|
+
name = byHost(ucpAgent);
|
|
63
|
+
}
|
|
64
|
+
if (!name && mcpClientName) {
|
|
65
|
+
signals.push("mcp-client");
|
|
66
|
+
for (const [pattern, candidate] of MCP_CLIENTS)
|
|
67
|
+
if (pattern.test(mcpClientName)) {
|
|
68
|
+
name = candidate;
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (!name && userAgent) {
|
|
73
|
+
for (const [pattern, candidate] of USER_AGENTS) {
|
|
74
|
+
if (pattern.test(userAgent)) {
|
|
75
|
+
signals.push("user-agent");
|
|
76
|
+
name = candidate;
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const claim = { name, signals };
|
|
82
|
+
if (signatureInput) {
|
|
83
|
+
signals.push("signature-input");
|
|
84
|
+
const keyId = /keyid="([^"]{1,200})"/i.exec(signatureInput)?.[1];
|
|
85
|
+
if (keyId)
|
|
86
|
+
claim.keyId = keyId;
|
|
87
|
+
if (/tag="agent-(browser|payer)-auth"/i.test(signatureInput) || /visa/i.test(signatureAgent ?? ""))
|
|
88
|
+
claim.network = "visa_tap";
|
|
89
|
+
else if (/mastercard/i.test(signatureAgent ?? "") || /mastercard/i.test(signatureInput))
|
|
90
|
+
claim.network = "mastercard_agent_pay";
|
|
91
|
+
else if (/relyon/i.test(signatureAgent ?? ""))
|
|
92
|
+
claim.network = "relyon";
|
|
93
|
+
}
|
|
94
|
+
// A request that signs itself or names a UCP/MCP client is an agent, even if
|
|
95
|
+
// the kit can't tell which one.
|
|
96
|
+
if (!claim.name && (signatureAgent || signatureInput || ucpAgent || mcpClientName))
|
|
97
|
+
claim.name = "unknown";
|
|
98
|
+
return claim;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The blocked entry this claim matches, if any. `name: unknown` entries are
|
|
102
|
+
* not applied at the edge: "unknown" means Relyon could not identify the agent
|
|
103
|
+
* from verified signals, which the kit can't establish from claims. Relyon
|
|
104
|
+
* still applies them to every checkout step and payment.
|
|
105
|
+
*/
|
|
106
|
+
export function blockedEntry(claim, blocked) {
|
|
107
|
+
for (const raw of blocked) {
|
|
108
|
+
if (typeof raw !== "object" || raw === null)
|
|
109
|
+
continue;
|
|
110
|
+
const entry = raw;
|
|
111
|
+
const nameMatches = entry.name === undefined || (entry.name !== "unknown" && entry.name === claim.name);
|
|
112
|
+
const networkMatches = entry.network === undefined
|
|
113
|
+
|| (entry.network === claim.network && (entry.key_id === undefined || entry.key_id === claim.keyId));
|
|
114
|
+
if (entry.name === undefined && entry.network === undefined)
|
|
115
|
+
continue;
|
|
116
|
+
if (nameMatches && networkMatches)
|
|
117
|
+
return entry;
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|