@tangle-network/agent-app 0.60.6 → 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.
- package/dist/{DesignCanvas-OWE67ZX3.js → DesignCanvas-TW45DTK7.js} +3 -2
- package/dist/{DesignCanvasEditor-4FPLJ3YJ.js → DesignCanvasEditor-3DL3PF6P.js} +3 -2
- package/dist/agent-surfaces/cli.d.ts +2 -0
- package/dist/agent-surfaces/cli.js +49 -0
- package/dist/agent-surfaces/cli.js.map +1 -0
- package/dist/agent-surfaces/generate.d.ts +1 -0
- package/dist/agent-surfaces/index.d.ts +139 -0
- package/dist/agent-surfaces/index.js +27 -0
- package/dist/agent-surfaces/index.js.map +1 -0
- package/dist/app-auth/index.js +2 -1
- package/dist/app-auth/index.js.map +1 -1
- package/dist/assistant/index.js +4 -4
- package/dist/chat-routes/index.js +2 -1
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-DWUSVC3U.js → chunk-AKC5ZC4R.js} +3 -3
- package/dist/chunk-C5RHSYUA.js +376 -0
- package/dist/chunk-C5RHSYUA.js.map +1 -0
- package/dist/chunk-MLDKEEFQ.js +48 -0
- package/dist/chunk-MLDKEEFQ.js.map +1 -0
- package/dist/{chunk-GJRGCVDV.js → chunk-MUZQUS6X.js} +236 -187
- package/dist/chunk-MUZQUS6X.js.map +1 -0
- package/dist/chunk-RN4WPTBH.js +62 -0
- package/dist/chunk-RN4WPTBH.js.map +1 -0
- package/dist/{chunk-YNSPVKMS.js → chunk-UTAIRVOK.js} +1 -60
- package/dist/chunk-UTAIRVOK.js.map +1 -0
- package/dist/design-canvas/index.js +2 -1
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/engine.js +2 -1
- package/dist/design-canvas-react/index.js +6 -5
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/operator/client.d.ts +76 -0
- package/dist/operator/contract.d.ts +255 -0
- package/dist/operator/index.d.ts +8 -0
- package/dist/operator/index.js +533 -0
- package/dist/operator/index.js.map +1 -0
- package/dist/operator/server.d.ts +101 -0
- package/dist/platform/index.js +5 -45
- package/dist/platform/index.js.map +1 -1
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +2 -1
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/sequences/index.js +2 -1
- package/dist/sequences/index.js.map +1 -1
- package/dist/web/index.js +4 -2
- package/dist/web-react/agent-setup-block.d.ts +16 -0
- package/dist/web-react/index.d.ts +1 -0
- package/dist/web-react/index.js +12 -10
- package/package.json +12 -1
- package/dist/chunk-GJRGCVDV.js.map +0 -1
- package/dist/chunk-YNSPVKMS.js.map +0 -1
- /package/dist/{DesignCanvas-OWE67ZX3.js.map → DesignCanvas-TW45DTK7.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-4FPLJ3YJ.js.map → DesignCanvasEditor-3DL3PF6P.js.map} +0 -0
- /package/dist/{chunk-DWUSVC3U.js.map → chunk-AKC5ZC4R.js.map} +0 -0
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// src/design-canvas-react/lazy.tsx
|
|
2
2
|
import { lazy } from "react";
|
|
3
3
|
var DesignCanvasLazy = lazy(
|
|
4
|
-
() => import("./DesignCanvasEditor-
|
|
4
|
+
() => import("./DesignCanvasEditor-3DL3PF6P.js").then((m) => ({ default: m.DesignCanvasEditor }))
|
|
5
5
|
);
|
|
6
6
|
var DesignCanvasChromeLazy = lazy(
|
|
7
|
-
() => import("./DesignCanvas-
|
|
7
|
+
() => import("./DesignCanvas-TW45DTK7.js").then((m) => ({ default: m.DesignCanvas }))
|
|
8
8
|
);
|
|
9
9
|
|
|
10
10
|
export {
|
|
11
11
|
DesignCanvasLazy,
|
|
12
12
|
DesignCanvasChromeLazy
|
|
13
13
|
};
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent-surfaces/index.ts"],"sourcesContent":["/**\n * Machine-readable surfaces for a Tangle product, generated from one config.\n *\n * Every product publishes the same four things an AI agent needs to become a\n * customer without a human doing the setup:\n *\n * - `/agent-setup.md`: a SKILL.md (Claude Code and Codex skill format) that\n * doubles as a copy-paste prompt. It takes a fresh agent from nothing to a\n * verified first call: one owner approval, a scoped key, install, call.\n * - `/llms.txt`: the llms.txt index, pointing at the setup skill first.\n * - `/.well-known/tangle-agent.json`: the Tangle agent manifest.\n * - Markdown for `Accept: text/markdown` on the product's pages, with\n * `Vary: Accept` on both representations so caches keep them apart.\n *\n * The signup section is rendered here, not in product config, so every\n * product describes Platform's agent signup identically and cannot drift.\n *\n * Web-standard `Request`/`Response` only: safe in Workers, Node and browsers.\n */\n\n/** Manifest schema this module emits. Additive over the 2026-06-16 shape. */\nexport const AGENT_MANIFEST_SCHEMA_VERSION = '2026-10-09'\n\nexport const TANGLE_PLATFORM_ORIGIN = 'https://id.tangle.tools'\n\nexport interface AgentSurfaceStep {\n title: string\n /** Fence language for the code block. */\n language: 'bash' | 'js' | 'ts' | 'python' | 'json'\n code: string\n /** What a successful run prints or returns. */\n expect: string\n}\n\nexport interface AgentSurfaceError {\n symptom: string\n cause: string\n fix: string\n}\n\nexport interface AgentSurfaceLink {\n label: string\n url: string\n}\n\n/**\n * How an agent obtains a key. `device` uses Platform's agent signup: the owner\n * approves once and the agent receives its own capped, revocable key.\n */\nexport type AgentSignup =\n | {\n kind: 'device'\n /** Platform trusted-app id the key is minted for (`sandbox`, `router`). */\n app: string\n /** Default lifetime spend cap the skill asks for, in USD. */\n budgetUsd?: number\n }\n | {\n kind: 'manual'\n /** Numbered steps the owner performs; each one is a human input. */\n steps: string[]\n }\n\nexport interface AgentSurfaceConfig {\n /** Short id used in the skill name: `tangle-<id>-setup`. */\n id: string\n name: string\n /** Public HTTPS origin, no trailing slash. */\n origin: string\n /** What the product is for, in one to three plain sentences. */\n summary: string\n useWhen: string[]\n signup: AgentSignup\n /** Environment variable the key is exported as. */\n apiKeyEnv: string\n /** Runtime prerequisites a fresh machine needs, e.g. `Node.js 20 or newer`. */\n prerequisites: string[]\n install: AgentSurfaceStep[]\n firstCall: AgentSurfaceStep[]\n verify: AgentSurfaceStep[]\n errors: AgentSurfaceError[]\n pricing: {\n /** Plain statement of how usage is charged. */\n summary: string\n /** Public, credential-free price data an agent can quote from. */\n quoteUrl?: string\n url?: string\n }\n next: AgentSurfaceLink[]\n docs?: string\n openapi?: string\n mcp?: { url: string; auth: string }\n related?: Array<{ name: string; manifest?: string; url?: string }>\n /** Extra manifest fields a product already publishes (kept verbatim). */\n manifest?: Record<string, unknown>\n}\n\nexport interface AgentSurfaceFile {\n path: string\n contentType: string\n body: string\n}\n\nconst MARKDOWN = 'text/markdown; charset=utf-8'\n\nfunction trimOrigin(origin: string): string {\n return origin.replace(/\\/+$/, '')\n}\n\nfunction fence(step: Pick<AgentSurfaceStep, 'language' | 'code'>): string {\n return ['```' + step.language, step.code.trimEnd(), '```'].join('\\n')\n}\n\n/**\n * The signup script the skill tells an agent to save and run. Node 18+ only,\n * no dependencies. It never prints the key; it writes `.tangle/api-key` with\n * mode 0600 and reports whether the owner's account can pay yet.\n */\nexport function agentSignupScript(platformOrigin = TANGLE_PLATFORM_ORIGIN): string {\n // The specifier is interpolated so this module's own import scan (the\n // browser-safe subpath gate) does not read script text as an import.\n return `// Requests a scoped Tangle key for this agent. The owner approves once.\nimport { mkdirSync, writeFileSync } from ${JSON.stringify('node:fs')}\n\nconst flag = (name) => {\n const index = process.argv.indexOf(\\`--\\${name}\\`)\n return index > 0 ? process.argv[index + 1] : undefined\n}\nconst platform = '${trimOrigin(platformOrigin)}'\nconst app = flag('app')\nif (!app) throw new Error('Pass --app (for example --app sandbox)')\nconst request = { app, agent_name: flag('agent-name') ?? 'coding-agent' }\nif (flag('owner-email')) request.owner_email = flag('owner-email')\nif (flag('budget-usd')) request.budget_usd = Number(flag('budget-usd'))\n\nasync function post(path, body) {\n const response = await fetch(platform + path, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n return { status: response.status, body: await response.json().catch(() => ({})) }\n}\n\nconst started = await post('/cross-site/device/start', request)\nif (started.status !== 200) {\n console.error(\\`Signup refused (HTTP \\${started.status}): \\${JSON.stringify(started.body)}\\`)\n process.exit(1)\n}\nconst grant = started.body.data\nconsole.log(grant.agent?.owner_notified\n ? \\`Approval email sent to \\${request.owner_email}.\\`\n : 'Send your owner this approval link.')\nconsole.log(\\`Approval link: \\${grant.verification_uri_complete}\\`)\nconsole.log(\\`Confirmation code: \\${grant.user_code} (expires in \\${Math.round(grant.expires_in / 60)} minutes)\\`)\nconsole.log('Waiting for approval...')\n\nconst deadline = Date.now() + grant.expires_in * 1000\nwhile (Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, grant.interval * 1000))\n const polled = await post('/cross-site/device/poll', { app, device_code: grant.device_code })\n if (polled.status === 428) continue\n if (polled.status !== 200) {\n console.error(\\`Approval failed (HTTP \\${polled.status}): \\${JSON.stringify(polled.body)}\\`)\n process.exit(1)\n }\n const { api_key: apiKey, key, account } = polled.body.data\n mkdirSync('.tangle', { recursive: true, mode: 0o700 })\n writeFileSync('.tangle/api-key', \\`\\${apiKey}\\\\n\\`, { mode: 0o600 })\n console.log(\\`Approved. Key \"\\${key?.name ?? app}\" saved to .tangle/api-key (spend cap $\\${key?.budget_usd ?? 'none'}).\\`)\n if (account && !account.funded) {\n console.log(\\`The owner's account has no credit yet. Ask the owner to add credits: \\${account.add_credits_url}\\`)\n }\n process.exit(0)\n}\nconsole.error('The approval link expired. Run this script again.')\nprocess.exit(1)\n`\n}\n\nfunction signupSection(config: AgentSurfaceConfig): string[] {\n const env = config.apiKeyEnv\n if (config.signup.kind === 'manual') {\n return [\n '## 1. Get a key',\n '',\n 'This product does not yet support agent signup. Ask your owner to do the following, then continue:',\n '',\n ...config.signup.steps.map((step, index) => `${index + 1}. ${step}`),\n '',\n `Store the key outside version control and export it as \\`${env}\\`. Never print, log, or commit it.`,\n ]\n }\n const budget = config.signup.budgetUsd ?? 25\n return [\n '## 1. Get a scoped key (one owner approval)',\n '',\n 'Tangle issues each agent its own key, owned by a person who approves it once.',\n `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.`,\n '',\n 'Save this script as `tangle-signup.mjs` (Node.js 18 or newer, no dependencies):',\n '',\n fence({ language: 'js', code: agentSignupScript() }),\n '',\n 'Run it with your own name and the owner\\'s email:',\n '',\n fence({\n language: 'bash',\n code: `node tangle-signup.mjs --app ${config.signup.app} --agent-name \"<your agent name>\" --owner-email \"<owner email>\" --budget-usd ${budget}`,\n }),\n '',\n 'What happens:',\n '',\n `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.`,\n '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.',\n `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.`,\n '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.',\n '',\n 'Then load the key without printing it, and keep it out of version control:',\n '',\n fence({\n language: 'bash',\n code: `export ${env}=\"$(cat .tangle/api-key)\"\\ngrep -qxF '.tangle/' .gitignore 2>/dev/null || echo '.tangle/' >> .gitignore`,\n }),\n '',\n 'Never print, log, paste, or commit the key.',\n ]\n}\n\nfunction stepsSection(heading: string, steps: AgentSurfaceStep[]): string[] {\n if (steps.length === 0) return []\n const lines = [heading, '']\n for (const step of steps) {\n lines.push(`${step.title}:`, '', fence(step), '', `Expected: ${step.expect}`, '')\n }\n return lines\n}\n\n/** The agent setup skill: valid SKILL.md and a plain copy-paste prompt. */\nexport function renderAgentSetupSkill(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n 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.`\n const lines: string[] = [\n '---',\n `name: tangle-${config.id}-setup`,\n `description: ${description}`,\n '---',\n '',\n `# Set up ${config.name}`,\n '',\n config.summary,\n '',\n 'Use it when:',\n '',\n ...config.useWhen.map((item) => `- ${item}`),\n '',\n 'Complete every step below in order and stop at the first failure; the error table at the end names the fix.',\n 'Prerequisites: ' + config.prerequisites.join('; ') + '.',\n '',\n ...signupSection(config),\n '',\n ...stepsSection('## 2. Install', config.install),\n ...stepsSection('## 3. Make the first call', config.firstCall),\n ...stepsSection('## 4. Verify it worked', config.verify),\n '## Common errors',\n '',\n '| Symptom | Cause | Fix |',\n '| --- | --- | --- |',\n ...config.errors.map(\n (error) => `| ${error.symptom.replace(/\\|/g, '\\\\|')} | ${error.cause.replace(/\\|/g, '\\\\|')} | ${error.fix.replace(/\\|/g, '\\\\|')} |`,\n ),\n '',\n '## Pricing',\n '',\n config.pricing.summary,\n ...(config.pricing.quoteUrl ? ['', `Current prices, no key needed: ${config.pricing.quoteUrl}`] : []),\n ...(config.pricing.url ? [`Pricing page: ${config.pricing.url}`] : []),\n '',\n '## Next',\n '',\n ...config.next.map((link) => `- [${link.label}](${link.url})`),\n '',\n '## Machine-readable surfaces',\n '',\n `- Agent manifest: ${origin}/.well-known/tangle-agent.json`,\n `- llms.txt: ${origin}/llms.txt`,\n `- This setup skill: ${origin}/agent-setup.md`,\n ...(config.openapi ? [`- OpenAPI: ${config.openapi}`] : []),\n ...(config.mcp ? [`- MCP server: ${config.mcp.url} (${config.mcp.auth})`] : []),\n '',\n ]\n return lines.join('\\n')\n}\n\n/** llms.txt index for the product. The setup skill is the first link. */\nexport function renderLlmsTxt(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n return [\n `# ${config.name}`,\n '',\n `> ${config.summary}`,\n '',\n `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.`,\n '',\n '## Start here',\n '',\n `- [Agent setup skill](${origin}/agent-setup.md): from nothing to a verified first call`,\n `- [Agent manifest](${origin}/.well-known/tangle-agent.json): machine-readable contract`,\n ...(config.openapi ? [`- [OpenAPI](${config.openapi}): HTTP API schema`] : []),\n ...(config.mcp ? [`- [MCP server](${config.mcp.url}): ${config.mcp.auth}`] : []),\n ...(config.docs ? [`- [Documentation](${config.docs})`] : []),\n '',\n '## Pricing',\n '',\n `- ${config.pricing.summary}`,\n ...(config.pricing.quoteUrl ? [`- [Machine-readable prices](${config.pricing.quoteUrl}): no key needed`] : []),\n '',\n '## Optional',\n '',\n ...config.next.map((link) => `- [${link.label}](${link.url})`),\n ...(config.related ?? []).map(\n (surface) => `- [${surface.name}](${surface.manifest ?? surface.url ?? ''})`,\n ),\n '',\n ].join('\\n')\n}\n\n/** Markdown for the product's home page, served for `Accept: text/markdown`. */\nexport function renderHomeMarkdown(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n return [\n `# ${config.name}`,\n '',\n config.summary,\n '',\n '## Use it when',\n '',\n ...config.useWhen.map((item) => `- ${item}`),\n '',\n '## Hand this to your agent',\n '',\n `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.`,\n '',\n '## Pricing',\n '',\n config.pricing.summary,\n ...(config.pricing.quoteUrl ? ['', `Machine-readable prices: ${config.pricing.quoteUrl}`] : []),\n '',\n '## Machine-readable surfaces',\n '',\n `- ${origin}/llms.txt`,\n `- ${origin}/.well-known/tangle-agent.json`,\n `- ${origin}/agent-setup.md`,\n ...(config.openapi ? [`- ${config.openapi}`] : []),\n ...(config.mcp ? [`- ${config.mcp.url}`] : []),\n '',\n ].join('\\n')\n}\n\n/** The `/.well-known/tangle-agent.json` document. */\nexport function renderAgentManifest(config: AgentSurfaceConfig): Record<string, unknown> {\n const origin = trimOrigin(config.origin)\n const signup =\n config.signup.kind === 'device'\n ? {\n kind: 'device_authorization',\n app: config.signup.app,\n start: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/start`,\n poll: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/poll`,\n request: {\n app: config.signup.app,\n agent_name: 'string, 1-64 characters',\n owner_email: 'optional; Tangle emails this owner the approval link',\n budget_usd: `optional lifetime spend cap, 1-1000, default ${config.signup.budgetUsd ?? 25}`,\n },\n human_inputs: ['The owner approves the request once.'],\n key: {\n scope: `${config.signup.app} only`,\n revocable_at: `${TANGLE_PLATFORM_ORIGIN}/app/keys`,\n },\n payment: 'Prepaid credit on the owner account. No free credit; paid calls are refused until the owner adds credits.',\n add_credits: `${TANGLE_PLATFORM_ORIGIN}/app/billing`,\n }\n : { kind: 'manual', steps: config.signup.steps }\n return {\n ...config.manifest,\n schema_version: AGENT_MANIFEST_SCHEMA_VERSION,\n name: config.name,\n description: config.summary,\n homepage: `${origin}/`,\n llms: `${origin}/llms.txt`,\n agent_setup: `${origin}/agent-setup.md`,\n ...(config.docs ? { docs: config.docs } : {}),\n ...(config.openapi ? { openapi: config.openapi } : {}),\n ...(config.mcp ? { mcp: config.mcp } : {}),\n environment: { api_key: config.apiKeyEnv },\n signup,\n pricing: {\n summary: config.pricing.summary,\n ...(config.pricing.quoteUrl ? { quote: config.pricing.quoteUrl } : {}),\n ...(config.pricing.url ? { page: config.pricing.url } : {}),\n },\n ...(config.related?.length ? { related_surfaces: config.related } : {}),\n }\n}\n\n/** Every static surface as files, for products that ship them as assets. */\nexport function agentSurfaceFiles(config: AgentSurfaceConfig): AgentSurfaceFile[] {\n return [\n { path: 'agent-setup.md', contentType: MARKDOWN, body: renderAgentSetupSkill(config) },\n { path: 'llms.txt', contentType: 'text/plain; charset=utf-8', body: renderLlmsTxt(config) },\n { path: 'index.md', contentType: MARKDOWN, body: renderHomeMarkdown(config) },\n {\n path: '.well-known/tangle-agent.json',\n contentType: 'application/json; charset=utf-8',\n body: `${JSON.stringify(renderAgentManifest(config), null, 2)}\\n`,\n },\n ]\n}\n\n/**\n * True when `Accept` ranks `text/markdown` strictly above `text/html` and\n * gives it a nonzero weight. A browser's default header never does.\n */\nexport function prefersMarkdown(accept: string | null | undefined): boolean {\n if (!accept) return false\n let markdown = -1\n let html = -1\n for (const part of accept.split(',')) {\n const [rawType, ...params] = part.trim().split(';')\n const type = rawType?.trim().toLowerCase()\n let quality = 1\n for (const param of params) {\n const [key, value] = param.trim().split('=')\n if (key?.trim().toLowerCase() === 'q') {\n const parsed = Number(value)\n quality = Number.isFinite(parsed) ? parsed : 0\n }\n }\n if (type === 'text/markdown') markdown = Math.max(markdown, quality)\n if (type === 'text/html') html = Math.max(html, quality)\n }\n return markdown > 0 && markdown > html\n}\n\n/** A copy of `response` whose `Vary` includes `Accept`. */\nexport function withVaryAccept(response: Response): Response {\n const vary = response.headers.get('vary')\n if (vary && vary.split(',').some((value) => value.trim().toLowerCase() === 'accept')) {\n return response\n }\n const headers = new Headers(response.headers)\n headers.set('vary', vary ? `${vary}, Accept` : 'Accept')\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n}\n\nexport interface AgentSurfaceHandler {\n /**\n * Answers a surface request (`/agent-setup.md`, `/llms.txt`, the manifest,\n * or a negotiated markdown page), or `null` to let the app answer it.\n */\n handle(request: Request): Response | null\n /** Adds `Vary: Accept` when the path has a markdown representation. */\n finalize(request: Request, response: Response): Response\n}\n\n/**\n * Request handler over {@link agentSurfaceFiles}. `markdownPages` maps extra\n * HTML paths to markdown served on negotiation; `/` always maps to the home\n * markdown.\n */\nexport function createAgentSurfaceHandler(\n config: AgentSurfaceConfig,\n options: { markdownPages?: Record<string, string> } = {},\n): AgentSurfaceHandler {\n const files = new Map(agentSurfaceFiles(config).map((file) => [`/${file.path}`, file]))\n const negotiated = new Map<string, string>([\n ['/', renderHomeMarkdown(config)],\n ...Object.entries(options.markdownPages ?? {}),\n ])\n\n function respond(body: string, contentType: string, method: string, vary: boolean): Response {\n const headers = new Headers({\n 'content-type': contentType,\n 'cache-control': 'public, max-age=300',\n 'x-content-type-options': 'nosniff',\n })\n if (vary) headers.set('vary', 'Accept')\n return new Response(method === 'HEAD' ? null : body, { status: 200, headers })\n }\n\n return {\n handle(request) {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n const path = new URL(request.url).pathname\n const file = files.get(path)\n if (file) return respond(file.body, file.contentType, request.method, false)\n const markdown = negotiated.get(path)\n if (markdown !== undefined && prefersMarkdown(request.headers.get('accept'))) {\n return respond(markdown, MARKDOWN, request.method, true)\n }\n return null\n },\n finalize(request, response) {\n return negotiated.has(new URL(request.url).pathname) ? withVaryAccept(response) : response\n },\n }\n}\n"],"mappings":";AAqBO,IAAM,gCAAgC;AAEtC,IAAM,yBAAyB;AAgFtC,IAAM,WAAW;AAEjB,SAAS,WAAW,QAAwB;AAC1C,SAAO,OAAO,QAAQ,QAAQ,EAAE;AAClC;AAEA,SAAS,MAAM,MAA2D;AACxE,SAAO,CAAC,QAAQ,KAAK,UAAU,KAAK,KAAK,QAAQ,GAAG,KAAK,EAAE,KAAK,IAAI;AACtE;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UAAI,KAAM,QAAO,QAAQ,KAAK,MAAM,KAAK,aAAa,QAAQ,QAAQ,KAAK;AAC3E,YAAM,WAAW,WAAW,IAAI,IAAI;AACpC,UAAI,aAAa,UAAa,gBAAgB,QAAQ,QAAQ,IAAI,QAAQ,CAAC,GAAG;AAC5E,eAAO,QAAQ,UAAU,UAAU,QAAQ,QAAQ,IAAI;AAAA,MACzD;AACA,aAAO;AAAA,IACT;AAAA,IACA,SAAS,SAAS,UAAU;AAC1B,aAAO,WAAW,IAAI,IAAI,IAAI,QAAQ,GAAG,EAAE,QAAQ,IAAI,eAAe,QAAQ,IAAI;AAAA,IACpF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// src/platform/api-key-auth.ts
|
|
2
|
+
function createApiKeyRequestAuth(options) {
|
|
3
|
+
return async (request) => {
|
|
4
|
+
const authorization = request.headers.get("Authorization");
|
|
5
|
+
if (authorization === null) return null;
|
|
6
|
+
const bearer = /^Bearer +(\S+)$/i.exec(authorization);
|
|
7
|
+
if (!bearer) {
|
|
8
|
+
throw denied(401, "api_key.invalid", "Invalid API key");
|
|
9
|
+
}
|
|
10
|
+
const requiredScope = options.requiredScope(request);
|
|
11
|
+
const requiredScopes = typeof requiredScope === "string" ? [requiredScope] : Array.from(requiredScope ?? []);
|
|
12
|
+
if (!requiredScopes?.length || !requiredScopes.every((scope) => typeof scope === "string" && scope.trim())) {
|
|
13
|
+
throw denied(403, "api_key.route_denied", "API key access is not enabled for this route");
|
|
14
|
+
}
|
|
15
|
+
const key = await options.verify(`Bearer ${bearer[1]}`);
|
|
16
|
+
if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {
|
|
17
|
+
throw denied(401, "api_key.invalid", "Invalid API key");
|
|
18
|
+
}
|
|
19
|
+
if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {
|
|
20
|
+
throw denied(401, "api_key.expired", "An unexpired API key with a finite expiry is required");
|
|
21
|
+
}
|
|
22
|
+
if (!Array.isArray(key.scopes) || !requiredScopes.every((scope) => key.scopes.includes(scope))) {
|
|
23
|
+
throw denied(403, "api_key.insufficient_scope", `API key requires scopes: ${requiredScopes.join(", ")}`);
|
|
24
|
+
}
|
|
25
|
+
const identity = await options.resolveIdentity(key);
|
|
26
|
+
if (!identity) throw denied(401, "api_key.invalid_owner", "API key owner is unavailable");
|
|
27
|
+
const claim = await options.claimRequest(key, crypto.randomUUID());
|
|
28
|
+
if (claim.allowed !== true) {
|
|
29
|
+
const headers = new Headers();
|
|
30
|
+
if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds > 0) {
|
|
31
|
+
headers.set("Retry-After", String(Math.ceil(claim.retryAfterSeconds)));
|
|
32
|
+
}
|
|
33
|
+
throw denied(429, "api_key.request_limit_exceeded", "API key request limit exceeded", headers);
|
|
34
|
+
}
|
|
35
|
+
if (key.expiresAt <= Date.now()) {
|
|
36
|
+
throw denied(401, "api_key.expired", "API key expired during authorization");
|
|
37
|
+
}
|
|
38
|
+
return identity;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function denied(status, code, error, headers) {
|
|
42
|
+
return Response.json({ error, code }, { status, headers });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export {
|
|
46
|
+
createApiKeyRequestAuth
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=chunk-MLDKEEFQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platform/api-key-auth.ts"],"sourcesContent":["/** Verified key fields required to enter a product's private API routes. */\nexport interface RequestApiKey {\n keyId: string\n ownerId: string\n scopes: readonly string[]\n /** Unix epoch milliseconds. Private API credentials must expire. */\n expiresAt: number\n}\n\nexport interface ApiKeyRequestAuthOptions<Key extends RequestApiKey, Identity> {\n /** Verify against the existing key store, including revocation and spending limits. */\n verify(authorization: string): Promise<Key | null>\n /** Return one scope or all required scopes; null or an empty list denies the route. */\n requiredScope(request: Request): string | readonly string[] | null\n /** Load the owner from product storage; retain normal workspace and tenant authorization. */\n resolveIdentity(key: Key): Promise<Identity | null>\n /** Atomically enforce the existing key's request quotas before admitting the request. */\n claimRequest(key: Key, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\n/**\n * Adapt existing Bearer keys to private product routes without issuing sessions.\n * Only absent authorization returns null; supplied invalid credentials never\n * fall through to cookie authentication. Callers retain their ordinary RBAC.\n */\nexport function createApiKeyRequestAuth<Key extends RequestApiKey, Identity>(\n options: ApiKeyRequestAuthOptions<Key, Identity>,\n): (request: Request) => Promise<Identity | null> {\n return async (request) => {\n const authorization = request.headers.get('Authorization')\n if (authorization === null) return null\n const bearer = /^Bearer +(\\S+)$/i.exec(authorization)\n if (!bearer) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n const requiredScope = options.requiredScope(request)\n const requiredScopes = typeof requiredScope === 'string' ? [requiredScope] : Array.from(requiredScope ?? [])\n if (!requiredScopes?.length || !requiredScopes.every(scope => typeof scope === 'string' && scope.trim())) {\n throw denied(403, 'api_key.route_denied', 'API key access is not enabled for this route')\n }\n const key = await options.verify(`Bearer ${bearer[1]}`)\n if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'An unexpired API key with a finite expiry is required')\n }\n if (!Array.isArray(key.scopes) || !requiredScopes.every(scope => key.scopes.includes(scope))) {\n throw denied(403, 'api_key.insufficient_scope', `API key requires scopes: ${requiredScopes.join(', ')}`)\n }\n const identity = await options.resolveIdentity(key)\n if (!identity) throw denied(401, 'api_key.invalid_owner', 'API key owner is unavailable')\n const claim = await options.claimRequest(key, crypto.randomUUID())\n if (claim.allowed !== true) {\n const headers = new Headers()\n if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds! > 0) {\n headers.set('Retry-After', String(Math.ceil(claim.retryAfterSeconds!)))\n }\n throw denied(429, 'api_key.request_limit_exceeded', 'API key request limit exceeded', headers)\n }\n if (key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'API key expired during authorization')\n }\n return identity\n }\n}\n\nfunction denied(status: number, code: string, error: string, headers?: Headers): Response {\n return Response.json({ error, code }, { status, headers })\n}\n"],"mappings":";AAyBO,SAAS,wBACd,SACgD;AAChD,SAAO,OAAO,YAAY;AACxB,UAAM,gBAAgB,QAAQ,QAAQ,IAAI,eAAe;AACzD,QAAI,kBAAkB,KAAM,QAAO;AACnC,UAAM,SAAS,mBAAmB,KAAK,aAAa;AACpD,QAAI,CAAC,QAAQ;AACX,YAAM,OAAO,KAAK,mBAAmB,iBAAiB;AAAA,IACxD;AACA,UAAM,gBAAgB,QAAQ,cAAc,OAAO;AACnD,UAAM,iBAAiB,OAAO,kBAAkB,WAAW,CAAC,aAAa,IAAI,MAAM,KAAK,iBAAiB,CAAC,CAAC;AAC3G,QAAI,CAAC,gBAAgB,UAAU,CAAC,eAAe,MAAM,WAAS,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,GAAG;AACxG,YAAM,OAAO,KAAK,wBAAwB,8CAA8C;AAAA,IAC1F;AACA,UAAM,MAAM,MAAM,QAAQ,OAAO,UAAU,OAAO,CAAC,CAAC,EAAE;AACtD,QAAI,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,KAAK,CAAC,IAAI,SAAS,KAAK,GAAG;AACtD,YAAM,OAAO,KAAK,mBAAmB,iBAAiB;AAAA,IACxD;AACA,QAAI,CAAC,OAAO,cAAc,IAAI,SAAS,KAAK,IAAI,aAAa,KAAK,IAAI,GAAG;AACvE,YAAM,OAAO,KAAK,mBAAmB,uDAAuD;AAAA,IAC9F;AACA,QAAI,CAAC,MAAM,QAAQ,IAAI,MAAM,KAAK,CAAC,eAAe,MAAM,WAAS,IAAI,OAAO,SAAS,KAAK,CAAC,GAAG;AAC5F,YAAM,OAAO,KAAK,8BAA8B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