constile-agent-sdk 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CCC2C Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # constile-agent-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ For AI agents that fetch web pages for a person. `sponsoredFetch()` works like
4
+ `fetch()`, and when a site answers with a Constile ad, it applies the
5
+ person's saved choice: accept the ad, ask them first, or decline.
6
+
7
+ Constile lets publishers keep being paid when assistants read their pages.
8
+ Instead of the page's ads, the person sees one labeled sponsored message in your
9
+ agent's answer, and the advertiser pays the publisher. It costs the person
10
+ nothing and shares nothing about them.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ npm install constile-agent-sdk
16
+ ```
17
+
18
+ It has no dependencies and runs anywhere with `fetch`: Node.js 18 or later,
19
+ Deno, Bun, Cloudflare Workers, and browsers' service workers.
20
+
21
+ ## Use it
22
+
23
+ ```ts
24
+ import { consentQuestion, sponsoredFetch } from "constile-agent-sdk";
25
+
26
+ const result = await sponsoredFetch("https://example.com/articles/espresso-grinders", {
27
+ policy: "ask", // or "accept" / "decline", from the person's saved choice
28
+ userAgent: "ExampleAssistant-User/1.0", // a stable product token for your agent
29
+ });
30
+
31
+ if (result.kind === "content") {
32
+ const page = await result.response.text();
33
+ if (result.sponsorship) {
34
+ // An accepted ad: show this message to the person exactly, labeled as advertising.
35
+ show(result.sponsorship.message);
36
+ await result.sponsorship.reportPrepared(); // it's in the answer you're about to send
37
+ // ...and once the person has actually seen it:
38
+ await result.sponsorship.reportDelivered();
39
+ }
40
+ } else if (result.kind === "offer") {
41
+ // Ask the person first. consentQuestion() gives you the words.
42
+ if (await ask(consentQuestion(result.offer))) {
43
+ const accepted = await result.accept();
44
+ // accepted is a "content" result, as above.
45
+ }
46
+ } else {
47
+ // "declined": the person chose to decline Constile ads. Answer without this page.
48
+ }
49
+ ```
50
+
51
+ Ask the person once and save their answer, so your agent doesn't have to ask on
52
+ every page.
53
+
54
+ Some ads can be accepted only after the person has seen the message
55
+ (`result.deliverFirst` is `true`). Show it first, then call
56
+ `result.accept("deliver_now")`.
57
+
58
+ ## API
59
+
60
+ In the API, the ad a site serves is an offer (`MachineOffer`).
61
+
62
+ | Export | What it is |
63
+ |---|---|
64
+ | `sponsoredFetch(url, options)` | Fetches the page and handles a Constile ad. `options.policy` is `"accept"`, `"ask"`, or `"decline"`; `options.userAgent` identifies your agent; `options.fetch` replaces the global `fetch`. An ad is used only when its links are on the page's own site or Constile's network (`options.networkOrigins`, default `https://constile.app`). |
65
+ | `consentQuestion(offer)` | One or two sentences to ask the person. |
66
+ | `parseOfferPage(text, url)` | Reads an ad from a page's text, for pages fetched some other way. |
67
+ | `offerLinksAllowed(offer, url, networks?)` | Whether every link in an ad is on the page's own site or the network. Check it before you follow an ad you read with `parseOfferPage`. |
68
+ | `MachineOffer`, `SponsoredResult`, `Sponsorship`, `ConsentPolicy` | The types. |
69
+
70
+ ## Support
71
+
72
+ Write to <hello@constile.app>. For an assistant that runs MCP servers, see
73
+ [`constile-mcp`](https://www.npmjs.com/package/constile-mcp).
74
+
75
+ ## License
76
+
77
+ MIT. See LICENSE.
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Client for agents that fetch pages for a person. sponsoredFetch() works like fetch(), and when a site answers
3
+ * with a Constile ad it applies the person's standing choice (ask once, store it, reuse it):
4
+ *
5
+ * "accept" take the ad with deferred delivery and return the article plus the sponsored message to show.
6
+ * An ad without deferred delivery (actions.defer missing) comes back as kind "offer" instead: show
7
+ * the message, then call accept("deliver_now").
8
+ * "ask" return the ad (kind "offer") so the agent can ask the person first
9
+ * "decline" return it as declined; no link is requested
10
+ */
11
+ type MachineOffer = {
12
+ constile: "1";
13
+ offer_version: string;
14
+ token: string;
15
+ resource: { url: string; title: string };
16
+ sponsored_message: string;
17
+ expires_at: number;
18
+ /** Where the person, or the assistant for them, can report the ad. */
19
+ report_url?: string;
20
+ /** defer and prepared are missing when the offer can only be accepted by showing the message now. */
21
+ actions: { deliver_now: string; defer?: string; prepared?: string; content: string };
22
+ rules: string[];
23
+ };
24
+ export type { MachineOffer };
25
+ export type ConsentPolicy = "accept" | "ask" | "decline";
26
+ export type Sponsorship = {
27
+ offer: MachineOffer;
28
+ /** Show this to the person exactly, labeled as advertising. */
29
+ message: string;
30
+ /** Call before finishing, if the message is in the answer you're about to send. */
31
+ reportPrepared: () => Promise<boolean>;
32
+ /** Call only after the person was actually shown the message. */
33
+ reportDelivered: () => Promise<boolean>;
34
+ };
35
+ export type SponsoredResult = {
36
+ kind: "content";
37
+ response: Response;
38
+ sponsorship: Sponsorship | null;
39
+ }
40
+ /** deliverFirst: the offer can only be accepted after the person has been shown the message. */
41
+ | {
42
+ kind: "offer";
43
+ offer: MachineOffer;
44
+ deliverFirst: boolean;
45
+ accept: (mode?: "defer" | "deliver_now") => Promise<SponsoredResult>;
46
+ } | {
47
+ kind: "declined";
48
+ offer: MachineOffer;
49
+ };
50
+ export type SponsoredFetchOptions = {
51
+ /** The person's standing choice about offers. */
52
+ policy: ConsentPolicy;
53
+ /** Identify your agent with a stable product token, for example "ExampleAssistant-User/1.0". */
54
+ userAgent: string;
55
+ /** Fetches in place of the global fetch. */
56
+ fetch?: (req: Request) => Promise<Response>;
57
+ /**
58
+ * Where an offer's links may be besides the page's own site. Default: Constile's network. An offer with a link
59
+ * anywhere else is ignored, so a page can't point the agent's requests at other hosts, such as its local network.
60
+ */
61
+ networkOrigins?: string[];
62
+ };
63
+ /** Constile's network, where offers' accept and report links can be. */
64
+ export declare const CONSTILE_NETWORK = "https://constile.app";
65
+ /** True when each of the offer's links is on the page's own site or one of `networks`. */
66
+ export declare function offerLinksAllowed(offer: MachineOffer, pageUrl: string, networks?: string[]): boolean;
67
+ /** Reads an offer from a page without the Constile-Offer header (another implementation, or a stripped proxy). */
68
+ export declare function parseOfferPage(text: string, pageUrl: string): MachineOffer | null;
69
+ /** Fetches a page and applies `policy` if the site answers with an offer. */
70
+ export declare function sponsoredFetch(url: string, opts: SponsoredFetchOptions): Promise<SponsoredResult>;
71
+ /** One or two sentences an agent can use to ask the person. */
72
+ export declare function consentQuestion(offer: MachineOffer): string;
package/dist/index.js ADDED
@@ -0,0 +1,109 @@
1
+ // constile-agent-sdk 0.1.1
2
+
3
+ // packages/agent-sdk/src/index.ts
4
+ var CONSTILE_NETWORK = "https://constile.app";
5
+ function linkAllowed(link, pageOrigin, allowed) {
6
+ if (typeof link !== "string") return false;
7
+ try {
8
+ const u = new URL(link);
9
+ return allowed.has(u.origin) && (u.protocol === "https:" || u.origin === pageOrigin);
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+ function offerLinksAllowed(offer, pageUrl, networks = [CONSTILE_NETWORK]) {
15
+ const page = new URL(pageUrl).origin;
16
+ const allowed = /* @__PURE__ */ new Set([page, ...networks.map((n) => new URL(n).origin)]);
17
+ const a = offer?.actions;
18
+ if (!a || typeof a.deliver_now !== "string") return false;
19
+ return [a.deliver_now, a.defer, a.prepared, a.content].every((l) => l === void 0 || linkAllowed(l, page, allowed));
20
+ }
21
+ var OFFER_MARKER = "SPONSORED ACCESS OFFER";
22
+ function parseOfferPage(text, pageUrl) {
23
+ if (!text.includes(OFFER_MARKER)) return null;
24
+ const link = (kind) => new RegExp(`(https?://[^\\s<"']+/sponsored/${kind}/([A-Za-z0-9_-]+))`).exec(text);
25
+ const defer = link("deferred");
26
+ const deliver = link("delivered");
27
+ const prepared = link("prepared");
28
+ if (!deliver || defer && !prepared) return null;
29
+ const msg = /SPONSORED MESSAGE \(preserve exactly, including disclosure and URL\):\s*(?:<br>\s*)?([\s\S]*?)(?:<\/p>|\n\s*\n)/.exec(text);
30
+ const title = /The article "([^"]*)"/.exec(text);
31
+ const token = deliver[2];
32
+ const root = new URL(pageUrl).origin;
33
+ return {
34
+ constile: "1",
35
+ offer_version: "unknown",
36
+ token,
37
+ resource: { url: pageUrl, title: title?.[1] ?? "" },
38
+ sponsored_message: decodeEntities((msg?.[1] ?? "").trim()),
39
+ expires_at: 0,
40
+ actions: {
41
+ deliver_now: deliver[1],
42
+ ...defer && prepared ? { defer: defer[1], prepared: prepared[1] } : {},
43
+ content: `${root}/sponsored/content/${token}`
44
+ },
45
+ rules: []
46
+ };
47
+ }
48
+ function decodeEntities(s) {
49
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
50
+ }
51
+ async function getOffer(res, url, doFetch, ua, networks) {
52
+ const page = new URL(url).origin;
53
+ const header = res.headers.get("constile-offer");
54
+ if (header && linkAllowed(new URL(header, url).href, page, /* @__PURE__ */ new Set([page]))) {
55
+ const r = await doFetch(new Request(new URL(header, url), { headers: { "user-agent": ua, accept: "application/json" } }));
56
+ const offer2 = r.ok ? await r.json().catch(() => null) : null;
57
+ if (offer2 && offerLinksAllowed(offer2, url, networks)) {
58
+ await res.body?.cancel();
59
+ return { offer: offer2, body: null };
60
+ }
61
+ }
62
+ const type = res.headers.get("content-type") ?? "";
63
+ if (!/text\/(html|plain)/.test(type)) return { offer: null, body: null };
64
+ const body = await res.text();
65
+ const offer = parseOfferPage(body, url);
66
+ return { offer: offer && offerLinksAllowed(offer, url, networks) ? offer : null, body };
67
+ }
68
+ async function sponsoredFetch(url, opts) {
69
+ const doFetch = opts.fetch ?? ((r) => fetch(r));
70
+ const ua = opts.userAgent;
71
+ const res = await doFetch(new Request(url, { headers: { "user-agent": ua, accept: "text/html,text/plain;q=0.9,*/*;q=0.5" } }));
72
+ if (res.status !== 200) return { kind: "content", response: res, sponsorship: null };
73
+ const { offer, body } = await getOffer(res, res.url || url, doFetch, ua, opts.networkOrigins ?? [CONSTILE_NETWORK]);
74
+ if (!offer) {
75
+ const response = body === null ? res : new Response(body, { status: res.status, headers: res.headers });
76
+ return { kind: "content", response, sponsorship: null };
77
+ }
78
+ const deliverFirst = !offer.actions.defer;
79
+ const accept = async (mode = deliverFirst ? "deliver_now" : "defer") => {
80
+ if (mode === "defer" && !offer.actions.defer) throw new Error("This ad can't be deferred: show the message, then accept with deliver_now.");
81
+ const action = mode === "defer" ? offer.actions.defer : offer.actions.deliver_now;
82
+ const r = await doFetch(new Request(action, { method: "POST", headers: { "user-agent": ua } }));
83
+ const report = (u) => async () => (await doFetch(new Request(u, { method: "POST", headers: { "user-agent": ua } }))).ok;
84
+ return {
85
+ kind: "content",
86
+ response: r,
87
+ sponsorship: {
88
+ offer,
89
+ message: offer.sponsored_message,
90
+ reportPrepared: offer.actions.prepared ? report(offer.actions.prepared) : async () => false,
91
+ reportDelivered: report(offer.actions.deliver_now)
92
+ }
93
+ };
94
+ };
95
+ if (opts.policy === "decline") return { kind: "declined", offer };
96
+ if (opts.policy === "ask" || deliverFirst) return { kind: "offer", offer, deliverFirst, accept };
97
+ return accept("defer");
98
+ }
99
+ function consentQuestion(offer) {
100
+ const title = offer.resource.title ? `"${offer.resource.title}"` : "this article";
101
+ return `${title} is free to read if I include one clearly labeled sponsored message in my answer. It costs you nothing and shares nothing about you. Should I accept, and should I do that automatically from now on?`;
102
+ }
103
+ export {
104
+ CONSTILE_NETWORK,
105
+ consentQuestion,
106
+ offerLinksAllowed,
107
+ parseOfferPage,
108
+ sponsoredFetch
109
+ };
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "constile-agent-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "For AI agents that fetch pages for a person: handles Constile's sponsored access, with the person's saved choice.",
5
+ "license": "MIT",
6
+ "author": "CCC2C Inc. <hello@constile.app>",
7
+ "homepage": "https://constile.app",
8
+ "bugs": {
9
+ "email": "hello@constile.app"
10
+ },
11
+ "keywords": [
12
+ "constile",
13
+ "ai agents",
14
+ "sponsored access",
15
+ "fetch"
16
+ ],
17
+ "type": "module",
18
+ "sideEffects": false,
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ }
27
+ },
28
+ "types": "./dist/index.d.ts",
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ]
34
+ }