@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.
Files changed (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/convex/_generated/api.d.ts +185 -0
  5. package/convex/_generated/api.js +23 -0
  6. package/convex/_generated/dataModel.d.ts +60 -0
  7. package/convex/_generated/server.d.ts +162 -0
  8. package/convex/_generated/server.js +101 -0
  9. package/convex/account.ts +110 -0
  10. package/convex/agent.ts +814 -0
  11. package/convex/auth.config.ts +4 -0
  12. package/convex/auth.ts +62 -0
  13. package/convex/backup.ts +94 -0
  14. package/convex/betterAuth/_generated/api.ts +56 -0
  15. package/convex/betterAuth/_generated/component.ts +431 -0
  16. package/convex/betterAuth/_generated/dataModel.ts +60 -0
  17. package/convex/betterAuth/_generated/server.ts +169 -0
  18. package/convex/betterAuth/adapter.ts +7 -0
  19. package/convex/betterAuth/convex.config.ts +3 -0
  20. package/convex/betterAuth/schema.ts +102 -0
  21. package/convex/betterAuth/schemaMetadata.ts +697 -0
  22. package/convex/betterAuth/schemaOptions.ts +13 -0
  23. package/convex/betterAuth/schemaPlugins.ts +13 -0
  24. package/convex/bundle.ts +183 -0
  25. package/convex/changes.ts +136 -0
  26. package/convex/cleanup.ts +44 -0
  27. package/convex/connect.ts +143 -0
  28. package/convex/convex.config.ts +7 -0
  29. package/convex/crons.ts +14 -0
  30. package/convex/demo.ts +72 -0
  31. package/convex/entries.ts +1770 -0
  32. package/convex/facts.ts +129 -0
  33. package/convex/files.ts +631 -0
  34. package/convex/http.ts +21 -0
  35. package/convex/image.ts +45 -0
  36. package/convex/images.ts +54 -0
  37. package/convex/invites.ts +227 -0
  38. package/convex/lib/access.ts +180 -0
  39. package/convex/lib/agentTools.ts +331 -0
  40. package/convex/lib/content.ts +317 -0
  41. package/convex/lib/corpus.ts +83 -0
  42. package/convex/lib/diff.ts +50 -0
  43. package/convex/lib/fail.ts +27 -0
  44. package/convex/lib/files.ts +70 -0
  45. package/convex/lib/history.ts +103 -0
  46. package/convex/lib/i18n.ts +52 -0
  47. package/convex/lib/input.ts +57 -0
  48. package/convex/lib/library.ts +28 -0
  49. package/convex/lib/lifecycle.ts +100 -0
  50. package/convex/lib/list.ts +112 -0
  51. package/convex/lib/migrations.ts +126 -0
  52. package/convex/lib/names.ts +56 -0
  53. package/convex/lib/pending.ts +84 -0
  54. package/convex/lib/policy.ts +155 -0
  55. package/convex/lib/publicness.ts +87 -0
  56. package/convex/lib/reminders.ts +27 -0
  57. package/convex/lib/search.ts +132 -0
  58. package/convex/lib/siteUrl.ts +95 -0
  59. package/convex/lib/status.ts +109 -0
  60. package/convex/lib/translation.ts +56 -0
  61. package/convex/lib/trees.ts +43 -0
  62. package/convex/lib/write.ts +296 -0
  63. package/convex/mail.ts +136 -0
  64. package/convex/members.ts +129 -0
  65. package/convex/migrations.ts +105 -0
  66. package/convex/navigation.ts +276 -0
  67. package/convex/ops.ts +50 -0
  68. package/convex/proposals.ts +753 -0
  69. package/convex/refresh.ts +163 -0
  70. package/convex/release.ts +435 -0
  71. package/convex/reminders.ts +116 -0
  72. package/convex/retention.ts +121 -0
  73. package/convex/routes/bundle.ts +62 -0
  74. package/convex/routes/connect.ts +80 -0
  75. package/convex/routes/export.ts +23 -0
  76. package/convex/routes/file.ts +34 -0
  77. package/convex/routes/key.ts +53 -0
  78. package/convex/routes/mcp.ts +300 -0
  79. package/convex/routes/release.ts +66 -0
  80. package/convex/routes/upload.ts +94 -0
  81. package/convex/schema.ts +443 -0
  82. package/convex/search.ts +58 -0
  83. package/convex/seed.ts +624 -0
  84. package/convex/siteDeletion.ts +78 -0
  85. package/convex/sites.ts +393 -0
  86. package/convex/tasks.ts +51 -0
  87. package/convex/tsconfig.json +27 -0
  88. package/convex/uploads.ts +429 -0
  89. package/convex/uploadsNode.ts +86 -0
  90. package/convex/views.ts +111 -0
  91. package/i18n/de.json +364 -0
  92. package/i18n/en.json +364 -0
  93. package/i18n/es.json +364 -0
  94. package/i18n/fr.json +364 -0
  95. package/package.json +45 -3
@@ -0,0 +1,814 @@
1
+ // The agent door (SPEC 16): a person's keys, and the tools behind POST /mcp (routes/mcp.ts).
2
+ // A key acts as its person with their role and grants at call time. Every write runs through the
3
+ // same operations as the platform (`saveAs`, `createAs`, ...), so rights, checks and history are one.
4
+ import type { Fields, Json } from '@lupinum/ginko'
5
+ import { labelOf as labelIn, checkLinks, fieldsInputSchema, fromToolInput, isSafeHref, isTranslatable, sha256, taskInputSchema, type JsonSchemaObject, type Schema } from '@lupinum/ginko/internal'
6
+ import { ConvexError, v } from 'convex/values'
7
+ import { components } from './_generated/api'
8
+ import type { Doc, Id } from './_generated/dataModel'
9
+ import { bundleOf } from './bundle'
10
+ import { factCopiesIn, factCopyNote, factsOf, type FactCopyFound, type StudioFact } from './facts'
11
+ import { internalMutation, internalQuery, mutation, query, type MutationCtx, type QueryCtx } from './_generated/server'
12
+ import { createAs, labelOf, removeAs, revertAs, saveAs, undoAs, usesOfEntry, versionAtAs } from './entries'
13
+ import { usageAs } from './files'
14
+ import { ownAs } from './proposals'
15
+ import { actorFor, entryOf, fail, idempotent, memberOf, type Actor } from './lib/access'
16
+ import { searchEntries as searchAll, searchTexts } from './lib/search'
17
+ import { builderTools, BUILDER_TOOLS, DRY_RUN, IMPORT_MAX, isBuilder, suggest, fixedTools, HISTORY_MAX, PROPOSE, PUBLISH, REQUEST_ID, SEARCH_MAX, linksIn, taskFor, taskHints, taskTools, describeTask, draftBricks, type TaskTool, type ToolDef } from './lib/agentTools'
18
+ import type { Data } from './lib/content'
19
+ import { leafStatus } from './lib/translation'
20
+ import { historyText, type HistoryMsg } from './lib/history'
21
+ import { same } from './lib/write'
22
+ import { effectiveReview } from './lib/policy'
23
+ import { secret } from './release'
24
+ import { normalizeEmail } from './members'
25
+ import { prefillAs } from './tasks'
26
+ import { ticketFor } from './uploads'
27
+
28
+ /** SPEC 16: 60 calls per minute and key. */
29
+ export const AGENT_RATE_LIMIT = 60
30
+ const KEYS_PER_PERSON = 10
31
+ const PROPOSAL_STATUS = ['open', 'scheduled', 'applied', 'rejected', 'stale', 'withdrawn']
32
+
33
+ // ---- Keys: created, listed and revoked by the person in the platform ("Mit KI verbinden"). ----
34
+
35
+ /** A new key for the signed-in person on this site. The plaintext is returned once; only its SHA-256 is stored. */
36
+ export const createKey = mutation({
37
+ args: { site: v.string(), label: v.string() },
38
+ handler: async (ctx, args) => {
39
+ const actor = await actorFor(ctx, args.site)
40
+ const label = args.label.trim()
41
+ if (label.length < 1 || label.length > 60) fail('INVALID', 'errors.nameLength1To60')
42
+ const own = await ctx.db.query('agentKeys').withIndex('by_site_user', (q) => q.eq('site', actor.site._id).eq('user', actor.user.id)).collect()
43
+ if (own.filter((k) => !k.revokedAt).length >= KEYS_PER_PERSON) fail('INVALID', 'errors.keyLimitReached', { keysPerPerson: KEYS_PER_PERSON })
44
+ const key = `ginko_agent_${secret()}`
45
+ const id = await ctx.db.insert('agentKeys', { site: actor.site._id, user: actor.user.id, hash: sha256(key), label, createdAt: Date.now() })
46
+ return { id, key }
47
+ },
48
+ })
49
+
50
+ /** The signed-in person's keys on this site, newest first. Never the hash. */
51
+ export const keys = query({
52
+ args: { site: v.string() },
53
+ handler: async (ctx, args) => {
54
+ const actor = await actorFor(ctx, args.site)
55
+ const rows = await ctx.db.query('agentKeys').withIndex('by_site_user', (q) => q.eq('site', actor.site._id).eq('user', actor.user.id)).order('desc').collect()
56
+ return rows.map((k) => ({
57
+ id: k._id, label: k.label, createdAt: k.createdAt, lastUsedAt: k.lastUsedAt ?? null, revokedAt: k.revokedAt ?? null,
58
+ /** The key's own setting (null: the site decides) and what that makes of it now (SPEC 17). */
59
+ review: k.review ?? null, reviewEffective: effectiveReview(k, actor.site),
60
+ }))
61
+ },
62
+ })
63
+
64
+ /** Revokes a key: the person's own, or any key of the site for owners and admins. Twice changes nothing. */
65
+ export const revokeKey = mutation({
66
+ args: { site: v.string(), key: v.string() },
67
+ handler: async (ctx, args) => {
68
+ const actor = await actorFor(ctx, args.site)
69
+ const id = ctx.db.normalizeId('agentKeys', args.key)
70
+ const row = id ? await ctx.db.get(id) : null
71
+ if (!row || row.site !== actor.site._id || (row.user !== actor.user.id && actor.role === 'staff')) fail('NOT_FOUND', 'errors.keyNotFound')
72
+ if (!row.revokedAt) await ctx.db.patch(row._id, { revokedAt: Date.now() })
73
+ return { id: row._id }
74
+ },
75
+ })
76
+
77
+ /**
78
+ * Sets whether this key's writes are proposals (SPEC 17); `null` hands the decision back to the site.
79
+ * The key's person and owners/admins may switch it on. Only owners and admins may switch it off or
80
+ * clear it: otherwise staff could lift the site's review for their own key.
81
+ */
82
+ export const setKeyReview = mutation({
83
+ args: { site: v.string(), key: v.string(), review: v.union(v.boolean(), v.null()) },
84
+ handler: async (ctx, args) => {
85
+ const actor = await actorFor(ctx, args.site)
86
+ const id = ctx.db.normalizeId('agentKeys', args.key)
87
+ const row = id ? await ctx.db.get(id) : null
88
+ const approver = actor.role !== 'staff'
89
+ if (!row || row.site !== actor.site._id || (row.user !== actor.user.id && !approver)) fail('NOT_FOUND', 'errors.keyNotFound')
90
+ if (args.review !== true && !approver) fail('FORBIDDEN', 'errors.onlyOwnersCanDisableReview')
91
+ await ctx.db.patch(row._id, { review: args.review ?? undefined })
92
+ return { id: row._id, review: args.review, reviewEffective: effectiveReview({ review: args.review ?? undefined }, actor.site) }
93
+ },
94
+ })
95
+
96
+ // ---- The door: key → actor, rate limit, tools, calls. Internal: only routes/mcp.ts calls these. ----
97
+
98
+ /** The person behind a key, with their role and grants now; null when revoked or no longer a member. */
99
+ async function agentActor(ctx: QueryCtx, keyId: Id<'agentKeys'>): Promise<Actor | null> {
100
+ const key = await ctx.db.get(keyId)
101
+ if (!key || key.revokedAt) return null
102
+ const site = await ctx.db.get(key.site)
103
+ const actor = site && await memberOf(ctx, site, { id: key.user })
104
+ return actor ? { ...actor, agentKey: key._id } : null
105
+ }
106
+
107
+ async function actorOrFail(ctx: QueryCtx, keyId: Id<'agentKeys'>): Promise<Actor> {
108
+ const actor = await agentActor(ctx, keyId)
109
+ // The HTTP layer admitted the key a moment ago; this covers a revocation in between.
110
+ if (!actor) fail('FORBIDDEN', 'errors.keyNoLongerValid')
111
+ return actor
112
+ }
113
+
114
+ /** First step of every request: the key must be live and its person a member; counts the call for the rate limit. */
115
+ export const admit = internalMutation({
116
+ args: { hash: v.string() },
117
+ handler: async (ctx, { hash }): Promise<{ ok: true; key: Id<'agentKeys'> } | { ok: false; code: 'UNAUTHORIZED' | 'RATE_LIMITED' }> => {
118
+ const key = await ctx.db.query('agentKeys').withIndex('by_hash', (q) => q.eq('hash', hash)).unique()
119
+ if (!key || !(await agentActor(ctx, key._id))) return { ok: false, code: 'UNAUTHORIZED' }
120
+ const now = Date.now()
121
+ const minute = Math.floor(now / 60_000)
122
+ const calls = key.minute === minute ? (key.calls ?? 0) : 0
123
+ if (calls >= AGENT_RATE_LIMIT) return { ok: false, code: 'RATE_LIMITED' }
124
+ await ctx.db.patch(key._id, { minute, calls: calls + 1, lastUsedAt: now })
125
+ return { ok: true, key: key._id }
126
+ },
127
+ })
128
+
129
+ /**
130
+ * The prefilled values of a task, resolved against the entry an edit changes, so a day already set stays (`prefillAs`).
131
+ * Only the prefilled fields: the stored values of the task's other fields are not written again.
132
+ */
133
+ async function prefillOf(ctx: QueryCtx, actor: Actor, tool: TaskTool, entry?: Id<'entries'>): Promise<Record<string, Json>> {
134
+ const values = await prefillAs(ctx, actor, { site: actor.site.slug, task: tool.ref, ...(entry ? { entry } : {}) }) as Record<string, Json>
135
+ const keys = Object.keys(('prefill' in tool.task && tool.task.prefill) || {})
136
+ return Object.fromEntries(Object.entries(values).filter(([key]) => keys.includes(key)))
137
+ }
138
+
139
+ async function inputSchemaOf(ctx: QueryCtx, actor: Actor, tool: TaskTool): Promise<JsonSchemaObject> {
140
+ const schema = actor.site.schema as Schema
141
+ // An edit of a single offers what it would write there now; a picked entry is known only at the call.
142
+ const single = tool.task.kind === 'edit' ? await singleOf(ctx, actor, tool.brick) : undefined
143
+ const prefill = await prefillOf(ctx, actor, tool, single?._id)
144
+ return taskInputSchema(schema.bricks[tool.brick]!, tool.task, { mainLocale: schema.locales[0]!, currency: schema.currency, prefill })
145
+ }
146
+
147
+ /** tools/list: the fixed tools and one tool per task the person may run; every task tool may carry `propose` and `request_id`, a create or edit task `publish`. */
148
+ export const tools = internalQuery({
149
+ args: { key: v.id('agentKeys') },
150
+ handler: async (ctx, { key }) => {
151
+ const actor = await actorOrFail(ctx, key)
152
+ const schema = actor.site.schema as Schema
153
+ const out: ToolDef[] = [...fixedTools(actor), ...builderTools(actor)]
154
+ for (const tool of taskTools(actor)) {
155
+ const input = await inputSchemaOf(ctx, actor, tool)
156
+ out.push({
157
+ name: tool.name, description: describeTask(schema.bricks[tool.brick]!, tool.task, schema.locales[0]!),
158
+ inputSchema: { ...input, properties: { ...input.properties, ...(tool.task.kind === 'remove' ? {} : { publish: PUBLISH }), propose: PROPOSE, request_id: REQUEST_ID } } as unknown as Json, annotations: taskHints(tool.task),
159
+ })
160
+ }
161
+ return out
162
+ },
163
+ })
164
+
165
+ /** ginko_overview, plus the site slug the HTTP layer needs for ginko_read. */
166
+ export const overview = internalQuery({
167
+ args: { key: v.id('agentKeys') },
168
+ handler: async (ctx, { key }) => {
169
+ const actor = await actorOrFail(ctx, key)
170
+ const schema = actor.site.schema as Schema
171
+ const allowed = taskTools(actor)
172
+ const review = effectiveReview(await ctx.db.get(key), actor.site)
173
+ // Values the site keeps in one place; texts quote them (`:fact{name="…"}`) instead of copying them.
174
+ const facts = (await factsOf(ctx, actor.site)).map((fact) => ({
175
+ quote: `:fact{name="${fact.name}"}`,
176
+ label: labelIn(schema.bricks[fact.brick]!.fields[fact.field]!.label, schema.locales[0]!, schema.locales[0]!),
177
+ shows: fact.text ?? null,
178
+ ...(fact.next ? { next: { shows: fact.next.text, from: fact.next.from } } : {}),
179
+ }))
180
+ return {
181
+ site: actor.site.slug,
182
+ name: actor.site.name,
183
+ url: schema.url,
184
+ locales: schema.locales,
185
+ role: actor.role,
186
+ /** True: changes through this key wait for approval (SPEC 17). */
187
+ review,
188
+ ...(review ? { hint: 'Changes made with this key wait for approval.' } : {}),
189
+ bricks: Object.entries(schema.bricks).filter(([, b]) => !b.retired).map(([brick, b]) => ({
190
+ brick, label: labelIn(b.label, schema.locales[0]!, schema.locales[0]!), kind: b.kind,
191
+ tasks: allowed.filter((t) => t.brick === brick).map((t) => ({ tool: t.name, label: labelIn(t.task.label, schema.locales[0]!, schema.locales[0]!) })),
192
+ })),
193
+ ...(facts.length ? { facts } : {}),
194
+ }
195
+ },
196
+ })
197
+
198
+ /** What the assistant is told when its call became a proposal (SPEC 17): nothing is live yet, and there is nothing to undo. */
199
+ const PROPOSED = 'Proposed, waiting for approval.'
200
+
201
+ /**
202
+ * A history line for the model: the catalog message in English, whatever the language of the person;
203
+ * rows written before `msg` only have the German `sentence`.
204
+ */
205
+ const lineFor = (row: { msg?: unknown; sentence: string }, schema: Schema): string =>
206
+ row.msg ? historyText(row.msg as HistoryMsg, 'en', schema) : row.sentence
207
+ const proposed = (result: Json): boolean => typeof result === 'object' && result !== null && !Array.isArray(result) && 'proposal' in result
208
+
209
+ const UNDOABLE = new Set(['save', 'create'])
210
+
211
+ /** ginko_history: the latest changes with their sentence (English); `undoable` when ginko_undo can take it back. */
212
+ export const history = internalQuery({
213
+ args: { key: v.id('agentKeys'), limit: v.optional(v.number()) },
214
+ handler: async (ctx, { key, limit }) => {
215
+ const actor = await actorOrFail(ctx, key)
216
+ const schema = actor.site.schema as Schema
217
+ const n = Math.min(Math.max(Math.floor(limit ?? 20), 1), HISTORY_MAX)
218
+ const rows = await ctx.db.query('changes').withIndex('by_site_at', (q) => q.eq('site', actor.site._id)).order('desc').take(n)
219
+ return rows.map((c) => ({
220
+ change: c._id, at: new Date(c.at).toISOString(), sentence: lineFor(c, schema), kind: c.kind,
221
+ ...(c.via ? { via: c.via } : {}), undoable: UNDOABLE.has(c.kind) && !c.undoneBy,
222
+ }))
223
+ },
224
+ })
225
+
226
+ /** The entry a task changes: the picked one, or the single entry of a single brick. */
227
+ async function targetOf(ctx: MutationCtx, actor: Actor, brick: string, picked: Json | undefined): Promise<Doc<'entries'>> {
228
+ if (picked !== undefined) {
229
+ if (typeof picked !== 'string') fail('INVALID', 'errors.entryIdMissing')
230
+ const entry = await entryOf(ctx, actor, picked)
231
+ if (entry.brick !== brick) fail('NOT_FOUND', 'errors.entryNotFound')
232
+ return entry
233
+ }
234
+ const entry = await singleOf(ctx, actor, brick)
235
+ if (!entry) fail('INVALID', 'errors.entryIdMissing')
236
+ return entry
237
+ }
238
+
239
+ /** The entry of a single brick; undefined for a collection. */
240
+ async function singleOf(ctx: QueryCtx, actor: Actor, brick: string): Promise<Doc<'entries'> | undefined> {
241
+ const entry = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', actor.site._id).eq('brick', brick)).first()
242
+ return entry?.kind === 'single' ? entry : undefined
243
+ }
244
+
245
+ /** The newest change row of an entry: the one the operation just wrote. */
246
+ function lastChangeOf(ctx: QueryCtx, entry: Id<'entries'>) {
247
+ return ctx.db.query('changes').withIndex('by_entry', (q) => q.eq('entry', entry)).order('desc').first()
248
+ }
249
+
250
+ function newRowId(): string {
251
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
252
+ return Array.from(crypto.getRandomValues(new Uint8Array(10)), (b) => alphabet[b % alphabet.length]).join('')
253
+ }
254
+
255
+ // ---- Tools that only read: search, an old version, a file's uses, the link check, the caller's proposals. ----
256
+
257
+ const text = (value: Json | undefined, what: string): string => {
258
+ if (typeof value !== 'string' || !value.trim()) fail('INVALID', 'errors.fieldMissing', { what })
259
+ return value
260
+ }
261
+
262
+ /** ginko_search: the shared search (lib/search.ts). Drafts are found too and marked. */
263
+ async function searchEntries(ctx: QueryCtx, actor: Actor, input: Record<string, Json>) {
264
+ const query = text(input.query, 'query')
265
+ const brick = typeof input.brick === 'string' ? input.brick : undefined
266
+ const limit = Math.min(Math.max(Math.floor(typeof input.limit === 'number' ? input.limit : 10), 1), SEARCH_MAX)
267
+ const hits = await searchAll(ctx, actor, { query, brick, limit })
268
+ return hits.map((hit) => ({ entry: hit.entry, brick: hit.brick, label: hit.label, snippet: hit.snippet, ...(hit.state === 'live' ? {} : { draft: true }) }))
269
+ }
270
+
271
+ /** ginko_check_links: the core link checker over the current content in every language, plus a scan for unsafe link targets. */
272
+ async function checkSiteLinks(ctx: QueryCtx, actor: Actor, input: Record<string, Json>) {
273
+ const schema = actor.site.schema as Schema
274
+ const only = typeof input.brick === 'string' ? input.brick : undefined
275
+ if (only !== undefined && !Object.hasOwn(schema.bricks, only)) fail('INVALID', 'errors.brickNotFoundSeeOverview', { only })
276
+ const bundles = await Promise.all(schema.locales.map((locale) => bundleOf(ctx, actor.site, locale)))
277
+ // The platform knows no files of the site's public folder, so a path that matches no entry or page is reported.
278
+ const issues = checkLinks(bundles, schema, { files: () => false })
279
+ const out = new Map<string, { entry: string | null; brick: string; label: string; field: string; link: string; reason: string; severity: string; locales: string[] }>()
280
+ const labels = new Map<string, { entry: string | null; label: string }>()
281
+ const entryOfIssue = async (brick: string, id: string | undefined) => {
282
+ const known = labels.get(`${brick}\n${id}`)
283
+ if (known) return known
284
+ // A single brick has no entry ID in the bundle: its one entry is the first of the brick.
285
+ const key = id ? ctx.db.normalizeId('entries', id) : null
286
+ const row = key ? await ctx.db.get(key) : await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', actor.site._id).eq('brick', brick)).first()
287
+ const value = { entry: row?._id ?? null, label: row ? labelOf(schema, brick, row.data as Data) : brick }
288
+ labels.set(`${brick}\n${id}`, value)
289
+ return value
290
+ }
291
+ const add = async (brick: string, id: string | undefined, field: string, link: string, reason: string, severity: string, locale: string) => {
292
+ const at = await entryOfIssue(brick, id)
293
+ const key = `${at.entry}\n${field}\n${link}\n${reason}`
294
+ const seen = out.get(key)
295
+ if (seen) { if (!seen.locales.includes(locale)) seen.locales.push(locale) } else out.set(key, { ...at, brick, field, link, reason, severity, locales: [locale] })
296
+ }
297
+ for (const issue of issues) await add(issue.brick, issue.id, issue.field, issue.href, issue.message, issue.severity, issue.locale)
298
+ for (const [key, def] of Object.entries(schema.bricks)) {
299
+ if (def.retired) continue
300
+ const rows = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', actor.site._id).eq('brick', key)).collect()
301
+ for (const row of rows) {
302
+ if (row.deletedAt) continue
303
+ for (const [name, field] of Object.entries(def.fields)) {
304
+ if (field.type !== 'markdown' || field.retired) continue
305
+ for (const markdown of searchTexts(field, (row.data as Data)[name])) {
306
+ for (const href of linksIn(markdown)) if (!isSafeHref(href)) await add(key, row._id, name, href, `Unsafe link: ${href.split(':')[0]}: is not allowed.`, 'error', schema.locales[0]!)
307
+ }
308
+ }
309
+ }
310
+ }
311
+ return [...out.values()].filter((i) => !only || i.brick === only)
312
+ }
313
+
314
+ /** The lookup tools of the door: one query, so the HTTP layer needs a single call. Each runs with the person's rights. */
315
+ export const lookup = internalQuery({
316
+ args: { key: v.id('agentKeys'), name: v.string(), args: v.record(v.string(), v.any()) },
317
+ handler: async (ctx, { key, name, args }): Promise<{ text: string; result: Json }> => {
318
+ const actor = await actorOrFail(ctx, key)
319
+ const input = args as Record<string, Json>
320
+ switch (name) {
321
+ case 'ginko_search': {
322
+ const hits = await searchEntries(ctx, actor, input)
323
+ return { text: hits.length ? `${hits.length} hits.` : 'Nothing found.', result: hits }
324
+ }
325
+ case 'ginko_version_at': {
326
+ const { task } = await revertTaskFor(ctx, actor, text(input.entry, 'entry'), text(input.change, 'change'))
327
+ const version = await versionAtAs(ctx, actor, { entry: text(input.entry, 'entry'), change: text(input.change, 'change'), task })
328
+ return { text: 'This is how the entry looked after that change.', result: { ...version, diff: version.diff as unknown as Json } }
329
+ }
330
+ case 'ginko_file_usage': {
331
+ const usage = await usageAs(ctx, actor, text(input.file, 'file'))
332
+ const used = usage.usedIn.map((u) => ({ entry: u.entry, brick: u.brick, label: u.title, paths: u.paths, missingAlt: u.missingAlt, ...(u.deleted ? { deleted: true } : {}) }))
333
+ return { text: used.length ? `The file “${usage.name}” is used in ${used.length} entries.` : `The file “${usage.name}” is not used anywhere.`, result: { file: usage.file, name: usage.name, usedIn: used } }
334
+ }
335
+ case 'ginko_check_links': {
336
+ const links = await checkSiteLinks(ctx, actor, input)
337
+ return { text: links.length ? `${links.length} link problems.` : 'No broken or unsafe links found.', result: links }
338
+ }
339
+ case 'ginko_schema': {
340
+ if (!isBuilder(actor)) break
341
+ const bricks = schemaOf(actor, input.brick)
342
+ return { text: `The fields of ${bricks.length === 1 ? `“${bricks[0]!.brick}”` : `${bricks.length} bricks`}, in the form ginko_write takes them.`, result: bricks as unknown as Json }
343
+ }
344
+ case 'ginko_proposals': {
345
+ const wanted = typeof input.status === 'string' ? input.status : undefined
346
+ if (wanted !== undefined && !PROPOSAL_STATUS.includes(wanted)) fail('INVALID', 'errors.unknownState', { wanted })
347
+ const rows = await ownAs(ctx, actor, wanted as Doc<'proposals'>['status'] | undefined)
348
+ const schema = actor.site.schema as Schema
349
+ const mine = rows.map((p) => ({
350
+ proposal: p.proposal, status: p.status, sentence: lineFor(p, schema), op: p.op, brick: p.brick, entry: p.entry, via: p.via,
351
+ createdAt: new Date(p.createdAt).toISOString(), reason: p.reason, change: p.change,
352
+ }))
353
+ const waiting = mine.filter((p) => p.status === 'open' || p.status === 'scheduled').length
354
+ return { text: waiting ? `${waiting} proposals wait for approval.` : 'Nothing waits for approval.', result: mine }
355
+ }
356
+ }
357
+ fail('FORBIDDEN', 'errors.toolNotFoundOrNotYours', { name })
358
+ },
359
+ })
360
+
361
+ /**
362
+ * ginko_read in another language: the outdated translations per entry, which the bundle delivers as they are (D6).
363
+ * Only the entries the bundle holds: not removed, not drafts, not left out of this language.
364
+ */
365
+ export const stale = internalQuery({
366
+ args: { key: v.id('agentKeys'), brick: v.string(), locale: v.string() },
367
+ handler: async (ctx, { key, brick, locale }): Promise<Record<string, string[]>> => {
368
+ const actor = await actorOrFail(ctx, key)
369
+ const schema = actor.site.schema as Schema
370
+ const out: Record<string, string[]> = {}
371
+ if (!Object.hasOwn(schema.bricks, brick)) return out
372
+ const rows = await ctx.db.query('entries').withIndex('by_site_brick_deleted', (q) => q.eq('site', actor.site._id).eq('brick', brick).eq('deletedAt', undefined)).collect()
373
+ for (const row of rows) {
374
+ if (row.state === 'draft') continue
375
+ const status = leafStatus(schema, brick, row, locale)
376
+ if (status.page !== 'hidden' && status.outdated.length) out[row._id] = status.outdated
377
+ }
378
+ return out
379
+ },
380
+ })
381
+
382
+ /** When a write shows on the website: in about a minute, or from the day of a week planned ahead or a planned price (`liveFrom`). */
383
+ const liveText = (liveFrom: string | undefined) => (liveFrom ? `On the website from ${liveFrom}.` : 'Live on the website in about a minute.')
384
+
385
+ /** The sentence for the person after a save-like write: proposed, unchanged, or done with the change to undo. */
386
+ function savedAs(result: Json, label: string): { text: string; result: Json } {
387
+ if (proposed(result)) return { text: PROPOSED, result }
388
+ const { change, liveFrom, pending } = result as { change?: string; liveFrom?: string; pending?: boolean }
389
+ // A save of a published entry waits as unpublished changes unless `publish` (lib/pending.ts).
390
+ if (pending !== undefined) {
391
+ return {
392
+ text: pending ? `Saved: ${label}. Not on the website yet: the change waits as an unpublished change until the person publishes it in the platform.` : `Saved: ${label}. It matches the published version again, so nothing waits to be published.`,
393
+ result,
394
+ }
395
+ }
396
+ return {
397
+ text: change ? `Done: ${label}. ${liveText(liveFrom)} To undo: ginko_undo with change ${change}.` : 'Nothing changed: the values were already like this.',
398
+ result,
399
+ }
400
+ }
401
+
402
+ /** The tool arguments as an object of the allowed shape; anything else is the assistant's mistake. */
403
+ function objectArg(value: Json | undefined, what: string): Record<string, Json> {
404
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) fail('INVALID', 'errors.fieldNotObject', { what })
405
+ return value
406
+ }
407
+
408
+ /**
409
+ * tools/call for every tool that writes. Returns the operation's result and a sentence for the person.
410
+ * JSON-RPC ids restart with every client session, so they cannot identify a retry; the assistant's own `request_id`
411
+ * can. With one, the whole call is an op `mcp-<request_id>`: the same call again returns the first answer and writes
412
+ * nothing, other arguments are OP_REUSED. The operation inside always gets a new op id, as without one.
413
+ */
414
+ export const call = internalMutation({
415
+ args: { key: v.id('agentKeys'), name: v.string(), args: v.record(v.string(), v.any()) },
416
+ handler: async (ctx, { key, name, args }): Promise<{ text: string; result: Json }> => {
417
+ const person = await actorOrFail(ctx, key)
418
+ const { request_id: requestId, ...rest } = args as Record<string, Json>
419
+ if (requestId === undefined) return callOnce(ctx, person, name, rest)
420
+ if (typeof requestId !== 'string') fail('INVALID', 'errors.actionIdInvalid')
421
+ // The op hash covers the tool and its arguments, so a retry with other input is OP_REUSED.
422
+ const op = { opId: `mcp-${requestId}`, name, args: rest }
423
+ return idempotent(ctx, person, op, () => callOnce(ctx, person, name, rest))
424
+ },
425
+ })
426
+
427
+ /** One tools/call that writes. `propose: true` makes it a proposal through the policy (`forceProposal`), never a second write path. */
428
+ async function callOnce(ctx: MutationCtx, person: Actor, name: string, args: Record<string, Json>): Promise<{ text: string; result: Json }> {
429
+ const { propose: ask, ...input } = args
430
+ if (ask !== undefined && typeof ask !== 'boolean') fail('INVALID', 'errors.proposeTrueFalse')
431
+ const actor: Actor = ask === true ? { ...person, forceProposal: true } : person
432
+ const opId = crypto.randomUUID()
433
+
434
+ if (name === 'ginko_undo') return undoThroughDoor(ctx, person, input.change, opId)
435
+ if (BUILDER_TOOLS.has(name)) {
436
+ if (!isBuilder(person)) fail('FORBIDDEN', 'errors.toolNotFoundOrNotYours', { name })
437
+ if (name === 'ginko_write') return writeThroughDoor(ctx, actor, input, opId)
438
+ if (name === 'ginko_create') return createThroughDoor(ctx, actor, input, opId)
439
+ // A batch has no `propose`: with review on, every item becomes a proposal of its own anyway.
440
+ if (name === 'ginko_import' && ask === undefined) return importThroughDoor(ctx, person, input, opId)
441
+ fail('INVALID', 'errors.unknownOption', { unknown: name === 'ginko_import' ? 'propose' : name })
442
+ }
443
+ if (name === 'ginko_revert' || name === 'ginko_translate' || name === 'ginko_draft') {
444
+ if (!fixedTools(person).some((t) => t.name === name)) fail('FORBIDDEN', 'errors.toolNotFoundOrNotYours', { name })
445
+ if (name === 'ginko_revert') return revertThroughDoor(ctx, actor, input, opId)
446
+ return name === 'ginko_translate' ? translateThroughDoor(ctx, actor, input, opId) : draftThroughDoor(ctx, actor, input, opId)
447
+ }
448
+ return taskThroughDoor(ctx, actor, name, input, opId)
449
+ }
450
+
451
+ async function taskThroughDoor(ctx: MutationCtx, actor: Actor, name: string, input: Record<string, Json>, opId: string): Promise<{ text: string; result: Json }> {
452
+ const schema = actor.site.schema as Schema
453
+ const site = actor.site.slug
454
+ const tool = taskTools(actor).find((t) => t.name === name)
455
+ if (!tool) fail('FORBIDDEN', 'errors.toolNotFoundOrNotYours', { name })
456
+ const brick = schema.bricks[tool.brick]!
457
+ const offered = await inputSchemaOf(ctx, actor, tool)
458
+ const unknown = Object.keys(input).filter((k) => !Object.hasOwn(offered.properties, k) && !(k === 'publish' && tool.task.kind !== 'remove'))
459
+ if (unknown.length) fail('INVALID', 'errors.unknownOption', { unknown: unknown.join(', ') })
460
+ const { entry: picked, confirm, publish: rawPublish, ...values } = input
461
+ const publish = publishArg(rawPublish)
462
+ const main = schema.locales[0]!
463
+ // Prefilled values count when the assistant leaves a field out: the tool offers them as defaults.
464
+ if (tool.task.kind === 'create') {
465
+ const data = { ...await prefillOf(ctx, actor, tool), ...fromToolInput(brick.fields, values, { mainLocale: main, currency: schema.currency, newRowId }) }
466
+ const result = await createAs(ctx, actor, { site, opId, task: tool.ref, brick: tool.brick, data, ...(publish ? { publish: {} } : {}) })
467
+ if (proposed(result)) return { text: PROPOSED, result }
468
+ const { entry: id, state, liveFrom } = result as { entry: Id<'entries'>; state: 'draft' | 'live'; liveFrom?: string }
469
+ // Without `publish` the new entry is a draft (SPEC 15); publishing it stays with the person in the platform.
470
+ const where = state === 'draft' ? 'Saved as a draft, not on the website yet. The person publishes it in the platform.' : liveText(liveFrom)
471
+ const change = await lastChangeOf(ctx, id)
472
+ return notingCopies(ctx, actor, brick.fields, values, { text: `Done: ${labelIn(tool.task.label, main, main)}. New entry ${id}. ${where} To undo: ginko_undo with change ${change?._id}.`, result: { ...(result as object), change: change?._id ?? null } })
473
+ }
474
+
475
+ const entry = await targetOf(ctx, actor, tool.brick, picked)
476
+ if (tool.task.kind === 'remove') {
477
+ if (confirm !== true) fail('INVALID', 'errors.removeNeedsConfirm')
478
+ const result = await removeAs(ctx, actor, { site, opId, task: tool.ref, entry: entry._id, lifeRev: entry.lifeRev })
479
+ if (proposed(result)) return { text: PROPOSED, result }
480
+ // The same warning as the platform's remove dialog: entries that point at it show without it now.
481
+ const uses = await usesOfEntry(ctx, actor, entry)
482
+ const note = uses.length ? ` Note: ${uses.length} ${uses.length === 1 ? 'entry pointed' : 'entries pointed'} at it (${uses.map((u) => `“${u.title}”`).join(', ')}); they now show without it until it is restored.` : ''
483
+ return { text: `Removed. The person can restore it in the platform for 30 days.${note}`, result }
484
+ }
485
+
486
+ const taskFields = tool.task.fields
487
+ const stored = entry.data as Record<string, Json>
488
+ // The task opens on the entry as the Studio's sheet does: its presets resolved on the entry (`prefill`, so a closure
489
+ // day already set stays), and a planned change whose day has come is the value in effect with its spent plan cleared
490
+ // (`opened`, from `prefillAs`), so a new value does not hide behind it.
491
+ const prefill = await prefillOf(ctx, actor, tool, entry._id)
492
+ const opened = await prefillAs(ctx, actor, { site, task: tool.ref, entry: entry._id }) as Record<string, Json>
493
+ const fields = {
494
+ ...Object.fromEntries(Object.entries(opened).filter(([k, value]) => taskFields.includes(k) && (Object.hasOwn(prefill, k) || !same(value, stored[k])))),
495
+ ...fromToolInput(Object.fromEntries(taskFields.map((f) => [f, brick.fields[f]!])), values, { mainLocale: main, currency: schema.currency, stored, newRowId }),
496
+ }
497
+ if (!Object.keys(fields).length) fail('INVALID', 'errors.nothingToChange')
498
+ // The assistant acts on the state it just read, so the current revision is its base.
499
+ return notingCopies(ctx, actor, brick.fields, values, savedAs(await saveAs(ctx, actor, { site, opId, task: tool.ref, entry: entry._id, baseRev: entry.rev, fields, locale: main, ...(publish ? { publish: true as const } : {}) }), labelIn(tool.task.label, main, main)))
500
+ }
501
+
502
+ /** `publish` of a write tool: absent or a boolean. */
503
+ function publishArg(value: Json | undefined): boolean {
504
+ if (value !== undefined && typeof value !== 'boolean') fail('INVALID', 'errors.unknownOption', { unknown: 'publish' })
505
+ return value === true
506
+ }
507
+
508
+ /** ginko_import collects the copies of all its items here and reads the facts once. */
509
+ interface CopyBatch { copies: FactCopyFound[]; facts: () => Promise<StudioFact[]> }
510
+
511
+ /**
512
+ * `done` with a note when the Markdown it wrote copies fact values (facts.ts), so the assistant quotes the facts instead.
513
+ * With `batch` (ginko_import), the copies go there and the import names them once for all items.
514
+ */
515
+ async function notingCopies(ctx: MutationCtx, actor: Actor, fields: Fields, values: Record<string, Json>, done: { text: string; result: Json }, batch?: CopyBatch): Promise<{ text: string; result: Json }> {
516
+ const found = await factCopiesIn(ctx, actor.site, fields, values, batch?.facts)
517
+ if (batch) {
518
+ batch.copies.push(...found)
519
+ return done
520
+ }
521
+ const note = factCopyNote(found)
522
+ return note ? { ...done, text: `${done.text} ${note}` } : done
523
+ }
524
+
525
+ /** ginko_translate: foreign-language texts through the normal save with `locale`; only whole texts of translatable fields. */
526
+ async function translateThroughDoor(ctx: MutationCtx, actor: Actor, input: Record<string, Json>, opId: string): Promise<{ text: string; result: Json }> {
527
+ const schema = actor.site.schema as Schema
528
+ const main = schema.locales[0]!
529
+ const asked = input.locale
530
+ const locale = schema.locales.find((l) => l === asked)
531
+ if (!locale) fail('INVALID', 'errors.languageNotSetUpAvailable', { asked: String(asked), locales: schema.locales.slice(1).join(', ') })
532
+ if (locale === main) fail('INVALID', 'errors.mainLanguageChangeViaTasks', { main })
533
+ const unknown = Object.keys(input).filter((k) => !['entry', 'locale', 'fields', 'confirm', 'publish'].includes(k))
534
+ if (unknown.length) fail('INVALID', 'errors.unknownOption', { unknown: unknown.join(', ') })
535
+ if (typeof input.entry !== 'string') fail('INVALID', 'errors.entryIdMissing')
536
+ const entry = await entryOf(ctx, actor, input.entry)
537
+ const brick = schema.bricks[entry.brick]
538
+ if (!brick) fail('INVALID', 'errors.brickNoLongerEditable')
539
+ const values = input.fields === undefined ? {} : objectArg(input.fields, 'fields')
540
+ const confirm = input.confirm === undefined ? [] : input.confirm
541
+ if (!Array.isArray(confirm) || confirm.some((c) => typeof c !== 'string')) fail('INVALID', 'errors.confirmMustBeFieldList')
542
+ for (const key of [...Object.keys(values), ...confirm as string[]]) {
543
+ const field = Object.hasOwn(brick.fields, key) ? brick.fields[key] : undefined
544
+ if (!field || field.retired || !isTranslatable(field) || field.type === 'slug') fail('INVALID', 'errors.fieldNotTranslatable', { key }, { field: key })
545
+ }
546
+ if (!Object.keys(values).length && !confirm.length) fail('INVALID', 'errors.nothingToTranslate')
547
+ for (const [key, value] of Object.entries(values)) if (value !== null && typeof value !== 'string') fail('INVALID', 'errors.fieldNeedsText', { key }, { field: key })
548
+ // The text is stored under the target language; `locale` keeps every other language as it is.
549
+ const fields = fromToolInput(brick.fields, values, { mainLocale: locale, currency: schema.currency, stored: entry.data as Record<string, Json>, newRowId })
550
+ const roots = [...new Set([...Object.keys(fields), ...confirm as string[]])]
551
+ const label = `Translation (${locale}): ${roots.map((k) => labelIn(brick.fields[k]!.label, main, main)).join(', ')}`
552
+ const result = await saveAs(ctx, actor, {
553
+ site: actor.site.slug, opId, task: taskFor(actor, entry.brick, 'edit', roots, entry), entry: entry._id, baseRev: entry.rev, fields, locale,
554
+ ...(confirm.length ? { confirm: confirm as string[] } : {}), sentence: label, ...(publishArg(input.publish) ? { publish: true as const } : {}),
555
+ })
556
+ return savedAs(result, label)
557
+ }
558
+
559
+ /** ginko_draft: a new draft in a collection; never live (the create is a draft, so no review applies). */
560
+ async function draftThroughDoor(ctx: MutationCtx, actor: Actor, input: Record<string, Json>, opId: string): Promise<{ text: string; result: Json }> {
561
+ const schema = actor.site.schema as Schema
562
+ const brickKey = input.brick
563
+ if (typeof brickKey !== 'string' || !draftBricks(actor).includes(brickKey)) fail('INVALID', 'errors.brickHasNoDrafts', { brick: String(brickKey) })
564
+ const brick = schema.bricks[brickKey]!
565
+ const values = objectArg(input.fields, 'fields')
566
+ const unknown = Object.keys(values).filter((k) => !Object.hasOwn(brick.fields, k) || brick.fields[k]!.retired || brick.fields[k]!.type === 'slug')
567
+ if (unknown.length) fail('INVALID', 'errors.unknownOption', { unknown: unknown.join(', ') })
568
+ const data = fromToolInput(brick.fields, values, { mainLocale: schema.locales[0]!, currency: schema.currency, newRowId })
569
+ const result = await createAs(ctx, actor, { site: actor.site.slug, opId, task: taskFor(actor, brickKey, 'create'), brick: brickKey, data })
570
+ const { entry: id } = result as { entry: Id<'entries'> }
571
+ const change = await lastChangeOf(ctx, id)
572
+ return {
573
+ text: `Saved as a draft, not on the website yet. New entry ${id}. The person publishes it in the platform. To undo: ginko_undo with change ${change?._id}.`,
574
+ result: { ...(result as object), change: change?._id ?? null },
575
+ }
576
+ }
577
+
578
+ /**
579
+ * The task a revert of this change goes through: none for owners and admins (a full revert), else the staff task. The fields a later change touched are the ones a revert can write: a
580
+ * staff task must cover them. `ginko_version_at` and `ginko_revert` both ask here, so the preview shows what the save writes.
581
+ */
582
+ async function revertTaskFor(ctx: QueryCtx, actor: Actor, entryId: string, changeId: string) {
583
+ const entry = await entryOf(ctx, actor, entryId)
584
+ // Owners and admins revert in full, with no task, as the Studio does for managers (ChangeRows.vue).
585
+ if (actor.role !== 'staff') return { entry, task: undefined }
586
+ const { fields } = await versionAtAs(ctx, actor, { entry: entryId, change: changeId })
587
+ return { entry, task: taskFor(actor, entry.brick, 'edit', fields, entry) }
588
+ }
589
+
590
+ /** ginko_revert: `entries.revert` (a normal save, so rights, review and undo apply). */
591
+ async function revertThroughDoor(ctx: MutationCtx, actor: Actor, input: Record<string, Json>, opId: string): Promise<{ text: string; result: Json }> {
592
+ if (typeof input.entry !== 'string' || typeof input.change !== 'string') fail('INVALID', 'errors.entryAndChangeIdRequired')
593
+ const { entry, task } = await revertTaskFor(ctx, actor, input.entry, input.change)
594
+ const result = await revertAs(ctx, actor, { site: actor.site.slug, opId, task, entry: entry._id, change: input.change })
595
+ return savedAs(result, 'Back to the earlier state')
596
+ }
597
+
598
+ async function undoThroughDoor(ctx: MutationCtx, actor: Actor, raw: Json | undefined, opId: string): Promise<{ text: string; result: Json }> {
599
+ const id = typeof raw === 'string' ? ctx.db.normalizeId('changes', raw) : null
600
+ const change = id ? await ctx.db.get(id) : null
601
+ if (!change || change.site !== actor.site._id) fail('NOT_FOUND', 'errors.changeNotFound')
602
+ const site = actor.site.slug
603
+ // A new entry is taken back by removing it, as the platform's undo button does (SPEC 4.2).
604
+ if (change.kind === 'create' && change.entry) {
605
+ const entry = await entryOf(ctx, actor, change.entry)
606
+ if (entry.deletedAt || entry.rev !== change.entryRev) fail('CHANGED_SINCE', 'errors.entryChangedMeanwhileNoUndo')
607
+ const result = await removeAs(ctx, actor, { site, opId, task: taskFor(actor, change.brick, 'remove'), entry: entry._id, lifeRev: entry.lifeRev })
608
+ if (proposed(result)) return { text: PROPOSED, result }
609
+ // The creation counts as undone, so history no longer offers it.
610
+ const removal = await lastChangeOf(ctx, entry._id)
611
+ if (removal) await ctx.db.patch(change._id, { undoneBy: removal._id })
612
+ return { text: 'Undone: the entry is removed.', result }
613
+ }
614
+ const entry = change.entry ? await ctx.db.get(change.entry) : null
615
+ const result = await undoAs(ctx, actor, { site, opId, task: taskFor(actor, change.brick, 'edit', change.fields ?? [], entry), change: change._id })
616
+ return { text: `Undone: ${lineFor(change, actor.site.schema as Schema)}.`, result }
617
+ }
618
+
619
+ // ---- Builder tools (owners and admins): the schema, any field, new entries, batches. ----
620
+
621
+ /** Where the person opens an entry (or a single brick) in the Studio; undefined when the platform address is not set. */
622
+ function studioLink(actor: Actor, brick: string, entry?: string): string | undefined {
623
+ const base = process.env.SITE_URL?.replace(/\/$/, '')
624
+ return base ? `${base}/s/${actor.site.slug}/all/${brick}${entry ? `/${entry}` : ''}` : undefined
625
+ }
626
+
627
+ /** A live brick by key, or an error that names the closest key. */
628
+ function brickOf(actor: Actor, raw: Json | undefined): { key: string; def: Schema['bricks'][string] } {
629
+ const schema = actor.site.schema as Schema
630
+ const main = schema.locales[0]!
631
+ if (typeof raw === 'string' && Object.hasOwn(schema.bricks, raw) && !schema.bricks[raw]!.retired) return { key: raw, def: schema.bricks[raw]! }
632
+ const live = Object.entries(schema.bricks).filter(([, b]) => !b.retired).map(([key, b]) => ({ key, label: labelIn(b.label, main, main) }))
633
+ const near = suggest(String(raw ?? ''), live)
634
+ if (near.length) fail('INVALID', 'errors.unknownBrickDidYouMean', { brick: String(raw), suggestion: near.join(', ') })
635
+ fail('INVALID', 'errors.brickNotFoundSeeOverview', { only: String(raw) })
636
+ }
637
+
638
+ /**
639
+ * Every name in `values` must be a live, writable field, also inside the rows of a list; else the error names the
640
+ * closest one. Without this check `fromToolInput` drops an unknown name and the save reports success for nothing.
641
+ */
642
+ function checkFields(actor: Actor, key: string, def: Schema['bricks'][string], values: Record<string, Json>) {
643
+ const main = (actor.site.schema as Schema).locales[0]!
644
+ const check = (fields: Schema['bricks'][string]['fields'], given: Record<string, Json>, at: string) => {
645
+ const writable = Object.entries(fields).filter(([, f]) => !f.retired && f.type !== 'slug')
646
+ for (const [name, value] of Object.entries(given)) {
647
+ const field = writable.find(([k]) => k === name)?.[1]
648
+ const path = `${at}${name}`
649
+ if (field) {
650
+ if (field.type === 'list' && Array.isArray(value)) value.forEach((row, i) => { if (typeof row === 'object' && row !== null && !Array.isArray(row)) check(field.of, row, `${path}[${i}].`) })
651
+ continue
652
+ }
653
+ const near = suggest(name, writable.map(([k, f]) => ({ key: k, label: labelIn(f.label, main, main) })))
654
+ if (near.length) fail('INVALID', 'errors.unknownFieldDidYouMean', { field: path, brick: key, suggestion: near.join(', ') }, { field: path })
655
+ fail('INVALID', 'errors.unknownField', { field: path, brick: key }, { field: path })
656
+ }
657
+ }
658
+ check(def.fields, values, '')
659
+ }
660
+
661
+ function onlyKeys(input: Record<string, Json>, allowed: readonly string[]) {
662
+ const unknown = Object.keys(input).filter((k) => !allowed.includes(k))
663
+ if (unknown.length) fail('INVALID', 'errors.unknownOption', { unknown: unknown.join(', ') })
664
+ }
665
+
666
+ /** ginko_schema: the bricks with their fields as JSON Schema in the form the builder tools take. */
667
+ function schemaOf(actor: Actor, only: Json | undefined) {
668
+ const schema = actor.site.schema as Schema
669
+ const main = schema.locales[0]!
670
+ const keys = only === undefined ? Object.keys(schema.bricks).filter((k) => !schema.bricks[k]!.retired) : [brickOf(actor, only).key]
671
+ return keys.map((key) => {
672
+ const def = schema.bricks[key]!
673
+ return {
674
+ brick: key, kind: def.kind, label: labelIn(def.label, main, main),
675
+ ...(def.kind === 'collection' && def.route ? { route: def.route } : {}),
676
+ input: fieldsInputSchema(def.fields, { mainLocale: main, currency: schema.currency }),
677
+ }
678
+ })
679
+ }
680
+
681
+ /** ginko_write: any fields of an entry or single, in the main language, as the Studio saves them (no task). */
682
+ async function writeThroughDoor(ctx: MutationCtx, actor: Actor, input: Record<string, Json>, opId: string, batch?: CopyBatch): Promise<{ text: string; result: Json }> {
683
+ onlyKeys(input, ['brick', 'entry', 'fields', 'publish'])
684
+ const schema = actor.site.schema as Schema
685
+ const main = schema.locales[0]!
686
+ const { key, def } = brickOf(actor, input.brick)
687
+ const values = objectArg(input.fields, 'fields')
688
+ checkFields(actor, key, def, values)
689
+ const entry = await targetOf(ctx, actor, key, input.entry)
690
+ const fields = fromToolInput(def.fields, values, { mainLocale: main, currency: schema.currency, stored: entry.data as Record<string, Json>, newRowId })
691
+ if (!Object.keys(fields).length) fail('INVALID', 'errors.nothingToChange')
692
+ const result = await saveAs(ctx, actor, { site: actor.site.slug, opId, entry: entry._id, baseRev: entry.rev, fields, locale: main, ...(publishArg(input.publish) ? { publish: true as const } : {}) })
693
+ const studio = studioLink(actor, key, def.kind === 'single' ? undefined : entry._id)
694
+ const saved = savedAs(result, `${labelOf(schema, key, entry.data as Data)}: ${Object.keys(fields).join(', ')}`)
695
+ return notingCopies(ctx, actor, def.fields, values, { text: saved.text, result: { ...(result as object), entry: entry._id, ...(studio ? { studio } : {}) } }, batch)
696
+ }
697
+
698
+ /** ginko_create: a new entry of a collection with any fields (no task). A draft unless `publish`. */
699
+ async function createThroughDoor(ctx: MutationCtx, actor: Actor, input: Record<string, Json>, opId: string, batch?: CopyBatch): Promise<{ text: string; result: Json }> {
700
+ onlyKeys(input, ['brick', 'fields', 'publish'])
701
+ const schema = actor.site.schema as Schema
702
+ const { key, def } = brickOf(actor, input.brick)
703
+ if (def.kind !== 'collection') fail('INVALID', 'errors.createNeedsCollection', { brick: key })
704
+ const values = objectArg(input.fields, 'fields')
705
+ checkFields(actor, key, def, values)
706
+ const data = fromToolInput(def.fields, values, { mainLocale: schema.locales[0]!, currency: schema.currency, newRowId })
707
+ const result = await createAs(ctx, actor, { site: actor.site.slug, opId, brick: key, data, ...(publishArg(input.publish) ? { publish: {} } : {}) })
708
+ if (proposed(result)) return notingCopies(ctx, actor, def.fields, values, { text: PROPOSED, result }, batch)
709
+ const { entry: id, state, liveFrom } = result as { entry: Id<'entries'>; state: 'draft' | 'live'; liveFrom?: string }
710
+ const change = await lastChangeOf(ctx, id)
711
+ const studio = studioLink(actor, key, id)
712
+ const where = state === 'draft' ? 'Saved as a draft, not on the website yet.' : liveText(liveFrom)
713
+ return notingCopies(ctx, actor, def.fields, values, {
714
+ text: `Created entry ${id} in “${key}”. ${where} To undo: ginko_undo with change ${change?._id}.`,
715
+ result: { ...(result as object), change: change?._id ?? null, ...(studio ? { studio } : {}) },
716
+ }, batch)
717
+ }
718
+
719
+ /**
720
+ * ginko_import: up to IMPORT_MAX writes and creates in this one mutation, so they are saved together or not at all. A
721
+ * failing item names itself (`at`). A dry run runs every item through the real save and then throws DRY_RUN, which
722
+ * rolls the transaction back: the check is exactly the save, not a copy of its rules.
723
+ */
724
+ async function importThroughDoor(ctx: MutationCtx, actor: Actor, input: Record<string, Json>, opId: string): Promise<{ text: string; result: Json }> {
725
+ onlyKeys(input, ['items', 'dry_run'])
726
+ const items = input.items
727
+ if (!Array.isArray(items) || !items.length) fail('INVALID', 'errors.fieldMissing', { what: 'items' })
728
+ if (items.length > IMPORT_MAX) fail('INVALID', 'errors.importTooLarge', { max: IMPORT_MAX })
729
+ const schema = actor.site.schema as Schema
730
+ const results: Json[] = []
731
+ const copies: (FactCopyFound & { item: number })[] = []
732
+ let facts: Promise<StudioFact[]> | undefined
733
+ const batchFacts = () => (facts ??= factsOf(ctx, actor.site))
734
+ for (const [i, raw] of items.entries()) {
735
+ try {
736
+ const item = objectArg(raw, `items[${i}]`)
737
+ const { entry, publish, ...rest } = item
738
+ const writes = entry !== undefined || (typeof item.brick === 'string' && schema.bricks[item.brick]?.kind === 'single')
739
+ const batch: CopyBatch = { copies: [], facts: batchFacts }
740
+ const done = writes
741
+ ? await writeThroughDoor(ctx, actor, { ...rest, ...(entry === undefined ? {} : { entry }), ...(publish === undefined ? {} : { publish }) }, `${opId}-${i}`, batch)
742
+ : await createThroughDoor(ctx, actor, { ...rest, ...(publish === undefined ? {} : { publish }) }, `${opId}-${i}`, batch)
743
+ copies.push(...batch.copies.map((copy) => ({ ...copy, item: i })))
744
+ const r = done.result as Record<string, Json>
745
+ // A draft or an unpublished change is saved but not online (SPEC 15): the answer must not promise the website.
746
+ const waits = r.pending === true || r.state === 'draft'
747
+ results.push({ item: i, op: writes ? 'write' : 'create', ...(r.entry ? { entry: r.entry } : {}), ...(r.proposal ? { proposal: r.proposal } : {}), ...(waits ? { waits: true } : {}), ...(r.studio ? { studio: r.studio } : {}) })
748
+ } catch (error) {
749
+ // The item that failed names itself; Convex rolls back the items before it.
750
+ if (error instanceof ConvexError && typeof error.data === 'object' && error.data !== null) throw new ConvexError({ ...(error.data as Record<string, Json>), at: `items[${i}]` })
751
+ throw error
752
+ }
753
+ }
754
+ // The IDs of a dry run are rolled back with it, so its answer names only what each item would do.
755
+ const rows = results as { item: number; op: string; proposal?: string; waits?: true }[]
756
+ const note = factCopyNote(copies, (copy) => `items[${copy.item}]`)
757
+ if (input.dry_run === true) throw new ConvexError({ code: DRY_RUN, results: rows.map((r) => ({ item: r.item, op: r.op, ...(r.proposal ? { proposed: true } : {}) })), ...(note ? { note } : {}) })
758
+ return { text: [importText(rows), note].filter(Boolean).join(' '), result: results }
759
+ }
760
+
761
+ /** What ginko_import says: what is live now and what waits for approval (review on), never "saved" for a proposal. */
762
+ export function importText(rows: readonly { op: string; proposal?: string; waits?: true }[]): string {
763
+ const live = rows.filter((r) => !r.proposal && !r.waits)
764
+ const created = live.filter((r) => r.op === 'create').length
765
+ const waiting = rows.filter((r) => r.proposal).length
766
+ const unpublished = rows.filter((r) => r.waits).length
767
+ const saved = live.length ? `Saved ${live.length} items (${created} new, ${live.length - created} changed). Each one is in ginko_history and can be undone there.` : ''
768
+ const held = unpublished ? `${unpublished} items are saved but not on the website yet (new entries are drafts, changes wait unpublished); the person publishes them in the platform.` : ''
769
+ const proposals = waiting ? `${waiting} items became proposals that wait for approval; nothing of them is on the website yet (ginko_proposals lists them).` : ''
770
+ return [saved, held, proposals].filter(Boolean).join(' ')
771
+ }
772
+
773
+ /** ginko_upload with a URL: refuses anyone but a builder before the door fetches anything. */
774
+ export const mayUpload = internalQuery({
775
+ args: { key: v.id('agentKeys') },
776
+ handler: async (ctx, { key }): Promise<null> => {
777
+ if (!isBuilder(await actorOrFail(ctx, key))) fail('FORBIDDEN', 'errors.toolNotFoundOrNotYours', { name: 'ginko_upload' })
778
+ return null
779
+ },
780
+ })
781
+
782
+ /** ginko_upload's first step: a one-time upload ticket for the key's person, for a library file. Builders only. */
783
+ export const uploadTicket = internalMutation({
784
+ args: { key: v.id('agentKeys') },
785
+ handler: async (ctx, { key }): Promise<{ ticket: string }> => {
786
+ const actor = await actorOrFail(ctx, key)
787
+ if (!isBuilder(actor)) fail('FORBIDDEN', 'errors.toolNotFoundOrNotYours', { name: 'ginko_upload' })
788
+ return { ticket: await ticketFor(ctx, actor, { library: true }) }
789
+ },
790
+ })
791
+
792
+ /**
793
+ * `pnpm local:dev` only: makes sure the local admin has a live key with this hash on the site, so the `.mcp.json` the
794
+ * CLI writes into the site folder works. The CLI keeps the key there and sends the same hash on every start. Not ready
795
+ * until the admin signed in once: the sign-in creates the user.
796
+ */
797
+ export const devKey = internalMutation({
798
+ args: { site: v.string(), email: v.string(), hash: v.string() },
799
+ handler: async (ctx, args): Promise<{ ok: true } | { ok: false; reason: 'site' | 'signin' | 'taken' }> => {
800
+ if (process.env.GINKO_LOCAL !== '1') fail('FORBIDDEN', 'errors.localOnly')
801
+ const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
802
+ if (!site) return { ok: false, reason: 'site' }
803
+ const user = await ctx.runQuery(components.betterAuth.adapter.findOne, { model: 'user', where: [{ field: 'email', value: normalizeEmail(args.email) }] })
804
+ const id = typeof user?.id === 'string' ? user.id : undefined
805
+ if (!id || !(await memberOf(ctx, site, { id }))) return { ok: false, reason: 'signin' }
806
+ const key = await ctx.db.query('agentKeys').withIndex('by_hash', (q) => q.eq('hash', args.hash)).unique()
807
+ if (!key) {
808
+ await ctx.db.insert('agentKeys', { site: site._id, user: id, hash: args.hash, label: 'local:dev', createdAt: Date.now() })
809
+ return { ok: true }
810
+ }
811
+ // A revoked key stays revoked, and a key of another site or person stays theirs: the CLI makes a new one.
812
+ return key.site === site._id && key.user === id && !key.revokedAt ? { ok: true } : { ok: false, reason: 'taken' }
813
+ },
814
+ })