@tangle-network/agent-app 0.60.7 → 0.60.8

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.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ agentSurfaceFiles
4
+ } from "../chunk-C5RHSYUA.js";
5
+
6
+ // src/agent-surfaces/generate.ts
7
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
8
+ import { dirname, join, resolve } from "path";
9
+ function readExisting(path) {
10
+ try {
11
+ return readFileSync(path, "utf8");
12
+ } catch {
13
+ return void 0;
14
+ }
15
+ }
16
+ function runAgentSurfacesCli(argv) {
17
+ const [configPath, ...rest] = argv;
18
+ const outIndex = rest.indexOf("--out");
19
+ const outDir = outIndex >= 0 ? rest[outIndex + 1] : void 0;
20
+ const check = rest.includes("--check");
21
+ if (!configPath || !outDir) {
22
+ console.error("Usage: agent-app-agent-surfaces <config.json> --out <dir> [--check]");
23
+ return 2;
24
+ }
25
+ const config = JSON.parse(readFileSync(resolve(configPath), "utf8"));
26
+ const stale = [];
27
+ for (const file of agentSurfaceFiles(config)) {
28
+ const target = join(resolve(outDir), file.path);
29
+ if (readExisting(target) === file.body) continue;
30
+ if (check) {
31
+ stale.push(file.path);
32
+ continue;
33
+ }
34
+ mkdirSync(dirname(target), { recursive: true });
35
+ writeFileSync(target, file.body);
36
+ console.log(`wrote ${file.path}`);
37
+ }
38
+ if (stale.length > 0) {
39
+ console.error(
40
+ `Agent surfaces are stale: ${stale.join(", ")}. Regenerate with: agent-app-agent-surfaces ${configPath} --out ${outDir}`
41
+ );
42
+ return 1;
43
+ }
44
+ return 0;
45
+ }
46
+
47
+ // src/agent-surfaces/cli.ts
48
+ process.exit(runAgentSurfacesCli(process.argv.slice(2)));
49
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/agent-surfaces/generate.ts","../../src/agent-surfaces/cli.ts"],"sourcesContent":["/**\n * Writes or checks a product's agent surfaces as static files. Node-only; the\n * `agent-app-agent-surfaces` bin wraps it.\n */\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { type AgentSurfaceConfig, agentSurfaceFiles } from './index'\n\nfunction readExisting(path: string): string | undefined {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n}\n\nexport function runAgentSurfacesCli(argv: readonly string[]): number {\n const [configPath, ...rest] = argv\n const outIndex = rest.indexOf('--out')\n const outDir = outIndex >= 0 ? rest[outIndex + 1] : undefined\n const check = rest.includes('--check')\n if (!configPath || !outDir) {\n console.error('Usage: agent-app-agent-surfaces <config.json> --out <dir> [--check]')\n return 2\n }\n const config = JSON.parse(readFileSync(resolve(configPath), 'utf8')) as AgentSurfaceConfig\n const stale: string[] = []\n for (const file of agentSurfaceFiles(config)) {\n const target = join(resolve(outDir), file.path)\n if (readExisting(target) === file.body) continue\n if (check) {\n stale.push(file.path)\n continue\n }\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, file.body)\n console.log(`wrote ${file.path}`)\n }\n if (stale.length > 0) {\n console.error(\n `Agent surfaces are stale: ${stale.join(', ')}. Regenerate with: agent-app-agent-surfaces ${configPath} --out ${outDir}`,\n )\n return 1\n }\n return 0\n}\n\n","#!/usr/bin/env node\n/**\n * `agent-app-agent-surfaces <config.json> --out <dir> [--check]`\n *\n * Writes a product's agent surfaces as static files, for products that serve\n * them as assets. `--check` writes nothing and exits 1 when a committed file\n * differs from what the config generates, so product docs cannot drift from\n * the shared source. Exit 2 is a usage error.\n */\nimport { runAgentSurfacesCli } from './generate'\n\nprocess.exit(runAgentSurfacesCli(process.argv.slice(2)))\n"],"mappings":";;;;;;AAIA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,SAAS,MAAM,eAAe;AAGvC,SAAS,aAAa,MAAkC;AACtD,MAAI;AACF,WAAO,aAAa,MAAM,MAAM;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,oBAAoB,MAAiC;AACnE,QAAM,CAAC,YAAY,GAAG,IAAI,IAAI;AAC9B,QAAM,WAAW,KAAK,QAAQ,OAAO;AACrC,QAAM,SAAS,YAAY,IAAI,KAAK,WAAW,CAAC,IAAI;AACpD,QAAM,QAAQ,KAAK,SAAS,SAAS;AACrC,MAAI,CAAC,cAAc,CAAC,QAAQ;AAC1B,YAAQ,MAAM,qEAAqE;AACnF,WAAO;AAAA,EACT;AACA,QAAM,SAAS,KAAK,MAAM,aAAa,QAAQ,UAAU,GAAG,MAAM,CAAC;AACnE,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,kBAAkB,MAAM,GAAG;AAC5C,UAAM,SAAS,KAAK,QAAQ,MAAM,GAAG,KAAK,IAAI;AAC9C,QAAI,aAAa,MAAM,MAAM,KAAK,KAAM;AACxC,QAAI,OAAO;AACT,YAAM,KAAK,KAAK,IAAI;AACpB;AAAA,IACF;AACA,cAAU,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAC9C,kBAAc,QAAQ,KAAK,IAAI;AAC/B,YAAQ,IAAI,SAAS,KAAK,IAAI,EAAE;AAAA,EAClC;AACA,MAAI,MAAM,SAAS,GAAG;AACpB,YAAQ;AAAA,MACN,6BAA6B,MAAM,KAAK,IAAI,CAAC,+CAA+C,UAAU,UAAU,MAAM;AAAA,IACxH;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AClCA,QAAQ,KAAK,oBAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC;","names":[]}
@@ -0,0 +1 @@
1
+ export declare function runAgentSurfacesCli(argv: readonly string[]): number;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Machine-readable surfaces for a Tangle product, generated from one config.
3
+ *
4
+ * Every product publishes the same four things an AI agent needs to become a
5
+ * customer without a human doing the setup:
6
+ *
7
+ * - `/agent-setup.md`: a SKILL.md (Claude Code and Codex skill format) that
8
+ * doubles as a copy-paste prompt. It takes a fresh agent from nothing to a
9
+ * verified first call: one owner approval, a scoped key, install, call.
10
+ * - `/llms.txt`: the llms.txt index, pointing at the setup skill first.
11
+ * - `/.well-known/tangle-agent.json`: the Tangle agent manifest.
12
+ * - Markdown for `Accept: text/markdown` on the product's pages, with
13
+ * `Vary: Accept` on both representations so caches keep them apart.
14
+ *
15
+ * The signup section is rendered here, not in product config, so every
16
+ * product describes Platform's agent signup identically and cannot drift.
17
+ *
18
+ * Web-standard `Request`/`Response` only: safe in Workers, Node and browsers.
19
+ */
20
+ /** Manifest schema this module emits. Additive over the 2026-06-16 shape. */
21
+ export declare const AGENT_MANIFEST_SCHEMA_VERSION = "2026-10-09";
22
+ export declare const TANGLE_PLATFORM_ORIGIN = "https://id.tangle.tools";
23
+ export interface AgentSurfaceStep {
24
+ title: string;
25
+ /** Fence language for the code block. */
26
+ language: 'bash' | 'js' | 'ts' | 'python' | 'json';
27
+ code: string;
28
+ /** What a successful run prints or returns. */
29
+ expect: string;
30
+ }
31
+ export interface AgentSurfaceError {
32
+ symptom: string;
33
+ cause: string;
34
+ fix: string;
35
+ }
36
+ export interface AgentSurfaceLink {
37
+ label: string;
38
+ url: string;
39
+ }
40
+ /**
41
+ * How an agent obtains a key. `device` uses Platform's agent signup: the owner
42
+ * approves once and the agent receives its own capped, revocable key.
43
+ */
44
+ export type AgentSignup = {
45
+ kind: 'device';
46
+ /** Platform trusted-app id the key is minted for (`sandbox`, `router`). */
47
+ app: string;
48
+ /** Default lifetime spend cap the skill asks for, in USD. */
49
+ budgetUsd?: number;
50
+ } | {
51
+ kind: 'manual';
52
+ /** Numbered steps the owner performs; each one is a human input. */
53
+ steps: string[];
54
+ };
55
+ export interface AgentSurfaceConfig {
56
+ /** Short id used in the skill name: `tangle-<id>-setup`. */
57
+ id: string;
58
+ name: string;
59
+ /** Public HTTPS origin, no trailing slash. */
60
+ origin: string;
61
+ /** What the product is for, in one to three plain sentences. */
62
+ summary: string;
63
+ useWhen: string[];
64
+ signup: AgentSignup;
65
+ /** Environment variable the key is exported as. */
66
+ apiKeyEnv: string;
67
+ /** Runtime prerequisites a fresh machine needs, e.g. `Node.js 20 or newer`. */
68
+ prerequisites: string[];
69
+ install: AgentSurfaceStep[];
70
+ firstCall: AgentSurfaceStep[];
71
+ verify: AgentSurfaceStep[];
72
+ errors: AgentSurfaceError[];
73
+ pricing: {
74
+ /** Plain statement of how usage is charged. */
75
+ summary: string;
76
+ /** Public, credential-free price data an agent can quote from. */
77
+ quoteUrl?: string;
78
+ url?: string;
79
+ };
80
+ next: AgentSurfaceLink[];
81
+ docs?: string;
82
+ openapi?: string;
83
+ mcp?: {
84
+ url: string;
85
+ auth: string;
86
+ };
87
+ related?: Array<{
88
+ name: string;
89
+ manifest?: string;
90
+ url?: string;
91
+ }>;
92
+ /** Extra manifest fields a product already publishes (kept verbatim). */
93
+ manifest?: Record<string, unknown>;
94
+ }
95
+ export interface AgentSurfaceFile {
96
+ path: string;
97
+ contentType: string;
98
+ body: string;
99
+ }
100
+ /**
101
+ * The signup script the skill tells an agent to save and run. Node 18+ only,
102
+ * no dependencies. It never prints the key; it writes `.tangle/api-key` with
103
+ * mode 0600 and reports whether the owner's account can pay yet.
104
+ */
105
+ export declare function agentSignupScript(platformOrigin?: string): string;
106
+ /** The agent setup skill: valid SKILL.md and a plain copy-paste prompt. */
107
+ export declare function renderAgentSetupSkill(config: AgentSurfaceConfig): string;
108
+ /** llms.txt index for the product. The setup skill is the first link. */
109
+ export declare function renderLlmsTxt(config: AgentSurfaceConfig): string;
110
+ /** Markdown for the product's home page, served for `Accept: text/markdown`. */
111
+ export declare function renderHomeMarkdown(config: AgentSurfaceConfig): string;
112
+ /** The `/.well-known/tangle-agent.json` document. */
113
+ export declare function renderAgentManifest(config: AgentSurfaceConfig): Record<string, unknown>;
114
+ /** Every static surface as files, for products that ship them as assets. */
115
+ export declare function agentSurfaceFiles(config: AgentSurfaceConfig): AgentSurfaceFile[];
116
+ /**
117
+ * True when `Accept` ranks `text/markdown` strictly above `text/html` and
118
+ * gives it a nonzero weight. A browser's default header never does.
119
+ */
120
+ export declare function prefersMarkdown(accept: string | null | undefined): boolean;
121
+ /** A copy of `response` whose `Vary` includes `Accept`. */
122
+ export declare function withVaryAccept(response: Response): Response;
123
+ export interface AgentSurfaceHandler {
124
+ /**
125
+ * Answers a surface request (`/agent-setup.md`, `/llms.txt`, the manifest,
126
+ * or a negotiated markdown page), or `null` to let the app answer it.
127
+ */
128
+ handle(request: Request): Response | null;
129
+ /** Adds `Vary: Accept` when the path has a markdown representation. */
130
+ finalize(request: Request, response: Response): Response;
131
+ }
132
+ /**
133
+ * Request handler over {@link agentSurfaceFiles}. `markdownPages` maps extra
134
+ * HTML paths to markdown served on negotiation; `/` always maps to the home
135
+ * markdown.
136
+ */
137
+ export declare function createAgentSurfaceHandler(config: AgentSurfaceConfig, options?: {
138
+ markdownPages?: Record<string, string>;
139
+ }): AgentSurfaceHandler;
@@ -0,0 +1,27 @@
1
+ import {
2
+ AGENT_MANIFEST_SCHEMA_VERSION,
3
+ TANGLE_PLATFORM_ORIGIN,
4
+ agentSignupScript,
5
+ agentSurfaceFiles,
6
+ createAgentSurfaceHandler,
7
+ prefersMarkdown,
8
+ renderAgentManifest,
9
+ renderAgentSetupSkill,
10
+ renderHomeMarkdown,
11
+ renderLlmsTxt,
12
+ withVaryAccept
13
+ } from "../chunk-C5RHSYUA.js";
14
+ export {
15
+ AGENT_MANIFEST_SCHEMA_VERSION,
16
+ TANGLE_PLATFORM_ORIGIN,
17
+ agentSignupScript,
18
+ agentSurfaceFiles,
19
+ createAgentSurfaceHandler,
20
+ prefersMarkdown,
21
+ renderAgentManifest,
22
+ renderAgentSetupSkill,
23
+ renderHomeMarkdown,
24
+ renderLlmsTxt,
25
+ withVaryAccept
26
+ };
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  chatToolCallPart
3
- } from "../chunk-GJRGCVDV.js";
3
+ } from "../chunk-MUZQUS6X.js";
4
4
  import "../chunk-FAU5FIFD.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
