@lupinum/ginko-server 0.0.0-stage → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/convex/_generated/api.d.ts +185 -0
- package/convex/_generated/api.js +23 -0
- package/convex/_generated/dataModel.d.ts +60 -0
- package/convex/_generated/server.d.ts +162 -0
- package/convex/_generated/server.js +101 -0
- package/convex/account.ts +110 -0
- package/convex/agent.ts +814 -0
- package/convex/auth.config.ts +4 -0
- package/convex/auth.ts +62 -0
- package/convex/backup.ts +94 -0
- package/convex/betterAuth/_generated/api.ts +56 -0
- package/convex/betterAuth/_generated/component.ts +431 -0
- package/convex/betterAuth/_generated/dataModel.ts +60 -0
- package/convex/betterAuth/_generated/server.ts +169 -0
- package/convex/betterAuth/adapter.ts +7 -0
- package/convex/betterAuth/convex.config.ts +3 -0
- package/convex/betterAuth/schema.ts +102 -0
- package/convex/betterAuth/schemaMetadata.ts +697 -0
- package/convex/betterAuth/schemaOptions.ts +13 -0
- package/convex/betterAuth/schemaPlugins.ts +13 -0
- package/convex/bundle.ts +183 -0
- package/convex/changes.ts +136 -0
- package/convex/cleanup.ts +44 -0
- package/convex/connect.ts +143 -0
- package/convex/convex.config.ts +7 -0
- package/convex/crons.ts +14 -0
- package/convex/demo.ts +72 -0
- package/convex/entries.ts +1770 -0
- package/convex/facts.ts +129 -0
- package/convex/files.ts +631 -0
- package/convex/http.ts +21 -0
- package/convex/image.ts +45 -0
- package/convex/images.ts +54 -0
- package/convex/invites.ts +227 -0
- package/convex/lib/access.ts +180 -0
- package/convex/lib/agentTools.ts +331 -0
- package/convex/lib/content.ts +317 -0
- package/convex/lib/corpus.ts +83 -0
- package/convex/lib/diff.ts +50 -0
- package/convex/lib/fail.ts +27 -0
- package/convex/lib/files.ts +70 -0
- package/convex/lib/history.ts +103 -0
- package/convex/lib/i18n.ts +52 -0
- package/convex/lib/input.ts +57 -0
- package/convex/lib/library.ts +28 -0
- package/convex/lib/lifecycle.ts +100 -0
- package/convex/lib/list.ts +112 -0
- package/convex/lib/migrations.ts +126 -0
- package/convex/lib/names.ts +56 -0
- package/convex/lib/pending.ts +84 -0
- package/convex/lib/policy.ts +155 -0
- package/convex/lib/publicness.ts +87 -0
- package/convex/lib/reminders.ts +27 -0
- package/convex/lib/search.ts +132 -0
- package/convex/lib/siteUrl.ts +95 -0
- package/convex/lib/status.ts +109 -0
- package/convex/lib/translation.ts +56 -0
- package/convex/lib/trees.ts +43 -0
- package/convex/lib/write.ts +296 -0
- package/convex/mail.ts +136 -0
- package/convex/members.ts +129 -0
- package/convex/migrations.ts +105 -0
- package/convex/navigation.ts +276 -0
- package/convex/ops.ts +50 -0
- package/convex/proposals.ts +753 -0
- package/convex/refresh.ts +163 -0
- package/convex/release.ts +435 -0
- package/convex/reminders.ts +116 -0
- package/convex/retention.ts +121 -0
- package/convex/routes/bundle.ts +62 -0
- package/convex/routes/connect.ts +80 -0
- package/convex/routes/export.ts +23 -0
- package/convex/routes/file.ts +34 -0
- package/convex/routes/key.ts +53 -0
- package/convex/routes/mcp.ts +300 -0
- package/convex/routes/release.ts +66 -0
- package/convex/routes/upload.ts +94 -0
- package/convex/schema.ts +443 -0
- package/convex/search.ts +58 -0
- package/convex/seed.ts +624 -0
- package/convex/siteDeletion.ts +78 -0
- package/convex/sites.ts +393 -0
- package/convex/tasks.ts +51 -0
- package/convex/tsconfig.json +27 -0
- package/convex/uploads.ts +429 -0
- package/convex/uploadsNode.ts +86 -0
- package/convex/views.ts +111 -0
- package/i18n/de.json +364 -0
- package/i18n/en.json +364 -0
- package/i18n/es.json +364 -0
- package/i18n/fr.json +364 -0
- package/package.json +45 -3
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// POST /mcp: the agent door (SPEC 16) as MCP Streamable HTTP, stateless: one JSON-RPC request in, one
|
|
2
|
+
// JSON answer out, no SSE, no session. Order: key and rate limit, then the method. Tool failures are
|
|
3
|
+
// tool results with `isError` and the English message, so the assistant can tell the person.
|
|
4
|
+
import type { Json } from '@lupinum/ginko'
|
|
5
|
+
import { coreMessage, sha256, SITE_BUDGET } from '@lupinum/ginko/internal'
|
|
6
|
+
import type { HttpRouter } from 'convex/server'
|
|
7
|
+
import { internal } from '../_generated/api'
|
|
8
|
+
import type { Id } from '../_generated/dataModel'
|
|
9
|
+
import { httpAction, type ActionCtx } from '../_generated/server'
|
|
10
|
+
import { DRY_RUN, READ_TOOLS } from '../lib/agentTools'
|
|
11
|
+
import { badKey } from '../lib/input'
|
|
12
|
+
import { t, type MessageKey } from '../lib/i18n'
|
|
13
|
+
import { isFetchableSiteUrl } from '../lib/siteUrl'
|
|
14
|
+
import { kindOf, TOO_LARGE, WRONG_TYPE } from '../lib/files'
|
|
15
|
+
import { storeFile } from './upload'
|
|
16
|
+
|
|
17
|
+
const PROTOCOL = '2025-06-18'
|
|
18
|
+
/** An answer holds at least one whole entry the Studio can save (SITE_BUDGET.entryBytes) plus room for its wrapping. */
|
|
19
|
+
const ANSWER_MAX = SITE_BUDGET.entryBytes + 64 * 1024
|
|
20
|
+
const BODY_MAX = 512 * 1024
|
|
21
|
+
const KEY = /^ginko_agent_[a-z0-9]{32}$/
|
|
22
|
+
|
|
23
|
+
// Written for the model, in English whatever the language of the site: the model answers the person in theirs.
|
|
24
|
+
const INSTRUCTIONS = 'Ginko maintains the content of one website for one person. Call ginko_overview first. Every task is a tool. '
|
|
25
|
+
+ 'Changes are live in about a minute and can be taken back with ginko_undo. Ask the person before removing anything. '
|
|
26
|
+
+ 'When you retry a change, send the same request_id, so it runs only once. '
|
|
27
|
+
+ 'Texts that belong to the website stay in the language of the website; answer the person in their own language. '
|
|
28
|
+
+ 'Owners and admins also build and fill the site: ginko_schema shows every field, ginko_write, ginko_create and ginko_import write them (ginko_import with dry_run first), ginko_upload adds files. '
|
|
29
|
+
+ 'Values the site keeps in one place (a price, opening days, the phone number) are listed as facts in ginko_overview: in a Markdown text, write the fact\'s quote (:fact{name="practice.price"}) instead of the value, so the text stays right when the value changes; change the value in its own field.'
|
|
30
|
+
|
|
31
|
+
type Rpc = { jsonrpc: '2.0'; id?: string | number | null; method: string; params?: Record<string, Json> }
|
|
32
|
+
|
|
33
|
+
function reply(status: number, body?: unknown, extra: Record<string, string> = {}): Response {
|
|
34
|
+
return new Response(body === undefined ? null : JSON.stringify(body), {
|
|
35
|
+
status, headers: { ...(body === undefined ? {} : { 'content-type': 'application/json' }), 'cache-control': 'no-store', ...extra },
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
const result = (id: Rpc['id'], value: unknown) => reply(200, { jsonrpc: '2.0', id, result: value })
|
|
39
|
+
const rpcError = (id: Rpc['id'], code: number, message: string, status = 200) => reply(status, { jsonrpc: '2.0', id: id ?? null, error: { code, message } })
|
|
40
|
+
|
|
41
|
+
function isRpc(body: unknown): body is Rpc {
|
|
42
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) return false
|
|
43
|
+
const b = body as Record<string, unknown>
|
|
44
|
+
const idOk = b.id === undefined || b.id === null || typeof b.id === 'string' || typeof b.id === 'number'
|
|
45
|
+
const paramsOk = b.params === undefined || (typeof b.params === 'object' && b.params !== null && !Array.isArray(b.params))
|
|
46
|
+
return b.jsonrpc === '2.0' && typeof b.method === 'string' && idOk && paramsOk
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A tool answer: the sentence for the person first, the data as JSON after it. */
|
|
50
|
+
function toolText(text: string, data?: unknown, isError = false) {
|
|
51
|
+
const content = [{ type: 'text', text }]
|
|
52
|
+
if (data !== undefined) content.push({ type: 'text', text: JSON.stringify(data) })
|
|
53
|
+
return { content, isError }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The English message of a thrown `fail(...)` (its catalog key, else the stored German text); anything else is a generic failure. */
|
|
57
|
+
function messageOf(error: unknown): string {
|
|
58
|
+
const data = (error as { data?: unknown }).data
|
|
59
|
+
if (data && typeof data === 'object' && 'message' in data) {
|
|
60
|
+
const { message, key, params, details, at } = data as { message: string; key?: string; params?: Record<string, string | number>; at?: string; details?: { errors?: { message: string; key?: string; params?: Record<string, string | number>; path?: string }[] } }
|
|
61
|
+
const head = key ? t('en', key as MessageKey, params) : message
|
|
62
|
+
// A field error names its path ("price: …"), so the assistant knows which value to fix.
|
|
63
|
+
const issues = details?.errors?.map((e) => `${e.path ? `${e.path}: ` : ''}${e.key ? coreMessage('en', e.key, e.params) : e.message}`) ?? []
|
|
64
|
+
const text = issues.length ? `${head} ${issues.join(' ')}` : head
|
|
65
|
+
// An import names the item that failed; nothing of the import is saved.
|
|
66
|
+
return at ? `${at}: ${text} Nothing of this import was saved.` : text
|
|
67
|
+
}
|
|
68
|
+
return 'That did not work. Try again later.'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function callTool(ctx: ActionCtx, key: Id<'agentKeys'>, name: string, args: Record<string, Json>) {
|
|
72
|
+
// Convex refuses such a key with an uncoded error before agent.call runs; the assistant needs the name to fix the call.
|
|
73
|
+
const bad = badKey(args)
|
|
74
|
+
if (bad) return toolText(t('en', 'errors.nameNotAllowed', { name: bad }), undefined, true)
|
|
75
|
+
try {
|
|
76
|
+
if (name === 'ginko_overview') return toolText('Overview of the website.', await ctx.runQuery(internal.agent.overview, { key }))
|
|
77
|
+
if (name === 'ginko_history') {
|
|
78
|
+
const limit = typeof args.limit === 'number' ? args.limit : undefined
|
|
79
|
+
return toolText('The latest changes, newest first.', await ctx.runQuery(internal.agent.history, { key, limit }))
|
|
80
|
+
}
|
|
81
|
+
if (name === 'ginko_read') {
|
|
82
|
+
// Any member may read the whole site (SPEC 2.7); the content is the public bundle, so drafts are not in it.
|
|
83
|
+
const { site } = await ctx.runQuery(internal.agent.overview, { key })
|
|
84
|
+
const bundle = await ctx.runQuery(internal.bundle.build, { slug: site, locale: typeof args.locale === 'string' ? args.locale : '' })
|
|
85
|
+
if (typeof bundle === 'string') return toolText('The website cannot be read right now.', undefined, true)
|
|
86
|
+
const brick = typeof args.brick === 'string' && Object.hasOwn(bundle.bricks, args.brick) ? bundle.bricks[args.brick] : undefined
|
|
87
|
+
if (!brick) return toolText(`There is no brick “${String(args.brick)}”. The brick keys are in ginko_overview.`, undefined, true)
|
|
88
|
+
// In another language, `fallback` names the missing translations and `stale` the outdated ones, which the website still shows.
|
|
89
|
+
if (bundle.locale !== bundle.mainLocale) {
|
|
90
|
+
const stale = await ctx.runQuery(internal.agent.stale, { key, brick: String(args.brick), locale: bundle.locale })
|
|
91
|
+
if (Object.keys(stale).length) return toolText(`Content of “${String(args.brick)}” (${bundle.locale}).`, { ...brick, stale })
|
|
92
|
+
}
|
|
93
|
+
return toolText(`Content of “${String(args.brick)}” (${bundle.locale}).`, brick)
|
|
94
|
+
}
|
|
95
|
+
if (name === 'ginko_upload') return await uploadThroughDoor(ctx, key, args)
|
|
96
|
+
if (READ_TOOLS.has(name)) {
|
|
97
|
+
const done = await ctx.runQuery(internal.agent.lookup, { key, name, args })
|
|
98
|
+
return toolText(done.text, done.result)
|
|
99
|
+
}
|
|
100
|
+
const done = await ctx.runMutation(internal.agent.call, { key, name, args })
|
|
101
|
+
return toolText(done.text, done.result)
|
|
102
|
+
} catch (error) {
|
|
103
|
+
// A dry run of ginko_import ends with a throw, so nothing it wrote is kept.
|
|
104
|
+
const data = (error as { data?: { code?: string; results?: unknown[]; note?: string } }).data
|
|
105
|
+
if (data?.code === DRY_RUN) return toolText([dryRunText((data.results ?? []) as { proposed?: boolean }[]), data.note].filter(Boolean).join(' '), data.results)
|
|
106
|
+
return toolText(messageOf(error), undefined, true)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** What a dry run of ginko_import says: each item passed the real save; with review on, some would be proposals. */
|
|
111
|
+
export function dryRunText(results: readonly { proposed?: boolean }[]): string {
|
|
112
|
+
const proposed = results.filter((r) => r.proposed).length
|
|
113
|
+
const would = proposed === results.length ? 'would become proposals that wait for approval' : proposed ? `would be saved (${proposed} of them as proposals that wait for approval)` : 'would be saved'
|
|
114
|
+
return `Dry run: all ${results.length} items ${would}. Nothing was saved.`
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const TYPES: Record<string, string> = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', pdf: 'application/pdf' }
|
|
118
|
+
/** The Content-Type for a file name's extension, if it is one the library takes. */
|
|
119
|
+
const typeOfName = (name: string): string | undefined => TYPES[name.split('.').pop()?.toLowerCase() ?? '']
|
|
120
|
+
|
|
121
|
+
/** The last part of a path ("photos/team.jpg" → "team.jpg"), for the stored file name. */
|
|
122
|
+
const baseName = (path: string) => path.split(/[\\/]/).pop()!.trim()
|
|
123
|
+
|
|
124
|
+
/** `text` as one shell word in single quotes, so a file name cannot end the quote. */
|
|
125
|
+
const shellWord = (text: string) => `'${text.replaceAll("'", `'\\''`)}'`
|
|
126
|
+
|
|
127
|
+
const REDIRECTS = 3
|
|
128
|
+
/** How long the door waits for a file, from the first request to the last byte. */
|
|
129
|
+
const FETCH_MS = 20_000
|
|
130
|
+
|
|
131
|
+
/** The file at a public address, following at most REDIRECTS redirects, each to a public address too. */
|
|
132
|
+
async function fetchPublic(address: string, signal: AbortSignal): Promise<{ response: Response; url: URL } | { refused: string }> {
|
|
133
|
+
const local = process.env.GINKO_LOCAL === '1'
|
|
134
|
+
let url = address
|
|
135
|
+
for (let hop = 0; hop <= REDIRECTS; hop++) {
|
|
136
|
+
if (!isFetchableSiteUrl(url, local)) return { refused: t('en', 'errors.uploadUrlNotAllowed') }
|
|
137
|
+
let response: Response
|
|
138
|
+
try {
|
|
139
|
+
response = await fetch(url, { redirect: 'manual', signal })
|
|
140
|
+
} catch {
|
|
141
|
+
return { refused: t('en', 'errors.uploadFetchFailed', { url: address, status: signal.aborted ? 'no answer within 20 seconds' : 'network error' }) }
|
|
142
|
+
}
|
|
143
|
+
const next = response.status >= 300 && response.status < 400 ? response.headers.get('location') : null
|
|
144
|
+
if (!next) return { response, url: new URL(url) }
|
|
145
|
+
await response.body?.cancel()
|
|
146
|
+
try {
|
|
147
|
+
url = new URL(next, url).toString()
|
|
148
|
+
} catch {
|
|
149
|
+
return { refused: t('en', 'errors.uploadFetchFailed', { url: address, status: 'invalid redirect' }) }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { refused: t('en', 'errors.uploadFetchFailed', { url: address, status: 'too many redirects' }) }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The body, or undefined once it passes `limit` bytes (a missing or wrong Content-Length does not get around it). With
|
|
157
|
+
* a Content-Length the buffer is that size from the start; without, it doubles as needed. One copy of the file at most.
|
|
158
|
+
*/
|
|
159
|
+
async function readCapped(response: Response, limit: number): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
160
|
+
const declared = Number(response.headers.get('content-length') ?? 0)
|
|
161
|
+
if (declared > limit) {
|
|
162
|
+
await response.body?.cancel()
|
|
163
|
+
return undefined
|
|
164
|
+
}
|
|
165
|
+
const reader = response.body?.getReader()
|
|
166
|
+
if (!reader) return new Uint8Array(0)
|
|
167
|
+
let out = new Uint8Array(declared || 64 * 1024)
|
|
168
|
+
let size = 0
|
|
169
|
+
for (;;) {
|
|
170
|
+
const { done, value } = await reader.read()
|
|
171
|
+
if (done) break
|
|
172
|
+
if (size + value.byteLength > limit) {
|
|
173
|
+
await reader.cancel()
|
|
174
|
+
return undefined
|
|
175
|
+
}
|
|
176
|
+
if (size + value.byteLength > out.byteLength) {
|
|
177
|
+
const grown = new Uint8Array(Math.min(limit, Math.max(out.byteLength * 2, size + value.byteLength)))
|
|
178
|
+
grown.set(out.subarray(0, size))
|
|
179
|
+
out = grown
|
|
180
|
+
}
|
|
181
|
+
out.set(value, size)
|
|
182
|
+
size += value.byteLength
|
|
183
|
+
}
|
|
184
|
+
return size === out.byteLength ? out : out.slice(0, size)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The file name at the end of an address ("team.jpg"), or '' when there is none or it is not valid percent-encoding. */
|
|
188
|
+
function lastSegment(url: URL): string {
|
|
189
|
+
try {
|
|
190
|
+
return decodeURIComponent(url.pathname.split('/').pop() ?? '')
|
|
191
|
+
} catch {
|
|
192
|
+
return ''
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* ginko_upload: a library file for the key's person, through the same ticket and checks as the Studio's upload. With
|
|
198
|
+
* `url` the door fetches the file and takes the ticket only once the file passed (so a failed fetch costs no upload
|
|
199
|
+
* of the person's quota); without, it hands out the one-time upload address for a local file.
|
|
200
|
+
*/
|
|
201
|
+
async function uploadThroughDoor(ctx: ActionCtx, key: Id<'agentKeys'>, args: Record<string, Json>) {
|
|
202
|
+
const url = typeof args.url === 'string' ? args.url : undefined
|
|
203
|
+
const given = typeof args.name === 'string' ? args.name.trim() : ''
|
|
204
|
+
if (url === undefined) {
|
|
205
|
+
const { ticket } = await ctx.runMutation(internal.agent.uploadTicket, { key })
|
|
206
|
+
const path = given || 'file.jpg'
|
|
207
|
+
const name = baseName(path) || 'file.jpg'
|
|
208
|
+
const address = `${process.env.CONVEX_SITE_URL}/upload?ticket=${encodeURIComponent(ticket)}&name=${encodeURIComponent(name)}`
|
|
209
|
+
const type = typeOfName(name) ?? '<image/jpeg | image/png | image/webp | application/pdf>'
|
|
210
|
+
return toolText('Send the file to this address within 10 minutes (once). The answer is { "upload": "<file ID>" }.', {
|
|
211
|
+
upload_url: address,
|
|
212
|
+
curl: `curl -sS -X POST -H 'Content-Type: ${type}' --data-binary @${shellWord(path)} '${address}'`,
|
|
213
|
+
})
|
|
214
|
+
}
|
|
215
|
+
await ctx.runQuery(internal.agent.mayUpload, { key })
|
|
216
|
+
const signal = AbortSignal.timeout(FETCH_MS)
|
|
217
|
+
const fetched = await fetchPublic(url, signal)
|
|
218
|
+
if ('refused' in fetched) return toolText(fetched.refused, undefined, true)
|
|
219
|
+
const { response } = fetched
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
await response.body?.cancel()
|
|
222
|
+
return toolText(t('en', 'errors.uploadFetchFailed', { url, status: response.status }), undefined, true)
|
|
223
|
+
}
|
|
224
|
+
const name = baseName(given) || lastSegment(fetched.url) || 'file'
|
|
225
|
+
// Many file hosts answer with a generic type; then the name decides, and storeFile checks the bytes against it.
|
|
226
|
+
const declared = (response.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase()
|
|
227
|
+
const type = declared === '' || declared === 'application/octet-stream' ? typeOfName(name) ?? declared : declared
|
|
228
|
+
const kind = kindOf(type)
|
|
229
|
+
// Refused before the body is read: a type the library does not take, or more bytes than its limit.
|
|
230
|
+
if (!kind) {
|
|
231
|
+
await response.body?.cancel()
|
|
232
|
+
return toolText(t('en', WRONG_TYPE.key, WRONG_TYPE.params), undefined, true)
|
|
233
|
+
}
|
|
234
|
+
let bytes: Uint8Array<ArrayBuffer> | undefined
|
|
235
|
+
try {
|
|
236
|
+
bytes = await readCapped(response, kind.limit)
|
|
237
|
+
} catch {
|
|
238
|
+
return toolText(t('en', 'errors.uploadFetchFailed', { url, status: signal.aborted ? 'no answer within 20 seconds' : 'network error' }), undefined, true)
|
|
239
|
+
}
|
|
240
|
+
if (!bytes) return toolText(t('en', TOO_LARGE.key, TOO_LARGE.params), undefined, true)
|
|
241
|
+
const { ticket } = await ctx.runMutation(internal.agent.uploadTicket, { key })
|
|
242
|
+
const owner = await ctx.runMutation(internal.uploads.redeem, { ticket })
|
|
243
|
+
if (!owner) return toolText(t('en', 'errors.uploadExpired'), undefined, true)
|
|
244
|
+
const stored = await storeFile(ctx, owner, name, type, bytes)
|
|
245
|
+
if (!stored.ok) return toolText(t('en', stored.key, stored.params), undefined, true)
|
|
246
|
+
const image = type.startsWith('image/')
|
|
247
|
+
return toolText(`Uploaded “${name}” as file ${stored.upload}.${image ? ' The image is processed for a few seconds before the website shows it.' : ''}`, {
|
|
248
|
+
file: stored.upload, name,
|
|
249
|
+
...(image ? { image_field: { file: stored.upload, alt: '' }, markdown: `` } : { file_field: { file: stored.upload }, markdown: `[${name}]($file.${stored.upload})` }),
|
|
250
|
+
})
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const mcp = httpAction(async (ctx, request) => {
|
|
254
|
+
const header = request.headers.get('authorization') ?? ''
|
|
255
|
+
const token = header.startsWith('Bearer ') ? header.slice('Bearer '.length).trim() : ''
|
|
256
|
+
const admitted = KEY.test(token) ? await ctx.runMutation(internal.agent.admit, { hash: sha256(token) }) : { ok: false as const, code: 'UNAUTHORIZED' as const }
|
|
257
|
+
if (!admitted.ok) {
|
|
258
|
+
return admitted.code === 'RATE_LIMITED'
|
|
259
|
+
? rpcError(null, -32000, 'Too many calls. Wait a minute.', 429)
|
|
260
|
+
: rpcError(null, -32001, 'The key is missing, invalid or revoked.', 401)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const raw = await request.text()
|
|
264
|
+
if (new TextEncoder().encode(raw).byteLength > BODY_MAX) return rpcError(null, -32600, 'The request is too large.', 413)
|
|
265
|
+
let body: unknown
|
|
266
|
+
try {
|
|
267
|
+
body = JSON.parse(raw)
|
|
268
|
+
} catch {
|
|
269
|
+
return rpcError(null, -32700, 'The request is not valid JSON.', 400)
|
|
270
|
+
}
|
|
271
|
+
if (!isRpc(body)) return rpcError(null, -32600, 'This is not a JSON-RPC 2.0 request.', 400)
|
|
272
|
+
// A notification (no id) gets no answer (MCP Streamable HTTP: 202).
|
|
273
|
+
if (body.id === undefined) return reply(202)
|
|
274
|
+
|
|
275
|
+
const { id, method, params = {} } = body
|
|
276
|
+
if (method === 'initialize') {
|
|
277
|
+
return result(id, { protocolVersion: PROTOCOL, capabilities: { tools: {} }, serverInfo: { name: 'ginko', version: '1' }, instructions: INSTRUCTIONS })
|
|
278
|
+
}
|
|
279
|
+
if (method === 'ping') return result(id, {})
|
|
280
|
+
if (method === 'tools/list') return result(id, { tools: await ctx.runQuery(internal.agent.tools, { key: admitted.key }) })
|
|
281
|
+
if (method === 'tools/call') {
|
|
282
|
+
const name = typeof params.name === 'string' ? params.name : ''
|
|
283
|
+
const args = typeof params.arguments === 'object' && params.arguments !== null && !Array.isArray(params.arguments) ? params.arguments as Record<string, Json> : {}
|
|
284
|
+
const answer = await callTool(ctx, admitted.key, name, args)
|
|
285
|
+
const sized = new TextEncoder().encode(JSON.stringify(answer)).byteLength > ANSWER_MAX
|
|
286
|
+
? toolText('The answer would be too large. Ask for a single brick or fewer entries.', undefined, true)
|
|
287
|
+
: answer
|
|
288
|
+
return result(id, sized)
|
|
289
|
+
}
|
|
290
|
+
return rpcError(id, -32601, `The method “${method}” does not exist here.`)
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
// No SSE stream and no sessions: GET and DELETE are not offered (MCP Streamable HTTP allows 405).
|
|
294
|
+
const notOffered = httpAction(async () => reply(405, undefined, { allow: 'POST' }))
|
|
295
|
+
|
|
296
|
+
export function register(http: HttpRouter) {
|
|
297
|
+
http.route({ path: '/mcp', method: 'POST', handler: mcp })
|
|
298
|
+
http.route({ path: '/mcp', method: 'GET', handler: notOffered })
|
|
299
|
+
http.route({ path: '/mcp', method: 'DELETE', handler: notOffered })
|
|
300
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// HTTP routes for the CLI's release (SPEC 5.1): `GET /release/state?site=<slug>` and `POST /release`.
|
|
2
|
+
// The push key `Authorization: Bearer ginko_<site>_<32>` names the site; only its SHA-256 is stored.
|
|
3
|
+
import type { HttpRouter } from 'convex/server'
|
|
4
|
+
import { internal } from '../_generated/api'
|
|
5
|
+
import { httpAction } from '../_generated/server'
|
|
6
|
+
import { t } from '../lib/i18n'
|
|
7
|
+
import { badKey } from '../lib/input'
|
|
8
|
+
import { RELEASE_LIMITS } from '../release'
|
|
9
|
+
import { authenticate, errorResponse, failure, json } from './key'
|
|
10
|
+
|
|
11
|
+
function isRelease(body: unknown): body is {
|
|
12
|
+
site?: string; commit: string; expectedSchemaRev: number; expectedContentRev: number; schema: object
|
|
13
|
+
writes: { entry: string; fields: Record<string, unknown> }[]
|
|
14
|
+
} {
|
|
15
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) return false
|
|
16
|
+
const b = body as Record<string, unknown>
|
|
17
|
+
if (b.site !== undefined && typeof b.site !== 'string') return false
|
|
18
|
+
if (typeof b.commit !== 'string' || !Number.isInteger(b.expectedSchemaRev) || !Number.isInteger(b.expectedContentRev)) return false
|
|
19
|
+
if (typeof b.schema !== 'object' || b.schema === null || Array.isArray(b.schema)) return false
|
|
20
|
+
if (!Array.isArray(b.writes)) return false
|
|
21
|
+
return b.writes.every((w) => typeof w === 'object' && w !== null && typeof (w as { entry?: unknown }).entry === 'string'
|
|
22
|
+
&& typeof (w as { fields?: unknown }).fields === 'object' && (w as { fields?: unknown }).fields !== null
|
|
23
|
+
&& !Array.isArray((w as { fields?: unknown }).fields))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const state = httpAction(async (ctx, request) => {
|
|
27
|
+
const key = await authenticate(ctx, request, ['release', 'check'])
|
|
28
|
+
if (key instanceof Response) return key
|
|
29
|
+
const slug = new URL(request.url).searchParams.get('site')
|
|
30
|
+
if (!slug) return failure('INVALID', 'The parameter site is missing.')
|
|
31
|
+
if (slug !== key.siteSlug) return failure('FORBIDDEN', 'This key belongs to another site.')
|
|
32
|
+
try {
|
|
33
|
+
return json(200, await ctx.runQuery(internal.release.state, { site: key.site }))
|
|
34
|
+
} catch (error) {
|
|
35
|
+
return errorResponse(error)
|
|
36
|
+
}
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
const release = httpAction(async (ctx, request) => {
|
|
40
|
+
const key = await authenticate(ctx, request, ['release'])
|
|
41
|
+
if (key instanceof Response) return key
|
|
42
|
+
const raw = await request.text()
|
|
43
|
+
if (new TextEncoder().encode(raw).byteLength > RELEASE_LIMITS.argBytes) return failure('RELEASE_TOO_LARGE', 'This release is too large.')
|
|
44
|
+
let body: unknown
|
|
45
|
+
try {
|
|
46
|
+
body = JSON.parse(raw)
|
|
47
|
+
} catch {
|
|
48
|
+
return failure('INVALID', 'The body is not valid JSON.')
|
|
49
|
+
}
|
|
50
|
+
if (!isRelease(body)) return failure('INVALID', 'The release does not have the expected shape.')
|
|
51
|
+
// Convex refuses some keys (`$…`, non-ASCII, over 1024 characters) with an uncoded error before the mutation runs.
|
|
52
|
+
const bad = badKey(body)
|
|
53
|
+
if (bad) return failure('INVALID', t('en', 'errors.nameNotAllowed', { name: bad }))
|
|
54
|
+
if (body.site !== undefined && body.site !== key.siteSlug) return failure('FORBIDDEN', 'This key belongs to another site.')
|
|
55
|
+
try {
|
|
56
|
+
const { site: _site, ...args } = body
|
|
57
|
+
return json(200, await ctx.runMutation(internal.release.release, { ...args, site: key.site, actor: `pushkey:${key.keyId}`, schema: args.schema, writes: args.writes }))
|
|
58
|
+
} catch (error) {
|
|
59
|
+
return errorResponse(error)
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
export function register(http: HttpRouter) {
|
|
64
|
+
http.route({ path: '/release/state', method: 'GET', handler: state })
|
|
65
|
+
http.route({ path: '/release', method: 'POST', handler: release })
|
|
66
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// POST /upload?ticket=<ticket>&name=<file name> (SPEC 4.3). The body is the file, its Content-Type
|
|
2
|
+
// says what kind it is (image or PDF). Order: ticket (used up, names member and site), type, size,
|
|
3
|
+
// content signature, then store and register for exactly that member and site. The file is stored
|
|
4
|
+
// as the type its bytes prove. Every refusal happens before the file is stored; a failed register
|
|
5
|
+
// deletes the stored file at once.
|
|
6
|
+
import type { HttpRouter } from 'convex/server'
|
|
7
|
+
import { internal } from '../_generated/api'
|
|
8
|
+
import type { Id } from '../_generated/dataModel'
|
|
9
|
+
import { httpAction, type ActionCtx } from '../_generated/server'
|
|
10
|
+
import { EMPTY, HEIC, isHeic, kindOf, TOO_LARGE, typeOfBytes, WRONG_CONTENT, WRONG_TYPE } from '../lib/files'
|
|
11
|
+
import { t, type MessageKey } from '../lib/i18n'
|
|
12
|
+
|
|
13
|
+
/** Only the platform UI (`SITE_URL`, the origin sign-in uses too) may call this route from the browser (CORS). */
|
|
14
|
+
function headersFor(request: Request): Record<string, string> {
|
|
15
|
+
const origin = request.headers.get('Origin')
|
|
16
|
+
if (!origin || origin !== process.env.SITE_URL?.replace(/\/$/, '')) return {}
|
|
17
|
+
return {
|
|
18
|
+
'Access-Control-Allow-Origin': origin,
|
|
19
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
20
|
+
'Access-Control-Allow-Headers': 'Content-Type',
|
|
21
|
+
'Access-Control-Max-Age': '600',
|
|
22
|
+
Vary: 'Origin',
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Refusal = { key: MessageKey; params?: Record<string, string | number> }
|
|
27
|
+
|
|
28
|
+
/** Answers with the upload id, or with `{ code, key, params, message }` (SPEC 11): the catalog message, `message` its German text. */
|
|
29
|
+
function reply(request: Request, status: number, body: { upload: string } | ({ code: string } & Refusal)) {
|
|
30
|
+
const out = 'key' in body ? { ...body, message: t('de', body.key, body.params) } : body
|
|
31
|
+
return Response.json(out, { status, headers: headersFor(request) })
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type Owner = { site: Id<'sites'>; user: string; folder?: Id<'folders'>; library?: boolean }
|
|
35
|
+
export type Stored = { ok: true; upload: string } | ({ ok: false; status: number; code: string } & Refusal)
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Checks a file's type, size and content and stores it for `owner` (a redeemed ticket). Shared by POST /upload and the
|
|
39
|
+
* agent door's ginko_upload, so a file from a URL passes exactly the checks of one from the Studio.
|
|
40
|
+
*/
|
|
41
|
+
export async function storeFile(ctx: ActionCtx, owner: Owner, name: string, type: string, bytes: Uint8Array<ArrayBuffer>): Promise<Stored> {
|
|
42
|
+
const refuse = (status: number, refusal: Refusal, code = 'UPLOAD_REJECTED'): Stored => ({ ok: false, status, code, ...refusal })
|
|
43
|
+
if (isHeic({ name, mime: type })) return refuse(415, HEIC)
|
|
44
|
+
const kind = kindOf(type)
|
|
45
|
+
if (!kind) return refuse(415, WRONG_TYPE)
|
|
46
|
+
if (bytes.byteLength > kind.limit) return refuse(413, TOO_LARGE)
|
|
47
|
+
if (bytes.byteLength === 0) return refuse(415, EMPTY)
|
|
48
|
+
const mime = typeOfBytes(kind.kind, bytes)
|
|
49
|
+
if (!mime) return refuse(415, isHeic({ bytes }) ? HEIC : WRONG_CONTENT)
|
|
50
|
+
|
|
51
|
+
const storageId = await ctx.storage.store(new Blob([bytes], { type: mime }))
|
|
52
|
+
try {
|
|
53
|
+
const upload = await ctx.runMutation(internal.uploads.register, {
|
|
54
|
+
site: owner.site, uploader: owner.user, storageId, name, size: bytes.byteLength, mime,
|
|
55
|
+
...(owner.folder ? { folder: owner.folder } : {}), ...(owner.library ? { library: true } : {}),
|
|
56
|
+
})
|
|
57
|
+
return { ok: true, upload }
|
|
58
|
+
} catch (error) {
|
|
59
|
+
await ctx.storage.delete(storageId)
|
|
60
|
+
const data = (error as { data?: { code?: string; key?: MessageKey; params?: Record<string, string | number> } }).data
|
|
61
|
+
if (data?.code && data.key) return refuse(400, { key: data.key, ...(data.params ? { params: data.params } : {}) }, data.code)
|
|
62
|
+
throw error
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function receive(ctx: ActionCtx, request: Request): Promise<Response> {
|
|
67
|
+
const url = new URL(request.url)
|
|
68
|
+
const owner = await ctx.runMutation(internal.uploads.redeem, { ticket: url.searchParams.get('ticket') ?? '' })
|
|
69
|
+
if (!owner) return reply(request, 403, { code: 'FORBIDDEN', key: 'errors.uploadExpired' })
|
|
70
|
+
|
|
71
|
+
// Refused before the body is read: a declared size over the limit of its type.
|
|
72
|
+
const declared = request.headers.get('Content-Length')
|
|
73
|
+
const kind = kindOf(request.headers.get('Content-Type') ?? '')
|
|
74
|
+
if (kind && declared !== null && Number(declared) > kind.limit) return reply(request, 413, { code: 'UPLOAD_REJECTED', ...TOO_LARGE })
|
|
75
|
+
const stored = await storeFile(ctx, owner, url.searchParams.get('name') ?? '', request.headers.get('Content-Type') ?? '', new Uint8Array(await request.arrayBuffer()))
|
|
76
|
+
if (stored.ok) return reply(request, 200, { upload: stored.upload })
|
|
77
|
+
const { status, code, key, params } = stored
|
|
78
|
+
return reply(request, status, { code, key, ...(params ? { params } : {}) })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const upload = httpAction(async (ctx, request) => {
|
|
82
|
+
try {
|
|
83
|
+
return await receive(ctx, request)
|
|
84
|
+
} catch {
|
|
85
|
+
return reply(request, 500, { code: 'INVALID', key: 'errors.uploadFailed' })
|
|
86
|
+
}
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
const preflight = httpAction(async (_ctx, request) => new Response(null, { status: 204, headers: headersFor(request) }))
|
|
90
|
+
|
|
91
|
+
export function register(http: HttpRouter) {
|
|
92
|
+
http.route({ path: '/upload', method: 'POST', handler: upload })
|
|
93
|
+
http.route({ path: '/upload', method: 'OPTIONS', handler: preflight })
|
|
94
|
+
}
|