@forgeintel/sdk 0.5.0-beta.1 → 0.5.0-beta.11

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/dist/openapi.d.ts CHANGED
@@ -2,10 +2,10 @@ type Json = Record<string, any>;
2
2
  export type SpecVersion = "2.0" | "3.0" | "3.1" | "3.2";
3
3
  export type ResponseSupport = "extended" | "incompatible" | "undocumented";
4
4
  export interface EnrichOptions {
5
- /** Disable all feedback additions while retaining optional agent context. */
5
+ /** Disable all feedback additions while retaining agent context. */
6
6
  feedback?: boolean;
7
- /** Merchant public origin, e.g. https://api.example.com */
8
- publicUrl: string;
7
+ /** Optional merchant public origin. Without it, feedback links use same-origin paths. */
8
+ publicUrl?: string;
9
9
  /** Public path of the feedback routes, e.g. /feedback */
10
10
  basePath: string;
11
11
  /** Sentence appended to x-guidance and paid operation descriptions. */
@@ -18,9 +18,10 @@ export interface EnrichOptions {
18
18
  describeOperations?: boolean;
19
19
  /** Also document the optional rate_this_call body field (when the SDK's rateHint is on). */
20
20
  hintField?: boolean;
21
- /** Document optional agent context on paid operations: `agent_context` in JSON request bodies, agent_* query parameters otherwise. */
21
+ /** Document agent context on paid operations: `agent_context` in JSON request bodies, agent_* query parameters otherwise. */
22
22
  agentContext?: {
23
23
  searchQuery: boolean;
24
+ required?: boolean;
24
25
  };
25
26
  }
26
27
  export interface OperationReport {
@@ -29,7 +30,7 @@ export interface OperationReport {
29
30
  path: string;
30
31
  /** Per 2xx status code: whether feedback_id was added to its JSON schema. */
31
32
  responses: Record<string, ResponseSupport>;
32
- /** Where optional agent context was documented, if asked to. */
33
+ /** Where agent context was documented, if asked to. */
33
34
  agentContext?: "body" | "query" | "not_added";
34
35
  reasons: string[];
35
36
  }
package/dist/openapi.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // and on any unexpected input return the original document unchanged.
4
4
  import { CONTEXT_FIELD, agentContextParameters, agentContextSchema } from "./context.js";
5
5
  import { FEEDBACK_ID_PATTERN } from "./id.js";
6
+ import { FEEDBACK_FIELD } from "./x402.js";
6
7
  import { ISSUES, NOTE_MAX_LENGTH, OUTCOMES, PROTOCOL } from "./values.js";
7
8
  const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
8
9
  const ANNOTATIONS = new Set(["$ref", "description", "title", "summary", "example", "examples", "deprecated", "readOnly", "writeOnly", "$comment"]);
@@ -38,16 +39,23 @@ function resolveRef(doc, ref) {
38
39
  }
39
40
  function feedbackProperties(rateUrl, hintField = false) {
40
41
  return {
41
- ...(hintField ? { rate_this_call: { type: "string", description: "How to rate this paid call in one free request." } } : {}),
42
- feedback_id: {
43
- type: "string",
44
- pattern: FEEDBACK_ID_PATTERN.source,
45
- description: "Rating ID for this paid call (also sent as the Forge-Feedback-Id header). See x-forge-feedback.",
46
- },
47
- feedback_url: {
48
- type: "string",
49
- format: "uri",
50
- description: `Quick-rating URL with outcome left blank; outcome values: ${Object.keys(OUTCOMES).join(", ")}. Base: ${rateUrl}`,
42
+ [FEEDBACK_FIELD]: {
43
+ type: "object",
44
+ description: "Added by Forge to paid responses: how to rate this call. See x-forge-feedback.",
45
+ required: ["feedback_id", "feedback_url"],
46
+ properties: {
47
+ feedback_id: {
48
+ type: "string",
49
+ pattern: FEEDBACK_ID_PATTERN.source,
50
+ description: "Rating ID for this paid call (also sent as the Forge-Feedback-Id header).",
51
+ },
52
+ feedback_url: {
53
+ type: "string",
54
+ format: "uri-reference",
55
+ description: `Quick-rating URL with outcome left blank; outcome values: ${Object.keys(OUTCOMES).join(", ")}. Base: ${rateUrl}`,
56
+ },
57
+ ...(hintField ? { rate_this_call: { type: "string", description: "How to rate this paid call in one free request." } } : {}),
58
+ },
51
59
  },
52
60
  };
53
61
  }
@@ -100,7 +108,7 @@ function extendSchema(doc, schema, props) {
100
108
  return { schema: copy };
101
109
  }
102
110
  const BODYLESS = new Set(["get", "head", "delete", "options", "trace"]);
103
- /** Document optional agent context on one paid operation. Never required; skipped when a schema can't take it safely. */
111
+ /** Document agent context on a paid operation; skip schemas that cannot be extended safely. */
104
112
  function addAgentContext(doc, version, item, method, op, opts, report) {
105
113
  const resolve = (v) => (isObj(v) && typeof v.$ref === "string" ? resolveRef(doc, v.$ref) : v);
106
114
  const listed = [...(Array.isArray(item.parameters) ? item.parameters : []), ...(Array.isArray(op.parameters) ? op.parameters : [])].map(resolve).filter(isObj);
@@ -115,8 +123,8 @@ function addAgentContext(doc, version, item, method, op, opts, report) {
115
123
  if (!params.length)
116
124
  return notAdded("parameter_collision");
117
125
  const documented = params.map((p) => version === "2.0"
118
- ? { name: p.name, in: "query", required: false, description: p.description, ...p.schema }
119
- : { name: p.name, in: "query", required: false, description: p.description, schema: p.schema });
126
+ ? { name: p.name, in: "query", required: !!opts.required && p.name !== "agent_type_other", description: p.description, ...p.schema }
127
+ : { name: p.name, in: "query", required: !!opts.required && p.name !== "agent_type_other", description: p.description, schema: p.schema });
120
128
  op.parameters = [...(Array.isArray(op.parameters) ? op.parameters : []), ...documented];
121
129
  report.agentContext = "query";
122
130
  return;
@@ -130,6 +138,10 @@ function addAgentContext(doc, version, item, method, op, opts, report) {
130
138
  const result = extendSchema(doc, param.schema, props);
131
139
  if ("reason" in result)
132
140
  return notAdded(result.reason);
141
+ if (opts.required) {
142
+ result.schema.required = [...new Set([...(Array.isArray(result.schema.required) ? result.schema.required : []), CONTEXT_FIELD])];
143
+ param.required = true;
144
+ }
133
145
  param.schema = result.schema;
134
146
  op.parameters = params.map((p, i) => (i === index ? param : p)); // inline copy if it was a shared $ref
135
147
  report.agentContext = "body";
@@ -146,8 +158,12 @@ function addAgentContext(doc, version, item, method, op, opts, report) {
146
158
  const result = extendSchema(doc, entry.schema, props);
147
159
  if ("reason" in result)
148
160
  return notAdded(result.reason);
161
+ if (opts.required)
162
+ result.schema.required = [...new Set([...(Array.isArray(result.schema.required) ? result.schema.required : []), CONTEXT_FIELD])];
149
163
  entry.schema = result.schema;
150
164
  }
165
+ if (opts.required)
166
+ copy.required = true;
151
167
  op.requestBody = copy; // inline copy if it was a shared $ref
152
168
  report.agentContext = "body";
153
169
  }
@@ -161,20 +177,21 @@ function appendSentence(text, sentence, marker) {
161
177
  }
162
178
  /** Work out the path prefix document paths are relative to, and whether it's this service's origin. */
163
179
  function serverBase(doc, version, publicUrl) {
164
- const origin = new URL(publicUrl).origin;
180
+ const origin = publicUrl ? new URL(publicUrl).origin : undefined;
181
+ const baseUrl = publicUrl ?? "https://forge.invalid";
165
182
  try {
166
183
  if (version === "2.0") {
167
- const scheme = Array.isArray(doc.schemes) && doc.schemes[0] ? doc.schemes[0] : new URL(publicUrl).protocol.slice(0, -1);
184
+ const scheme = Array.isArray(doc.schemes) && doc.schemes[0] ? doc.schemes[0] : new URL(baseUrl).protocol.slice(0, -1);
168
185
  const base = typeof doc.basePath === "string" ? doc.basePath : "";
169
- const url = typeof doc.host === "string" ? new URL(`${scheme}://${doc.host}${base}`) : new URL(base || "/", publicUrl);
170
- return { prefix: url.pathname.replace(/\/+$/, ""), sameOrigin: url.origin === origin };
186
+ const url = typeof doc.host === "string" ? new URL(`${scheme}://${doc.host}${base}`) : new URL(base || "/", baseUrl);
187
+ return { prefix: url.pathname.replace(/\/+$/, ""), sameOrigin: !origin || url.origin === origin };
171
188
  }
172
189
  const server = Array.isArray(doc.servers) ? doc.servers[0] : undefined;
173
190
  if (!isObj(server) || typeof server.url !== "string")
174
191
  return { prefix: "", sameOrigin: true };
175
192
  const raw = server.url.replace(/\{([^}]+)\}/g, (_, name) => server.variables?.[name]?.default ?? "");
176
- const url = new URL(raw, publicUrl);
177
- return { prefix: url.pathname.replace(/\/+$/, ""), sameOrigin: url.origin === origin };
193
+ const url = new URL(raw, baseUrl);
194
+ return { prefix: url.pathname.replace(/\/+$/, ""), sameOrigin: !origin || url.origin === origin };
178
195
  }
179
196
  catch {
180
197
  return { prefix: "", sameOrigin: false };
@@ -253,7 +270,7 @@ export function enrichOpenApi(input, options) {
253
270
  }
254
271
  try {
255
272
  const doc = clone(original);
256
- const origin = new URL(options.publicUrl).origin;
273
+ const origin = options.publicUrl ? new URL(options.publicUrl).origin : "";
257
274
  const base = options.basePath.replace(/\/+$/, "");
258
275
  const rateUrl = `${origin}${base}/rate`;
259
276
  const formUrl = `${origin}${base}`;
@@ -368,7 +385,7 @@ export function enrichOpenApi(input, options) {
368
385
  }
369
386
  else {
370
387
  const ops = feedbackOperations(version, formUrl, rateUrl, operationIds);
371
- const servers = inPrefix ? {} : { servers: [{ url: origin }] };
388
+ const servers = inPrefix ? {} : { servers: [{ url: origin || "/" }] };
372
389
  paths[docBase] = { ...servers, get: ops.form, post: ops.submit };
373
390
  paths[`${docBase}/rate`] = { ...servers, get: ops.rate };
374
391
  paths[`${docBase}/summary`] = { ...servers, get: ops.summary };
package/dist/x402.d.ts CHANGED
@@ -1,14 +1,23 @@
1
1
  import { type Tone } from "./ask.js";
2
+ import type { ContextOptions } from "./context.js";
2
3
  /** Key of the Forge extension in x402 v2 `extensions`: in the 402 challenge (next to e.g. `bazaar`) and in the payment receipt. */
3
4
  export declare const FEEDBACK_EXTENSION = "forge-feedback";
5
+ /** Key of the object the SDK adds to paid JSON response bodies: feedback_id, feedback_url, and optionally rate_this_call. */
6
+ export declare const FEEDBACK_FIELD = "forge_feedback";
7
+ /**
8
+ * The service origin a challenge was issued for: v2 `resource.url` (header or body), or v1 `accepts[].resource`.
9
+ * Used for absolute rating links when no origin is configured or registered. Never throws.
10
+ */
11
+ export declare function challengeOrigin(challenge: string | unknown): string | undefined;
12
+ /** The service origin a payment was made for (x402 v2 `resource.url` in the payment header). Never throws. */
13
+ export declare function paymentOrigin(headerValue: string): string | undefined;
4
14
  /**
5
15
  * The `forge-feedback` challenge extension: how to rate the call, as structured data. Clients that inspect
6
16
  * the 402 (e.g. `awal x402 details`) print every extension, so this reaches agents before they pay.
7
- * With `agentContext`, it also says how to report agent context with the paid request.
17
+ * Agent context is a separate switch with its own extension (`forge-agent-context`).
8
18
  */
9
- export declare function feedbackExtension(rateUrl: string, tone?: Tone, agentContext?: string): {
19
+ export declare function feedbackExtension(rateUrl: string, tone?: Tone): {
10
20
  info: {
11
- agent_context?: string | undefined;
12
21
  rate: string;
13
22
  outcome: string[];
14
23
  issue: {
@@ -42,21 +51,30 @@ export declare function receiptExtension(rateUrl: string, feedbackId: string, to
42
51
  * Returns undefined when the header can't be parsed, settlement failed, or the extension is already there.
43
52
  */
44
53
  export declare function describeReceipt(headerValue: string, extension: unknown): string | undefined;
54
+ /**
55
+ * The longest challenge description the SDK produces. Clients copy the description into the payment payload,
56
+ * and the CDP facilitator rejects a payload whose resource.description exceeds 500 characters, failing the payment.
57
+ */
58
+ export declare const MAX_DESCRIPTION = 500;
45
59
  /** What the SDK adds to a challenge. Each part is skipped when already present. */
46
60
  export interface ChallengeAdditions {
47
61
  /** Appended to the description (v2 resource.description, v1 accepts[].description). */
48
62
  sentence?: string;
63
+ /** Appended instead when `sentence` would pass MAX_DESCRIPTION; the description is left alone when this doesn't fit either. */
64
+ shortSentence?: string;
49
65
  /** Idempotency marker for the sentence. Default: the sentence itself. */
50
66
  marker?: string;
51
67
  /** Added as extensions["forge-feedback"] (v2 only; v1 challenges have no extensions). */
52
68
  extension?: unknown;
53
- /** Independent context prompt when feedback is disabled. */
69
+ /** Added as extensions["forge-agent-context"] whenever agent context is enabled, independent of feedback. */
54
70
  contextExtension?: unknown;
71
+ /** Declare agent context in the merchant's `bazaar` extension (schema and example together). */
72
+ bazaarContext?: ContextOptions;
55
73
  }
56
74
  /**
57
- * Add the rating sentence and/or the forge-feedback extension to a base64 PAYMENT-REQUIRED header (x402 v2).
58
- * `accepts` is untouched: v2 matches payments on `accepts`, and @x402/core only checks echoed extensions
59
- * the server itself advertised, so an added extension doesn't affect payment.
75
+ * Add the rating sentence, Forge's extensions and Bazaar agent context to a base64 PAYMENT-REQUIRED header (x402 v2).
76
+ * `accepts` is untouched: v2 matches payments on `accepts`. @x402/core checks that each echoed extension's `info`
77
+ * contains what the server advertised, so added extensions and added Bazaar fields don't affect payment.
60
78
  * Returns undefined when the header can't be parsed or already has everything.
61
79
  */
62
80
  export declare function describeChallenge(headerValue: string, additions: ChallengeAdditions): string | undefined;
package/dist/x402.js CHANGED
@@ -1,13 +1,48 @@
1
1
  import { ASK } from "./ask.js";
2
+ import { addContextToBazaar } from "./bazaar.js";
2
3
  import { ISSUES, PROTOCOL } from "./values.js";
3
4
  /** Key of the Forge extension in x402 v2 `extensions`: in the 402 challenge (next to e.g. `bazaar`) and in the payment receipt. */
4
5
  export const FEEDBACK_EXTENSION = "forge-feedback";
6
+ /** Key of the object the SDK adds to paid JSON response bodies: feedback_id, feedback_url, and optionally rate_this_call. */
7
+ export const FEEDBACK_FIELD = "forge_feedback";
8
+ const originOf = (url) => {
9
+ try {
10
+ const parsed = new URL(String(url));
11
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.origin : undefined;
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ };
17
+ /**
18
+ * The service origin a challenge was issued for: v2 `resource.url` (header or body), or v1 `accepts[].resource`.
19
+ * Used for absolute rating links when no origin is configured or registered. Never throws.
20
+ */
21
+ export function challengeOrigin(challenge) {
22
+ try {
23
+ const value = typeof challenge === "string" ? JSON.parse(Buffer.from(challenge, "base64").toString("utf8")) : challenge;
24
+ const resource = value?.resource?.url ?? (Array.isArray(value?.accepts) ? value.accepts[0]?.resource : undefined);
25
+ return originOf(resource);
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ /** The service origin a payment was made for (x402 v2 `resource.url` in the payment header). Never throws. */
32
+ export function paymentOrigin(headerValue) {
33
+ try {
34
+ return originOf(JSON.parse(Buffer.from(headerValue, "base64").toString("utf8"))?.resource?.url);
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
5
40
  /**
6
41
  * The `forge-feedback` challenge extension: how to rate the call, as structured data. Clients that inspect
7
42
  * the 402 (e.g. `awal x402 details`) print every extension, so this reaches agents before they pay.
8
- * With `agentContext`, it also says how to report agent context with the paid request.
43
+ * Agent context is a separate switch with its own extension (`forge-agent-context`).
9
44
  */
10
- export function feedbackExtension(rateUrl, tone = "soft", agentContext) {
45
+ export function feedbackExtension(rateUrl, tone = "soft") {
11
46
  return {
12
47
  info: {
13
48
  protocol: PROTOCOL,
@@ -16,9 +51,8 @@ export function feedbackExtension(rateUrl, tone = "soft", agentContext) {
16
51
  rate: `GET ${rateUrl}?feedback_id=FEEDBACK_ID&outcome=fully`,
17
52
  outcome: ["fully", "partially", "no"],
18
53
  issue: { when: "The outcome is not fully. Tells the merchant what to fix.", values: Object.keys(ISSUES) },
19
- feedback_id: "In the paid response body (feedback_id) and the Forge-Feedback-Id header.",
54
+ feedback_id: `In the paid response body (${FEEDBACK_FIELD}.feedback_id) and the Forge-Feedback-Id header.`,
20
55
  payment: "None. Plain GET, not an x402 endpoint.",
21
- ...(agentContext ? { agent_context: agentContext } : {}),
22
56
  },
23
57
  };
24
58
  }
@@ -57,16 +91,31 @@ export function describeReceipt(headerValue, extension) {
57
91
  receipt.extensions = { ...extensions, [FEEDBACK_EXTENSION]: extension };
58
92
  return Buffer.from(JSON.stringify(receipt), "utf8").toString("base64");
59
93
  }
60
- function appendSentence(description, sentence, marker) {
94
+ /**
95
+ * The longest challenge description the SDK produces. Clients copy the description into the payment payload,
96
+ * and the CDP facilitator rejects a payload whose resource.description exceeds 500 characters, failing the payment.
97
+ */
98
+ export const MAX_DESCRIPTION = 500;
99
+ function appendSentence(description, sentence, marker, shortSentence) {
61
100
  const current = typeof description === "string" ? description.trim() : "";
62
- return current.includes(marker) ? current : current ? `${current} ${sentence}` : sentence;
101
+ if (current.includes(marker))
102
+ return current;
103
+ for (const candidate of [sentence, shortSentence]) {
104
+ if (!candidate)
105
+ continue;
106
+ const next = current ? `${current} ${candidate}` : candidate;
107
+ if (next.length <= MAX_DESCRIPTION)
108
+ return next;
109
+ }
110
+ // Nothing fits: the forge-feedback extension still carries the ask.
111
+ return current;
63
112
  }
64
113
  /** Apply additions to a v2 PaymentRequired in place. Returns whether anything changed. */
65
114
  function addToV2(challenge, add) {
66
115
  let changed = false;
67
116
  const resource = challenge.resource;
68
117
  if (add.sentence && resource && typeof resource === "object") {
69
- const next = appendSentence(resource.description, add.sentence, add.marker ?? add.sentence);
118
+ const next = appendSentence(resource.description, add.sentence, add.marker ?? add.sentence, add.shortSentence);
70
119
  if (next !== resource.description) {
71
120
  resource.description = next;
72
121
  changed = true;
@@ -81,17 +130,20 @@ function addToV2(challenge, add) {
81
130
  changed = true;
82
131
  }
83
132
  else if (typeof extensions === "object" && !Array.isArray(extensions) && !(key in extensions)) {
84
- // Added last, so the merchant's own extensions (e.g. bazaar) keep their order and content.
133
+ // Added last, so the merchant's own extensions (e.g. bazaar) keep their order.
85
134
  challenge.extensions = { ...extensions, [key]: extension };
86
135
  changed = true;
87
136
  }
88
137
  }
138
+ const extensions = challenge.extensions;
139
+ if (add.bazaarContext && extensions && typeof extensions === "object" && addContextToBazaar(extensions.bazaar, add.bazaarContext))
140
+ changed = true;
89
141
  return changed;
90
142
  }
91
143
  /**
92
- * Add the rating sentence and/or the forge-feedback extension to a base64 PAYMENT-REQUIRED header (x402 v2).
93
- * `accepts` is untouched: v2 matches payments on `accepts`, and @x402/core only checks echoed extensions
94
- * the server itself advertised, so an added extension doesn't affect payment.
144
+ * Add the rating sentence, Forge's extensions and Bazaar agent context to a base64 PAYMENT-REQUIRED header (x402 v2).
145
+ * `accepts` is untouched: v2 matches payments on `accepts`. @x402/core checks that each echoed extension's `info`
146
+ * contains what the server advertised, so added extensions and added Bazaar fields don't affect payment.
95
147
  * Returns undefined when the header can't be parsed or already has everything.
96
148
  */
97
149
  export function describeChallenge(headerValue, additions) {
@@ -124,7 +176,7 @@ export function describeChallengeBody(body, additions) {
124
176
  const marker = additions.marker ?? sentence;
125
177
  return {
126
178
  ...b,
127
- accepts: b.accepts.map((a) => a && typeof a === "object" ? { ...a, description: appendSentence(a.description, sentence, marker) } : a),
179
+ accepts: b.accepts.map((a) => a && typeof a === "object" ? { ...a, description: appendSentence(a.description, sentence, marker, additions.shortSentence) } : a),
128
180
  };
129
181
  }
130
182
  if (b.x402Version === 2 && b.resource && typeof b.resource === "object") {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@forgeintel/sdk",
3
- "version": "0.5.0-beta.1",
4
- "description": "The Forge SDK for x402 paid APIs: agent feedback (feedback IDs, one-request GET ratings), agent context, OpenAPI and challenge enrichment, and passive call signals. Express, Hono, Next.js and any fetch handler. Never on your critical path.",
3
+ "version": "0.5.0-beta.11",
4
+ "description": "The Forge SDK for x402 paid APIs: agent feedback, agent context, OpenAPI and challenge enrichment, and passive call signals. Express, Hono, Next.js and fetch handlers. No Forge network request on the merchant response path.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "engines": {
@@ -73,7 +73,7 @@
73
73
  },
74
74
  "publishConfig": {
75
75
  "access": "public",
76
- "tag": "beta"
76
+ "tag": "latest"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "express": ">=4.21 <6",