- import "../chunk-E4AY62T2.js";
7
6
  import "../chunk-FBVLEGEG.js";
7
+ import "../chunk-KHCJKVQN.js";
8
+ import "../chunk-XEURJVS5.js";
9
+ import "../chunk-E4AY62T2.js";
8
10
  import "../chunk-Y6PRDUFJ.js";
9
11
  import "../chunk-GEYACSFW.js";
10
12
  import {
11
13
  ChatComposer
12
14
  } from "../chunk-DECJLOS4.js";
13
15
  import "../chunk-L7MB2LLM.js";
14
- import "../chunk-KHCJKVQN.js";
15
- import "../chunk-XEURJVS5.js";
16
16
  import "../chunk-NJDQ2JCP.js";
17
17
  import {
18
18
  ModelPicker
@@ -11,4 +11,4 @@ export {
11
11
  DesignCanvasLazy,
12
12
  DesignCanvasChromeLazy
13
13
  };
14
- //# sourceMappingURL=chunk-CN5HNTU6.js.map
14
+ //# sourceMappingURL=chunk-AKC5ZC4R.js.map
@@ -0,0 +1,376 @@
1
+ // src/agent-surfaces/index.ts
2
+ var AGENT_MANIFEST_SCHEMA_VERSION = "2026-10-09";
3
+ var TANGLE_PLATFORM_ORIGIN = "https://id.tangle.tools";
4
+ var MARKDOWN = "text/markdown; charset=utf-8";
5
+ function trimOrigin(origin) {
6
+ return origin.replace(/\/+$/, "");
7
+ }
8
+ function fence(step) {
9
+ return ["```" + step.language, step.code.trimEnd(), "```"].join("\n");
10
+ }
11
+ function agentSignupScript(platformOrigin = TANGLE_PLATFORM_ORIGIN) {
12
+ return `// Requests a scoped Tangle key for this agent. The owner approves once.
13
+ import { mkdirSync, writeFileSync } from ${JSON.stringify("node:fs")}
14
+
15
+ const flag = (name) => {
16
+ const index = process.argv.indexOf(\`--\${name}\`)
17
+ return index > 0 ? process.argv[index + 1] : undefined
18
+ }
19
+ const platform = '${trimOrigin(platformOrigin)}'
20
+ const app = flag('app')
21
+ if (!app) throw new Error('Pass --app (for example --app sandbox)')
22
+ const request = { app, agent_name: flag('agent-name') ?? 'coding-agent' }
23
+ if (flag('owner-email')) request.owner_email = flag('owner-email')
24
+ if (flag('budget-usd')) request.budget_usd = Number(flag('budget-usd'))
25
+
26
+ async function post(path, body) {
27
+ const response = await fetch(platform + path, {
28
+ method: 'POST',
29
+ headers: { 'content-type': 'application/json' },
30
+ body: JSON.stringify(body),
31
+ })
32
+ return { status: response.status, body: await response.json().catch(() => ({})) }
33
+ }
34
+
35
+ const started = await post('/cross-site/device/start', request)
36
+ if (started.status !== 200) {
37
+ console.error(\`Signup refused (HTTP \${started.status}): \${JSON.stringify(started.body)}\`)
38
+ process.exit(1)
39
+ }
40
+ const grant = started.body.data
41
+ console.log(grant.agent?.owner_notified
42
+ ? \`Approval email sent to \${request.owner_email}.\`
43
+ : 'Send your owner this approval link.')
44
+ console.log(\`Approval link: \${grant.verification_uri_complete}\`)
45
+ console.log(\`Confirmation code: \${grant.user_code} (expires in \${Math.round(grant.expires_in / 60)} minutes)\`)
46
+ console.log('Waiting for approval...')
47
+
48
+ const deadline = Date.now() + grant.expires_in * 1000
49
+ while (Date.now() < deadline) {
50
+ await new Promise((resolve) => setTimeout(resolve, grant.interval * 1000))
51
+ const polled = await post('/cross-site/device/poll', { app, device_code: grant.device_code })
52
+ if (polled.status === 428) continue
53
+ if (polled.status !== 200) {
54
+ console.error(\`Approval failed (HTTP \${polled.status}): \${JSON.stringify(polled.body)}\`)
55
+ process.exit(1)
56
+ }
57
+ const { api_key: apiKey, key, account } = polled.body.data
58
+ mkdirSync('.tangle', { recursive: true, mode: 0o700 })
59
+ writeFileSync('.tangle/api-key', \`\${apiKey}\\n\`, { mode: 0o600 })
60
+ console.log(\`Approved. Key "\${key?.name ?? app}" saved to .tangle/api-key (spend cap $\${key?.budget_usd ?? 'none'}).\`)
61
+ if (account && !account.funded) {
62
+ console.log(\`The owner's account has no credit yet. Ask the owner to add credits: \${account.add_credits_url}\`)
63
+ }
64
+ process.exit(0)
65
+ }
66
+ console.error('The approval link expired. Run this script again.')
67
+ process.exit(1)
68
+ `;
69
+ }
70
+ function signupSection(config) {
71
+ const env = config.apiKeyEnv;
72
+ if (config.signup.kind === "manual") {
73
+ return [
74
+ "## 1. Get a key",
75
+ "",
76
+ "This product does not yet support agent signup. Ask your owner to do the following, then continue:",
77
+ "",
78
+ ...config.signup.steps.map((step, index) => `${index + 1}. ${step}`),
79
+ "",
80
+ `Store the key outside version control and export it as \`${env}\`. Never print, log, or commit it.`
81
+ ];
82
+ }
83
+ const budget = config.signup.budgetUsd ?? 25;
84
+ return [
85
+ "## 1. Get a scoped key (one owner approval)",
86
+ "",
87
+ "Tangle issues each agent its own key, owned by a person who approves it once.",
88
+ `Ask your owner which email address their Tangle account uses (or should use). Nothing is charged by signing up, and there is no free credit: ${config.name} work is paid from the owner's prepaid balance.`,
89
+ "",
90
+ "Save this script as `tangle-signup.mjs` (Node.js 18 or newer, no dependencies):",
91
+ "",
92
+ fence({ language: "js", code: agentSignupScript() }),
93
+ "",
94
+ "Run it with your own name and the owner's email:",
95
+ "",
96
+ fence({
97
+ language: "bash",
98
+ code: `node tangle-signup.mjs --app ${config.signup.app} --agent-name "<your agent name>" --owner-email "<owner email>" --budget-usd ${budget}`
99
+ }),
100
+ "",
101
+ "What happens:",
102
+ "",
103
+ `1. Tangle emails the owner a one-time approval link. If you cannot give an email, omit \`--owner-email\` and send the owner the printed link yourself.`,
104
+ "2. The owner signs in (or creates an account and verifies the email), checks the confirmation code, and approves. That is the only human step.",
105
+ `3. The script writes the key to \`.tangle/api-key\` (mode 600). It can only be used for ${config.name}, it can spend at most the cap you requested, and the owner can revoke it under Keys at any time.`,
106
+ "4. If the script says the account has no credit, ask the owner to add credits at the printed link before your first paid call.",
107
+ "",
108
+ "Then load the key without printing it, and keep it out of version control:",
109
+ "",
110
+ fence({
111
+ language: "bash",
112
+ code: `export ${env}="$(cat .tangle/api-key)"
113
+ grep -qxF '.tangle/' .gitignore 2>/dev/null || echo '.tangle/' >> .gitignore`
114
+ }),
115
+ "",
116
+ "Never print, log, paste, or commit the key."
117
+ ];
118
+ }
119
+ function stepsSection(heading, steps) {
120
+ if (steps.length === 0) return [];
121
+ const lines = [heading, ""];
122
+ for (const step of steps) {
123
+ lines.push(`${step.title}:`, "", fence(step), "", `Expected: ${step.expect}`, "");
124
+ }
125
+ return lines;
126
+ }
127
+ function renderAgentSetupSkill(config) {
128
+ const origin = trimOrigin(config.origin);
129
+ const description = `Set up ${config.name} for this agent end to end: get a scoped API key with one owner approval, install the client, make the first successful call, and verify it.`;
130
+ const lines = [
131
+ "---",
132
+ `name: tangle-${config.id}-setup`,
133
+ `description: ${description}`,
134
+ "---",
135
+ "",
136
+ `# Set up ${config.name}`,
137
+ "",
138
+ config.summary,
139
+ "",
140
+ "Use it when:",
141
+ "",
142
+ ...config.useWhen.map((item) => `- ${item}`),
143
+ "",
144
+ "Complete every step below in order and stop at the first failure; the error table at the end names the fix.",
145
+ "Prerequisites: " + config.prerequisites.join("; ") + ".",
146
+ "",
147
+ ...signupSection(config),
148
+ "",
149
+ ...stepsSection("## 2. Install", config.install),
150
+ ...stepsSection("## 3. Make the first call", config.firstCall),
151
+ ...stepsSection("## 4. Verify it worked", config.verify),
152
+ "## Common errors",
153
+ "",
154
+ "| Symptom | Cause | Fix |",
155
+ "| --- | --- | --- |",
156
+ ...config.errors.map(
157
+ (error) => `| ${error.symptom.replace(/\|/g, "\\|")} | ${error.cause.replace(/\|/g, "\\|")} | ${error.fix.replace(/\|/g, "\\|")} |`
158
+ ),
159
+ "",
160
+ "## Pricing",
161
+ "",
162
+ config.pricing.summary,
163
+ ...config.pricing.quoteUrl ? ["", `Current prices, no key needed: ${config.pricing.quoteUrl}`] : [],
164
+ ...config.pricing.url ? [`Pricing page: ${config.pricing.url}`] : [],
165
+ "",
166
+ "## Next",
167
+ "",
168
+ ...config.next.map((link) => `- [${link.label}](${link.url})`),
169
+ "",
170
+ "## Machine-readable surfaces",
171
+ "",
172
+ `- Agent manifest: ${origin}/.well-known/tangle-agent.json`,
173
+ `- llms.txt: ${origin}/llms.txt`,
174
+ `- This setup skill: ${origin}/agent-setup.md`,
175
+ ...config.openapi ? [`- OpenAPI: ${config.openapi}`] : [],
176
+ ...config.mcp ? [`- MCP server: ${config.mcp.url} (${config.mcp.auth})`] : [],
177
+ ""
178
+ ];
179
+ return lines.join("\n");
180
+ }
181
+ function renderLlmsTxt(config) {
182
+ const origin = trimOrigin(config.origin);
183
+ return [
184
+ `# ${config.name}`,
185
+ "",
186
+ `> ${config.summary}`,
187
+ "",
188
+ `To set this product up from scratch, fetch ${origin}/agent-setup.md and follow it. It is a complete prompt and a SKILL.md: one owner approval, a scoped key, install, first call, verification.`,
189
+ "",
190
+ "## Start here",
191
+ "",
192
+ `- [Agent setup skill](${origin}/agent-setup.md): from nothing to a verified first call`,
193
+ `- [Agent manifest](${origin}/.well-known/tangle-agent.json): machine-readable contract`,
194
+ ...config.openapi ? [`- [OpenAPI](${config.openapi}): HTTP API schema`] : [],
195
+ ...config.mcp ? [`- [MCP server](${config.mcp.url}): ${config.mcp.auth}`] : [],
196
+ ...config.docs ? [`- [Documentation](${config.docs})`] : [],
197
+ "",
198
+ "## Pricing",
199
+ "",
200
+ `- ${config.pricing.summary}`,
201
+ ...config.pricing.quoteUrl ? [`- [Machine-readable prices](${config.pricing.quoteUrl}): no key needed`] : [],
202
+ "",
203
+ "## Optional",
204
+ "",
205
+ ...config.next.map((link) => `- [${link.label}](${link.url})`),
206
+ ...(config.related ?? []).map(
207
+ (surface) => `- [${surface.name}](${surface.manifest ?? surface.url ?? ""})`
208
+ ),
209
+ ""
210
+ ].join("\n");
211
+ }
212
+ function renderHomeMarkdown(config) {
213
+ const origin = trimOrigin(config.origin);
214
+ return [
215
+ `# ${config.name}`,
216
+ "",
217
+ config.summary,
218
+ "",
219
+ "## Use it when",
220
+ "",
221
+ ...config.useWhen.map((item) => `- ${item}`),
222
+ "",
223
+ "## Hand this to your agent",
224
+ "",
225
+ `An AI agent can set ${config.name} up by itself: fetch ${origin}/agent-setup.md and follow it. The owner approves once; nothing else needs a human.`,
226
+ "",
227
+ "## Pricing",
228
+ "",
229
+ config.pricing.summary,
230
+ ...config.pricing.quoteUrl ? ["", `Machine-readable prices: ${config.pricing.quoteUrl}`] : [],
231
+ "",
232
+ "## Machine-readable surfaces",
233
+ "",
234
+ `- ${origin}/llms.txt`,
235
+ `- ${origin}/.well-known/tangle-agent.json`,
236
+ `- ${origin}/agent-setup.md`,
237
+ ...config.openapi ? [`- ${config.openapi}`] : [],
238
+ ...config.mcp ? [`- ${config.mcp.url}`] : [],
239
+ ""
240
+ ].join("\n");
241
+ }
242
+ function renderAgentManifest(config) {
243
+ const origin = trimOrigin(config.origin);
244
+ const signup = config.signup.kind === "device" ? {
245
+ kind: "device_authorization",
246
+ app: config.signup.app,
247
+ start: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/start`,
248
+ poll: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/poll`,
249
+ request: {
250
+ app: config.signup.app,
251
+ agent_name: "string, 1-64 characters",
252
+ owner_email: "optional; Tangle emails this owner the approval link",
253
+ budget_usd: `optional lifetime spend cap, 1-1000, default ${config.signup.budgetUsd ?? 25}`
254
+ },
255
+ human_inputs: ["The owner approves the request once."],
256
+ key: {
257
+ scope: `${config.signup.app} only`,
258
+ revocable_at: `${TANGLE_PLATFORM_ORIGIN}/app/keys`
259
+ },
260
+ payment: "Prepaid credit on the owner account. No free credit; paid calls are refused until the owner adds credits.",
261
+ add_credits: `${TANGLE_PLATFORM_ORIGIN}/app/billing`
262
+ } : { kind: "manual", steps: config.signup.steps };
263
+ return {
264
+ ...config.manifest,
265
+ schema_version: AGENT_MANIFEST_SCHEMA_VERSION,
266
+ name: config.name,
267
+ description: config.summary,
268
+ homepage: `${origin}/`,
269
+ llms: `${origin}/llms.txt`,
270
+ agent_setup: `${origin}/agent-setup.md`,
271
+ ...config.docs ? { docs: config.docs } : {},
272
+ ...config.openapi ? { openapi: config.openapi } : {},
273
+ ...config.mcp ? { mcp: config.mcp } : {},
274
+ environment: { api_key: config.apiKeyEnv },
275
+ signup,
276
+ pricing: {
277
+ summary: config.pricing.summary,
278
+ ...config.pricing.quoteUrl ? { quote: config.pricing.quoteUrl } : {},
279
+ ...config.pricing.url ? { page: config.pricing.url } : {}
280
+ },
281
+ ...config.related?.length ? { related_surfaces: config.related } : {}
282
+ };
283
+ }
284
+ function agentSurfaceFiles(config) {
285
+ return [
286
+ { path: "agent-setup.md", contentType: MARKDOWN, body: renderAgentSetupSkill(config) },
287
+ { path: "llms.txt", contentType: "text/plain; charset=utf-8", body: renderLlmsTxt(config) },
288
+ { path: "index.md", contentType: MARKDOWN, body: renderHomeMarkdown(config) },
289
+ {
290
+ path: ".well-known/tangle-agent.json",
291
+ contentType: "application/json; charset=utf-8",
292
+ body: `${JSON.stringify(renderAgentManifest(config), null, 2)}
293
+ `
294
+ }
295
+ ];
296
+ }
297
+ function prefersMarkdown(accept) {
298
+ if (!accept) return false;
299
+ let markdown = -1;
300
+ let html = -1;
301
+ for (const part of accept.split(",")) {
302
+ const [rawType, ...params] = part.trim().split(";");
303
+ const type = rawType?.trim().toLowerCase();
304
+ let quality = 1;
305
+ for (const param of params) {
306
+ const [key, value] = param.trim().split("=");
307
+ if (key?.trim().toLowerCase() === "q") {
308
+ const parsed = Number(value);
309
+ quality = Number.isFinite(parsed) ? parsed : 0;
310
+ }
311
+ }
312
+ if (type === "text/markdown") markdown = Math.max(markdown, quality);
313
+ if (type === "text/html") html = Math.max(html, quality);
314
+ }
315
+ return markdown > 0 && markdown > html;
316
+ }
317
+ function withVaryAccept(response) {
318
+ const vary = response.headers.get("vary");
319
+ if (vary && vary.split(",").some((value) => value.trim().toLowerCase() === "accept")) {
320
+ return response;
321
+ }
322
+ const headers = new Headers(response.headers);
323
+ headers.set("vary", vary ? `${vary}, Accept` : "Accept");
324
+ return new Response(response.body, {
325
+ status: response.status,
326
+ statusText: response.statusText,
327
+ headers
328
+ });
329
+ }
330
+ function createAgentSurfaceHandler(config, options = {}) {
331
+ const files = new Map(agentSurfaceFiles(config).map((file) => [`/${file.path}`, file]));
332
+ const negotiated = new Map([
333
+ ["/", renderHomeMarkdown(config)],
334
+ ...Object.entries(options.markdownPages ?? {})
335
+ ]);
336
+ function respond(body, contentType, method, vary) {
337
+ const headers = new Headers({
338
+ "content-type": contentType,
339
+ "cache-control": "public, max-age=300",
340
+ "x-content-type-options": "nosniff"
341
+ });
342
+ if (vary) headers.set("vary", "Accept");
343
+ return new Response(method === "HEAD" ? null : body, { status: 200, headers });
344
+ }
345
+ return {
346
+ handle(request) {
347
+ if (request.method !== "GET" && request.method !== "HEAD") return null;
348
+ const path = new URL(request.url).pathname;
349
+ const file = files.get(path);
350
+ if (file) return respond(file.body, file.contentType, request.method, false);
351
+ const markdown = negotiated.get(path);
352
+ if (markdown !== void 0 && prefersMarkdown(request.headers.get("accept"))) {
353
+ return respond(markdown, MARKDOWN, request.method, true);
354
+ }
355
+ return null;
356
+ },
357
+ finalize(request, response) {
358
+ return negotiated.has(new URL(request.url).pathname) ? withVaryAccept(response) : response;
359
+ }
360
+ };
361
+ }
362
+
363
+ export {
364
+ AGENT_MANIFEST_SCHEMA_VERSION,
365
+ TANGLE_PLATFORM_ORIGIN,
366
+ agentSignupScript,
367
+ renderAgentSetupSkill,
368
+ renderLlmsTxt,
369
+ renderHomeMarkdown,
370
+ renderAgentManifest,
371
+ agentSurfaceFiles,
372
+ prefersMarkdown,
373
+ withVaryAccept,
374
+ createAgentSurfaceHandler
375
+ };
376
+ //# sourceMappingURL=chunk-C5RHSYUA.js.map