@retainer/extension 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1010 @@
1
+ import { nextOccurrence } from './cron.js';
2
+ import { SYSTEM_LIFECYCLE_FUNCTION_ID } from './protocol.js';
3
+ import { parseServerRange, satisfiesServerRange } from './semver.js';
4
+ import { verifierHeaderAllowed } from './webhook.js';
5
+ export { nextOccurrence } from './cron.js';
6
+ export { compareVersions, newestReleases, parseServerRange, satisfiesServerRange, } from './semver.js';
7
+ import { agentToolGroupSchema, FIELD_TYPES, isInverseRelation } from '@retainer/shared';
8
+ import { z } from 'zod';
9
+ /** The icons a sidebar link may name; the web app draws each. */
10
+ export const SIDEBAR_ICONS = [
11
+ 'app',
12
+ 'calendar',
13
+ 'clock',
14
+ 'mail',
15
+ 'chart',
16
+ 'file',
17
+ 'users',
18
+ ];
19
+ /** The query parameter a sidebar link carries, naming the installation, for the app's sign-in. */
20
+ export const SIDEBAR_INSTALLATION_PARAM = 'retainer_installation';
21
+ /** Capabilities a function may declare in `uses`; open for later ones (model calls spec 11). */
22
+ export const EXTENSION_USES = ['model', 'agent'];
23
+ /**
24
+ * What approving `model` means, in plain words, wherever access is shown
25
+ * (model calls spec 3.1). One sentence for every release: the grant is model
26
+ * use, not a particular extent of it.
27
+ */
28
+ export const MODEL_USE_NOTICE = 'When this extension uses a model, it sends the workspace data involved to Anthropic for processing.';
29
+ /**
30
+ * What approving `agent` means (agent spec §9.4): the agent's tool groups in
31
+ * plain words, then the model notice, since what it reads goes to Anthropic.
32
+ */
33
+ export function agentUseNotice(tools) {
34
+ const can = [
35
+ tools.includes('retainer.read') ? 'read this workspace' : undefined,
36
+ tools.includes('retainer.write') ? 'write to it' : undefined,
37
+ tools.includes('web.search') ? 'search the web' : undefined,
38
+ tools.some((tool) => tool.startsWith('tools.'))
39
+ ? "call this workspace's read tools"
40
+ : undefined,
41
+ ].filter(Boolean);
42
+ const list = can.length > 1 ? `${can.slice(0, -1).join(', ')} and ${can.at(-1)}` : (can[0] ?? 'work');
43
+ return `Uses an agent that can ${list}.${tools.includes('web.search') ? ' Workspace data it reads can appear in its searches.' : ''} ${MODEL_USE_NOTICE}`;
44
+ }
45
+ export const TAMLOOT_REGISTRATION_ID = '54326882-cc28-4983-a5fe-cf0298520b68';
46
+ /**
47
+ * The installation setting that chooses what happens when the source deletes
48
+ * an item it imported; absent, the release's `onSourceDelete` applies.
49
+ */
50
+ export const SOURCE_DELETE_SETTING = 'onSourceDelete';
51
+ const sourceDeletePolicies = z.enum(['keep', 'retract']);
52
+ /** What happens to imported content when the source deletes it, for these installation settings. */
53
+ export function sourceDeletePolicy(manifest, settings) {
54
+ const chosen = sourceDeletePolicies.safeParse(settings[SOURCE_DELETE_SETTING]);
55
+ return chosen.success && manifest.settings[SOURCE_DELETE_SETTING]?.options?.includes(chosen.data)
56
+ ? chosen.data
57
+ : manifest.onSourceDelete;
58
+ }
59
+ /**
60
+ * Plain words for the options of the policies the platform itself applies,
61
+ * wherever they are chosen or shown.
62
+ */
63
+ export const POLICY_OPTION_LABELS = {
64
+ createPeople: {
65
+ never: 'Never',
66
+ contacted_first: 'Only people you contacted first',
67
+ everyone: 'Everyone',
68
+ },
69
+ [SOURCE_DELETE_SETTING]: {
70
+ retract: 'Remove what was imported',
71
+ keep: 'Keep what was imported',
72
+ },
73
+ };
74
+ const uuid = z.uuid();
75
+ const name = z.string().regex(/^[a-z][a-zA-Z0-9-]{0,99}$/);
76
+ const label = z.string().min(1).max(200);
77
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
78
+ const version = z.string().regex(/^\d+\.\d+\.\d+$/);
79
+ const field = z.strictObject({
80
+ universalId: uuid,
81
+ name,
82
+ label,
83
+ type: z.enum(FIELD_TYPES),
84
+ /** What the field holds. Required; see `checkDescriptions`. */
85
+ description: z.string().max(2000).optional(),
86
+ isNullable: z.boolean().optional(),
87
+ isUnique: z.boolean().optional(),
88
+ isFilterable: z.boolean().optional(),
89
+ isSearchable: z.boolean().optional(),
90
+ settings: z
91
+ .strictObject({
92
+ options: z
93
+ .array(z.strictObject({ value: label, label }))
94
+ .max(200)
95
+ .optional(),
96
+ targetObject: uuid.optional(),
97
+ targetObjects: z.array(uuid).max(20).optional(),
98
+ relationCardinality: z.enum(['many_to_one', 'many_to_many']).optional(),
99
+ onDelete: z.enum(['set_null', 'cascade']).optional(),
100
+ rollUpEvents: z.boolean().optional(),
101
+ maxValues: z.number().int().min(1).max(100).optional(),
102
+ })
103
+ .optional(),
104
+ });
105
+ const object = z.strictObject({
106
+ universalId: uuid,
107
+ nameSingular: name,
108
+ namePlural: name,
109
+ labelSingular: label,
110
+ labelPlural: label,
111
+ class: z.enum(['entity', 'event']).optional(),
112
+ /** What the object's records are. Required; see `checkDescriptions`. */
113
+ description: z.string().max(2000).optional(),
114
+ labelField: name.optional(),
115
+ fields: z.array(field).max(200),
116
+ });
117
+ const inputSchema = z.lazy(() => z.strictObject({
118
+ type: z.enum(['object', 'string', 'number', 'integer', 'boolean', 'array', 'null']),
119
+ description: z.string().max(2000).optional(),
120
+ properties: z.record(name, inputSchema).optional(),
121
+ required: z.array(name).max(100).optional(),
122
+ additionalProperties: z.literal(false).optional(),
123
+ items: inputSchema.optional(),
124
+ maxLength: z.number().int().min(1).max(65536).optional(),
125
+ maxItems: z.number().int().min(1).max(1000).optional(),
126
+ }));
127
+ // `then` would make the routine SDK's tools object look like a promise.
128
+ const toolName = z
129
+ .string()
130
+ .regex(/^[a-z][a-z0-9_]{0,99}$/)
131
+ .refine((name) => name !== 'then', 'a tool cannot be named "then"');
132
+ const toolTrigger = z.strictObject({
133
+ kind: z.literal('tool'),
134
+ title: label,
135
+ effect: z.enum(['read', 'write', 'send']),
136
+ connection: z.enum(['workspace', 'member']),
137
+ outputSchema: inputSchema,
138
+ });
139
+ /** Server-provided input for a record button. */
140
+ export const recordButtonInputSchema = {
141
+ type: 'object',
142
+ additionalProperties: false,
143
+ properties: { recordId: { type: 'string', maxLength: 36 } },
144
+ required: ['recordId'],
145
+ };
146
+ export const bindingKeySchema = z.string().regex(/^[a-z][a-zA-Z0-9_]{0,39}$/);
147
+ const trigger = z.discriminatedUnion('kind', [
148
+ z.strictObject({ kind: z.literal('configure') }),
149
+ z.strictObject({ kind: z.literal('install') }),
150
+ z.strictObject({ kind: z.literal('uninstall') }),
151
+ z.strictObject({ kind: z.literal('connect') }),
152
+ z.strictObject({ kind: z.literal('disconnect') }),
153
+ z.strictObject({ kind: z.literal('job') }),
154
+ toolTrigger,
155
+ z.strictObject({ kind: z.literal('recordButton'), binding: bindingKeySchema, label }),
156
+ z.strictObject({ kind: z.literal('route'), route: name }),
157
+ z.strictObject({ kind: z.literal('serverRoute'), route: name }),
158
+ z.strictObject({
159
+ kind: z.literal('schedule'),
160
+ cron: z.string().min(9).max(100),
161
+ timezone: z.literal('UTC'),
162
+ }),
163
+ z.strictObject({
164
+ kind: z.literal('change'),
165
+ binding: bindingKeySchema,
166
+ fields: z.array(bindingKeySchema).max(200).optional(),
167
+ /**
168
+ * Whether a change to a related record (a link to or from it, or a merge
169
+ * into it) also fires the trigger. Absent means true, the first contract.
170
+ */
171
+ related: z.boolean().optional(),
172
+ /**
173
+ * Only these direct operations fire it. With `fields`, `update` still
174
+ * needs a watched field and `create` can fire. Absent means every
175
+ * operation, the first contract.
176
+ */
177
+ operations: z
178
+ .array(z.enum(['create', 'update']))
179
+ .min(1)
180
+ .max(2)
181
+ .optional(),
182
+ }),
183
+ ]);
184
+ const functionDefinition = z.strictObject({
185
+ universalId: uuid,
186
+ name: z.string(),
187
+ description: z.string().min(1).max(2000),
188
+ handlerDigest: digest,
189
+ trigger,
190
+ inputSchema,
191
+ timeoutSeconds: z.number().int().min(1).max(300).default(120),
192
+ /**
193
+ * The secret settings this function reads or writes. Its run receives only
194
+ * these. Absent (the first contract) means every secret setting, so
195
+ * already-built catalogs and their digests stay valid.
196
+ */
197
+ secrets: z.array(name).max(100).optional(),
198
+ /**
199
+ * The runtime scopes this function needs, a subset of the release's scopes.
200
+ * Its run token carries the intersection with the installed grant. Absent
201
+ * means the release's scopes.
202
+ */
203
+ scopes: z
204
+ .array(z.enum(['read', 'write']))
205
+ .min(1)
206
+ .max(2)
207
+ .optional(),
208
+ /**
209
+ * The function may write the release's mapped outputs through the fill-only
210
+ * mapped write. Reviewed with the release, like `secrets` and `scopes`.
211
+ */
212
+ mappedWrite: name.optional(),
213
+ /**
214
+ * Platform capabilities the function uses (model calls spec 3.1). Reviewed
215
+ * with the release and approved with its access; a run gets one only when
216
+ * its function declares it and the installation's grant includes it.
217
+ */
218
+ uses: z.array(z.enum(EXTENSION_USES)).min(1).optional(),
219
+ /**
220
+ * The workspace agent's tool groups for this function's tasks (agent spec
221
+ * §9.4), with `uses: ['agent']`. Reviewed and approved with the release.
222
+ */
223
+ agent: z.strictObject({ tools: z.array(agentToolGroupSchema).min(1).max(20) }).optional(),
224
+ });
225
+ export const functionSchema = functionDefinition
226
+ .refine((fn) => (fn.trigger.kind === 'tool' ? toolName : name).safeParse(fn.name).success, {
227
+ path: ['name'],
228
+ message: 'invalid name for function trigger',
229
+ })
230
+ .refine((fn) => !!fn.agent === !!fn.uses?.includes('agent'), {
231
+ path: ['agent'],
232
+ message: "a function that uses the agent lists its tools in agent.tools, with uses: ['agent']",
233
+ })
234
+ .refine((fn) => !fn.agent || fn.trigger.kind !== 'tool', {
235
+ path: ['agent'],
236
+ message: 'a tool cannot hand tasks to the agent',
237
+ });
238
+ const toolDefinition = functionDefinition
239
+ .omit({ trigger: true })
240
+ .extend({ ...toolTrigger.omit({ kind: true }).shape, name: toolName });
241
+ /** A field destination declared by an extension binding. */
242
+ const bindingFieldSchema = z.strictObject({
243
+ key: bindingKeySchema,
244
+ label,
245
+ /** What the extension writes or reads here. Required; see `checkDescriptions`. */
246
+ description: z.string().max(2000).optional(),
247
+ types: z.array(z.enum(FIELD_TYPES)).min(1).max(FIELD_TYPES.length),
248
+ required: z.boolean(),
249
+ lookup: z.literal(true).optional(),
250
+ owned: z.literal(true).optional(),
251
+ installationOwned: z.literal(true).optional(),
252
+ target: bindingKeySchema.optional(),
253
+ values: z.array(name).min(1).max(200).optional(),
254
+ create: field.optional(),
255
+ });
256
+ const bindingSchema = z.strictObject({
257
+ key: bindingKeySchema,
258
+ label,
259
+ description: z.string().min(1).max(2000),
260
+ class: z.enum(['entity', 'event']),
261
+ access: z.enum(['read', 'write']),
262
+ required: z.boolean(),
263
+ owned: z.literal(true).optional(),
264
+ match: bindingKeySchema.optional(),
265
+ /** This binding creates records, so all required schema fields must be supplied. */
266
+ creates: z.literal(true).optional(),
267
+ fields: z.array(bindingFieldSchema).max(200),
268
+ create: object.optional(),
269
+ });
270
+ /**
271
+ * Whether a field can hold a binding field's values: not an event type's core
272
+ * field, not the read-only side of a relation, and of a type the binding field
273
+ * takes. The server adds that the field is active; API clients, which see
274
+ * `readOnly`, add that it is writable. One rule for the server, the bundles
275
+ * that suggest bindings and the web form.
276
+ */
277
+ export function bindableField(field, rule) {
278
+ return !field.coreRole && !isInverseRelation(field) && rule.types.includes(field.type);
279
+ }
280
+ /** The longest reason a `configure` run may save for one suggestion (configure spec 2.2). */
281
+ export const SUGGESTION_REASON_MAX = 500;
282
+ const bindingValueSchema = z.union([name, z.strictObject({ value: name, label })]);
283
+ const bindingFieldChoice = z.discriminatedUnion('action', [
284
+ z.strictObject({ action: z.literal('skip') }),
285
+ z.strictObject({
286
+ action: z.literal('existing'),
287
+ field: name,
288
+ values: z.record(name, bindingValueSchema).optional(),
289
+ }),
290
+ z.strictObject({
291
+ action: z.literal('create'),
292
+ name: name.optional(),
293
+ values: z.record(name, bindingValueSchema).optional(),
294
+ }),
295
+ ]);
296
+ const bindingFields = z.record(bindingKeySchema, bindingFieldChoice).optional();
297
+ export const bindingChoicesSchema = z.record(bindingKeySchema, z.discriminatedUnion('action', [
298
+ z.strictObject({ action: z.literal('skip') }),
299
+ z.strictObject({
300
+ action: z.literal('existing'),
301
+ objects: z.array(name).min(1).max(20),
302
+ fields: bindingFields,
303
+ }),
304
+ z.strictObject({
305
+ action: z.literal('create'),
306
+ nameSingular: name.optional(),
307
+ namePlural: name.optional(),
308
+ labelSingular: label.optional(),
309
+ labelPlural: label.optional(),
310
+ fields: bindingFields,
311
+ }),
312
+ ]));
313
+ /** Later proposals take precedence, retaining suggestions for the same target. */
314
+ export function mergeBindingChoices(...proposals) {
315
+ const result = {};
316
+ for (const proposal of proposals) {
317
+ for (const [key, choice] of Object.entries(proposal ?? {})) {
318
+ const prior = result[key];
319
+ if (!prior ||
320
+ prior.action === 'skip' ||
321
+ choice.action === 'skip' ||
322
+ prior.action !== choice.action ||
323
+ (prior.action === 'existing' &&
324
+ choice.action === 'existing' &&
325
+ (prior.objects.length !== choice.objects.length ||
326
+ !prior.objects.every((object, index) => object === choice.objects[index])))) {
327
+ result[key] = choice;
328
+ continue;
329
+ }
330
+ const fields = { ...prior.fields };
331
+ for (const [fieldKey, field] of Object.entries(choice.fields ?? {})) {
332
+ const previous = fields[fieldKey];
333
+ fields[fieldKey] =
334
+ (previous?.action === 'existing' &&
335
+ field.action === 'existing' &&
336
+ previous.field === field.field) ||
337
+ (previous?.action === 'create' &&
338
+ field.action === 'create' &&
339
+ previous.name === field.name)
340
+ ? { ...field, values: { ...previous.values, ...field.values } }
341
+ : field;
342
+ }
343
+ result[key] = { ...prior, ...choice, fields };
344
+ }
345
+ }
346
+ return result;
347
+ }
348
+ export const bindingWriteStampSchema = z.strictObject({
349
+ bindings_revision: z.number().int().positive(),
350
+ objectId: uuid,
351
+ fieldIds: z.record(z.string().min(1).max(100), uuid),
352
+ });
353
+ const viewDefinition = z.strictObject({ universalId: uuid, name: label, kind: z.literal('table') });
354
+ export const viewSchema = viewDefinition.extend({
355
+ binding: bindingKeySchema,
356
+ fields: z.array(bindingKeySchema).max(200),
357
+ });
358
+ const manifestSchema = z.strictObject({
359
+ manifestVersion: z.literal(1),
360
+ universalId: uuid,
361
+ name,
362
+ version,
363
+ description: z.string().min(1).max(2000),
364
+ packageDigest: digest,
365
+ /**
366
+ * The reviewed servers this release supports, as a bounded semver range
367
+ * (`semver.ts`), e.g. `>=0.1.0 <0.2.0`. A server patch inside the range needs
368
+ * no new release.
369
+ */
370
+ serverRange: z.string().max(200).optional(),
371
+ /**
372
+ * The first contract's exact list. Still accepted, as an exact set, so
373
+ * already-built catalogs and their digests stay valid. Give one or the other.
374
+ */
375
+ serverVersions: z.array(version).min(1).max(100).optional(),
376
+ runtimeVersion: z.literal('node24'),
377
+ execution: z.enum(['hosted', 'standalone']),
378
+ /** Reviewed first-party OAuth client identity, pinned into the release digest. */
379
+ oauthClientId: z.string().min(1).max(2048).regex(/^\S+$/).optional(),
380
+ /**
381
+ * A link in Retainer's sidebar for members of workspaces where the
382
+ * installation is active (spec 8). The path is on the app's origin, the
383
+ * origin of its client's registered redirect; opening it signs the person
384
+ * in to the app through Retainer.
385
+ */
386
+ sidebarLink: z
387
+ .strictObject({
388
+ label: z.string().min(1).max(40),
389
+ icon: z.enum(SIDEBAR_ICONS),
390
+ // An absolute path with no query or fragment: Retainer adds the query.
391
+ path: z
392
+ .string()
393
+ .max(500)
394
+ .regex(/^\/(?![/\\])[A-Za-z0-9\-._~/%!$&'()*+,;=:@]*$/),
395
+ })
396
+ .optional(),
397
+ protocolVersion: z.literal(1),
398
+ requestedActor: z.enum(['integration', 'agent']),
399
+ scopes: z
400
+ .array(z.enum(['read', 'write']))
401
+ .min(1)
402
+ .max(2),
403
+ connection: z.enum(['workspace', 'member']),
404
+ createPeople: z.enum(['never', 'contacted_first', 'everyone']),
405
+ onSourceDelete: sourceDeletePolicies,
406
+ /** Narrow server-computed derivation; only these functions may replace their own derived claims. */
407
+ lastContact: z
408
+ .strictObject({
409
+ functionIds: z.array(uuid).min(1).max(20),
410
+ events: bindingKeySchema,
411
+ destinations: z.array(bindingKeySchema).min(1).max(20),
412
+ })
413
+ .optional(),
414
+ /** Reviewed, release-pinned ingestion authority; provider code attests only through setup. */
415
+ source: z
416
+ .strictObject({
417
+ provider: name,
418
+ identity: z.enum(['account', 'global-resource']),
419
+ verifyFunctionId: uuid,
420
+ syncFunctionIds: z.array(uuid).min(1).max(20),
421
+ scanFunctionIds: z.array(uuid).min(1).max(20).optional(),
422
+ event: bindingKeySchema,
423
+ people: bindingKeySchema.optional(),
424
+ revisionOrder: z.enum(['integer', 'timestamp', 'opaque']),
425
+ /** Server-managed derived task identities; only the pinned ingestion functions may reconcile them. */
426
+ tasks: bindingKeySchema.optional(),
427
+ })
428
+ .optional(),
429
+ /** Release-owned ingress contracts; workspace settings cannot choose verifiers or job functions. */
430
+ webhooks: z
431
+ .array(z.strictObject({
432
+ route: name,
433
+ verifierFunctionId: uuid,
434
+ syncFunctionId: uuid,
435
+ secretSetting: name,
436
+ headers: z.array(z.string().refine(verifierHeaderAllowed)).min(1).max(20),
437
+ accountHeader: z
438
+ .string()
439
+ .regex(/^[a-z0-9-]{1,100}$/)
440
+ .optional(),
441
+ challenge: z.boolean().optional(),
442
+ optional: z.boolean().optional(),
443
+ }))
444
+ .max(20)
445
+ .optional(),
446
+ settings: z.record(name, z.strictObject({
447
+ type: z.enum(['string', 'boolean', 'number']),
448
+ label,
449
+ /** Absent means installation; keep old serialized manifests and release digests unchanged. */
450
+ level: z.enum(['installation', 'connection']).optional(),
451
+ description: z.string().max(2000).optional(),
452
+ secret: z.boolean().default(false),
453
+ /** Provider-generated secret, writable only by admitted runs; never an admin form input. */
454
+ generated: z.boolean().optional(),
455
+ reconnect: z.boolean().default(false),
456
+ required: z.boolean().default(false),
457
+ /** Form defaults only; approval requests still carry explicit non-secret values. */
458
+ default: z.union([z.string(), z.boolean(), z.number().finite()]).optional(),
459
+ options: z.array(z.string().min(1).max(200)).min(1).max(20).optional(),
460
+ /** Explicit sharing acknowledgement; the server refuses false in a preview or commit. */
461
+ consent: z.boolean().optional(),
462
+ })),
463
+ bindings: z.array(bindingSchema).max(100).optional(),
464
+ views: z.array(viewSchema).max(100),
465
+ functions: z.array(functionSchema).max(100),
466
+ /**
467
+ * A member connection may connect by OAuth (Tamloot connect spec 4.2). The
468
+ * server stages the verifier and the code; the bundle stores the tokens.
469
+ * No defaults, so manifests without it keep their digests.
470
+ */
471
+ oauth: z
472
+ .strictObject({
473
+ verifierSetting: name,
474
+ codeSetting: name,
475
+ tokenSetting: name,
476
+ keySetting: name.optional(),
477
+ /** Where a member revokes the app; shown as a link. */
478
+ revokeUrl: z.url(),
479
+ })
480
+ .optional(),
481
+ /** Shown to a member whose active connection has imported nothing yet. */
482
+ gettingStarted: z
483
+ .strictObject({
484
+ text: z.string().min(1).max(300),
485
+ linkLabel: z.string().min(1).max(60),
486
+ url: z.url(),
487
+ })
488
+ .optional(),
489
+ });
490
+ /** Bound traversal before recursive parsing (including objects received directly by build tools). */
491
+ function bounded(value, depth = 0, seen = new Set()) {
492
+ if (depth > 20)
493
+ throw new Error('unsupported_manifest: maximum nesting is 20');
494
+ if (value && typeof value === 'object') {
495
+ if (seen.has(value))
496
+ throw new Error('unsupported_manifest: cyclic input');
497
+ seen.add(value);
498
+ for (const child of Object.values(value))
499
+ bounded(child, depth + 1, seen);
500
+ seen.delete(value);
501
+ }
502
+ else if (typeof value === 'function' ||
503
+ typeof value === 'symbol' ||
504
+ typeof value === 'bigint') {
505
+ throw new Error('unsupported_manifest: JSON values required');
506
+ }
507
+ }
508
+ function checkInput(schema) {
509
+ if (schema.type !== 'object' &&
510
+ (schema.properties || schema.required || schema.additionalProperties !== undefined))
511
+ throw new Error('unsupported_manifest: object keywords require object type');
512
+ if (schema.type === 'object') {
513
+ if (schema.additionalProperties !== false)
514
+ throw new Error('unsupported_manifest: object inputs must reject additional properties');
515
+ if (new Set(schema.required).size !== (schema.required?.length ?? 0) ||
516
+ schema.required?.some((key) => !Object.hasOwn(schema.properties ?? {}, key)))
517
+ throw new Error('unsupported_manifest: required properties must exist and be unique');
518
+ for (const property of Object.values(schema.properties ?? {}))
519
+ checkInput(property);
520
+ }
521
+ if (schema.type === 'array') {
522
+ if (!schema.items || !schema.maxItems)
523
+ throw new Error('unsupported_manifest: arrays need bounded items');
524
+ checkInput(schema.items);
525
+ }
526
+ else if (schema.items || schema.maxItems !== undefined) {
527
+ throw new Error('unsupported_manifest: array keywords require array type');
528
+ }
529
+ if (schema.maxLength !== undefined && schema.type !== 'string')
530
+ throw new Error('unsupported_manifest: maxLength requires string type');
531
+ }
532
+ function checkFunction(fn) {
533
+ checkInput(fn.inputSchema);
534
+ if (fn.trigger.kind === 'tool')
535
+ checkInput(fn.trigger.outputSchema);
536
+ if (fn.trigger.kind === 'change') {
537
+ const input = fn.inputSchema;
538
+ if (input.type !== 'object' ||
539
+ input.additionalProperties !== false ||
540
+ input.required?.length !== 1 ||
541
+ input.required[0] !== 'changePosition' ||
542
+ Object.keys(input.properties ?? {}).length !== 1 ||
543
+ input.properties?.changePosition?.type !== 'string' ||
544
+ input.properties.changePosition.maxLength !== 19)
545
+ throw new Error('unsupported_manifest: change handlers accept only a local changePosition');
546
+ const watched = fn.trigger.fields ?? [];
547
+ if (new Set(watched).size !== watched.length)
548
+ throw new Error('unsupported_manifest: duplicate watched field');
549
+ const operations = fn.trigger.operations ?? [];
550
+ if (new Set(operations).size !== operations.length)
551
+ throw new Error('unsupported_manifest: duplicate trigger operation');
552
+ }
553
+ if (fn.trigger.kind === 'recordButton') {
554
+ const input = fn.inputSchema;
555
+ if (input.type !== 'object' ||
556
+ input.additionalProperties !== false ||
557
+ input.required?.length !== 1 ||
558
+ input.required[0] !== 'recordId' ||
559
+ Object.keys(input.properties ?? {}).length !== 1 ||
560
+ input.properties?.recordId?.type !== 'string' ||
561
+ input.properties.recordId.maxLength !== 36)
562
+ throw new Error('unsupported_manifest: record buttons accept only a recordId');
563
+ }
564
+ if (fn.trigger.kind === 'schedule') {
565
+ const input = fn.inputSchema;
566
+ if (input.type !== 'object' ||
567
+ input.additionalProperties !== false ||
568
+ input.required?.length !== 1 ||
569
+ input.required[0] !== 'scheduledAt' ||
570
+ Object.keys(input.properties ?? {}).length !== 1 ||
571
+ input.properties?.scheduledAt?.type !== 'string' ||
572
+ (input.properties.scheduledAt.maxLength !== undefined &&
573
+ input.properties.scheduledAt.maxLength < 24))
574
+ throw new Error('unsupported_manifest: schedule handlers accept only a UTC scheduledAt');
575
+ nextOccurrence(fn.trigger.cron, new Date('2000-01-01T00:00:00Z'));
576
+ }
577
+ }
578
+ function checkBindings(manifest) {
579
+ const bindings = manifest.bindings ?? [];
580
+ const byKey = new Map(bindings.map((binding) => [binding.key, binding]));
581
+ const keys = new Set(byKey.keys());
582
+ for (const { trigger } of manifest.functions) {
583
+ if (trigger.kind !== 'change' || !trigger.binding)
584
+ continue;
585
+ const bound = byKey.get(trigger.binding);
586
+ if (!bound || trigger.fields?.some((key) => !bound.fields.some((field) => field.key === key)))
587
+ throw new Error('unsupported_manifest: change trigger names an unknown binding or field');
588
+ }
589
+ for (const fn of manifest.functions) {
590
+ if (fn.trigger.kind !== 'recordButton')
591
+ continue;
592
+ if (manifest.execution !== 'hosted' || manifest.connection !== 'workspace')
593
+ throw new Error('unsupported_manifest: record buttons require hosted workspace execution');
594
+ if (!byKey.has(fn.trigger.binding))
595
+ throw new Error('unsupported_manifest: record button names an unknown binding');
596
+ if (fn.mappedWrite && fn.mappedWrite !== fn.trigger.binding)
597
+ throw new Error('unsupported_manifest: record button must write through its own binding');
598
+ }
599
+ if (keys.size !== bindings.length)
600
+ throw new Error('unsupported_manifest: duplicate binding key');
601
+ for (const view of manifest.views) {
602
+ const binding = byKey.get(view.binding);
603
+ if (!binding ||
604
+ (binding.class === 'event' && binding.access === 'read') ||
605
+ new Set(view.fields).size !== view.fields.length ||
606
+ view.fields.some((key) => !binding.fields.some((field) => field.key === key)))
607
+ throw new Error('unsupported_manifest: view names an unknown binding or field');
608
+ }
609
+ for (const binding of bindings) {
610
+ const fields = new Map(binding.fields.map((field) => [field.key, field]));
611
+ if (fields.size !== binding.fields.length)
612
+ throw new Error(`unsupported_manifest: duplicate field in binding ${binding.key}`);
613
+ if (binding.owned && !binding.create)
614
+ throw new Error(`unsupported_manifest: owned binding ${binding.key} needs a create definition`);
615
+ if (binding.creates && binding.access !== 'write')
616
+ throw new Error(`unsupported_manifest: creating through ${binding.key} requires write access`);
617
+ if (binding.match) {
618
+ const match = fields.get(binding.match);
619
+ if (!match?.required || match.types.length !== 1 || match.types[0] !== 'emails')
620
+ throw new Error(`unsupported_manifest: ${binding.key} needs a required emails match field`);
621
+ }
622
+ for (const field of binding.fields) {
623
+ if ((field.target && (!keys.has(field.target) || field.types.join() !== 'relation')) ||
624
+ (field.values &&
625
+ (field.types.join() !== 'select' ||
626
+ new Set(field.values).size !== field.values.length)) ||
627
+ (field.owned && (!field.create || field.lookup)) ||
628
+ (field.installationOwned && !field.owned) ||
629
+ (field.create && !field.types.includes(field.create.type)))
630
+ throw new Error(`unsupported_manifest: invalid field ${binding.key}.${field.key}`);
631
+ }
632
+ }
633
+ }
634
+ function checkBoundWrites(manifest) {
635
+ for (const fn of manifest.functions) {
636
+ if (!fn.mappedWrite)
637
+ continue;
638
+ const binding = manifest.bindings?.find((entry) => entry.key === fn.mappedWrite);
639
+ if (manifest.execution !== 'hosted' ||
640
+ binding?.access !== 'write' ||
641
+ binding.class !== 'entity')
642
+ throw new Error('unsupported_manifest: mapped writes require a hosted entity write binding');
643
+ if (!['job', 'change', 'schedule', 'recordButton'].includes(fn.trigger.kind) ||
644
+ !functionScopes(manifest, fn).includes('write'))
645
+ throw new Error('unsupported_manifest: mapped writes require a runtime function with write');
646
+ }
647
+ }
648
+ /** The secret settings a function can access. */
649
+ export function functionSecrets(manifest, fn) {
650
+ // A disconnect hook gets only what it declares: generated connection secrets (connect spec 4.2).
651
+ if (fn.trigger?.kind === 'disconnect')
652
+ return fn.secrets ?? [];
653
+ return (fn.secrets ??
654
+ Object.entries(manifest.settings)
655
+ .filter(([, definition]) => definition.secret)
656
+ .map(([key]) => key));
657
+ }
658
+ /** A release's disconnect hook and the generated secrets it may read after a disconnect. */
659
+ export function disconnectHook(manifest) {
660
+ const fn = manifest.functions.find((f) => f.trigger.kind === 'disconnect');
661
+ return { functionId: fn?.universalId ?? null, secrets: fn ? functionSecrets(manifest, fn) : [] };
662
+ }
663
+ /** The function kinds a standalone release may declare (spec 8). */
664
+ const STANDALONE_TRIGGERS = ['tool', 'job'];
665
+ /**
666
+ * Whether a release runs code in the hosted runtime: every hosted release,
667
+ * and a standalone one with functions. Such a release follows the hosted
668
+ * rules for `runtimeEnabled`, executable admission and readiness (spec 8);
669
+ * `execution` decides only how the app's own service gets its credential and
670
+ * how the installation activates.
671
+ */
672
+ export function runsHostedCode(manifest) {
673
+ return manifest.execution === 'hosted' || manifest.functions.length > 0;
674
+ }
675
+ /** The scopes a function needs; its run token gets their intersection with the grant (spec 8). */
676
+ export function functionScopes(manifest, fn) {
677
+ return fn.scopes ?? manifest.scopes;
678
+ }
679
+ /** The capabilities a function's run may receive, before the installation's grant (spec 3.1). */
680
+ export function functionUses(fn) {
681
+ return fn.uses ?? [];
682
+ }
683
+ /** A release's uses: the union of its functions'. Approved with its access. */
684
+ export function releaseUses(manifest) {
685
+ return EXTENSION_USES.filter((use) => manifest.functions.some((fn) => fn.uses?.includes(use)));
686
+ }
687
+ /** Tamloot can install with manual mappings when only its configure hook needs a model. */
688
+ export function hasOptionalSetupModel(manifest) {
689
+ if (manifest.universalId !== TAMLOOT_REGISTRATION_ID || !manifest.bindings?.length)
690
+ return false;
691
+ const modelFunctions = manifest.functions.filter((fn) => functionUses(fn).includes('model'));
692
+ return modelFunctions.length > 0 && modelFunctions.every((fn) => fn.trigger.kind === 'configure');
693
+ }
694
+ /** Whether a release supports this server: inside its range, or in its exact list. */
695
+ export function supportsServer(manifest, serverVersion) {
696
+ if (manifest.serverRange !== undefined)
697
+ return satisfiesServerRange(serverVersion, manifest.serverRange);
698
+ return manifest.serverVersions?.includes(serverVersion) ?? false;
699
+ }
700
+ /** Member credentials and hooks have their own scope; workspace releases retain the first contract. */
701
+ function checkConnections(manifest) {
702
+ const hooks = (kind) => manifest.functions.filter((fn) => fn.trigger.kind === kind);
703
+ const https = (url) => {
704
+ if (new URL(url).protocol !== 'https:')
705
+ throw new Error('unsupported_manifest: manifest links must use https');
706
+ };
707
+ if (manifest.oauth)
708
+ https(manifest.oauth.revokeUrl);
709
+ if (manifest.gettingStarted)
710
+ https(manifest.gettingStarted.url);
711
+ if (manifest.connection === 'workspace') {
712
+ if (Object.values(manifest.settings).some((setting) => setting.level === 'connection') ||
713
+ hooks('connect').length ||
714
+ hooks('disconnect').length ||
715
+ manifest.oauth ||
716
+ manifest.gettingStarted)
717
+ throw new Error('unsupported_manifest: workspace releases cannot declare member settings or hooks');
718
+ return;
719
+ }
720
+ if (manifest.execution !== 'hosted')
721
+ throw new Error('unsupported_manifest: member connections require hosted execution');
722
+ if (hooks('connect').length !== 1 || hooks('disconnect').length > 1)
723
+ throw new Error('unsupported_manifest: member releases require one connect and at most one disconnect hook');
724
+ if (manifest.webhooks?.length)
725
+ throw new Error('unsupported_manifest: member webhooks are not supported');
726
+ if (manifest.functions.some((fn) => ['change', 'route', 'serverRoute'].includes(fn.trigger.kind)))
727
+ throw new Error('unsupported_manifest: member releases cannot declare change or route triggers');
728
+ if (manifest.source && manifest.source.identity !== 'account')
729
+ throw new Error('unsupported_manifest: member sources require account identity');
730
+ for (const setting of Object.values(manifest.settings)) {
731
+ if (setting.secret && setting.level !== 'connection')
732
+ throw new Error('unsupported_manifest: member secrets require connection level');
733
+ if (setting.consent && setting.level === 'connection')
734
+ throw new Error('unsupported_manifest: sharing consent requires installation level');
735
+ }
736
+ const generatedConnectionSecret = (key) => {
737
+ const setting = manifest.settings[key];
738
+ return (!!setting && setting.level === 'connection' && setting.secret && setting.generated === true);
739
+ };
740
+ if (hooks('disconnect').some((fn) => (fn.secrets ?? []).some((key) => !generatedConnectionSecret(key))))
741
+ throw new Error('unsupported_manifest: disconnect hooks may request only generated connection secrets');
742
+ const oauth = manifest.oauth;
743
+ if (!oauth)
744
+ return;
745
+ const handshake = [oauth.verifierSetting, oauth.codeSetting, oauth.tokenSetting];
746
+ if (new Set(handshake).size !== 3 || !handshake.every(generatedConnectionSecret))
747
+ throw new Error('unsupported_manifest: OAuth verifier, code and token settings must be three generated connection secrets');
748
+ if (oauth.keySetting !== undefined) {
749
+ const key = manifest.settings[oauth.keySetting];
750
+ if (key?.level !== 'connection' ||
751
+ !key.secret ||
752
+ key.generated ||
753
+ handshake.includes(oauth.keySetting))
754
+ throw new Error('unsupported_manifest: the OAuth key setting must be a connection secret that is not generated');
755
+ }
756
+ if (Object.values(manifest.settings).some((setting) => setting.level === 'connection' && setting.secret && setting.required))
757
+ throw new Error('unsupported_manifest: with OAuth, no connection secret may be required; the method decides');
758
+ const connect = hooks('connect')[0];
759
+ if (!connect || !handshake.every((key) => functionSecrets(manifest, connect).includes(key)))
760
+ throw new Error('unsupported_manifest: the connect hook must declare the OAuth secrets');
761
+ }
762
+ /** What a binding adds to a workspace's schema: its object and the fields it creates. */
763
+ function createdSchema(binding) {
764
+ return [
765
+ ...(binding.create ? [binding.create] : []),
766
+ ...binding.fields.flatMap((field) => (field.create ? [field.create] : [])),
767
+ ...(binding.create?.fields ?? []),
768
+ ];
769
+ }
770
+ /**
771
+ * Every binding field, and every object and field a binding creates, says what
772
+ * it holds. The configure model reads these descriptions to choose where each
773
+ * value goes, and agents read the created ones in the workspace schema.
774
+ */
775
+ function checkDescriptions(manifest) {
776
+ for (const binding of manifest.bindings ?? [])
777
+ for (const item of [...binding.fields, ...createdSchema(binding)])
778
+ if (!item.description?.trim()) {
779
+ const name = 'key' in item ? item.key : 'name' in item ? item.name : item.nameSingular;
780
+ throw new Error(`unsupported_manifest: describe ${name} in binding ${binding.key}`);
781
+ }
782
+ }
783
+ /**
784
+ * Validates a release manifest. With `retained`, used for a catalog's older
785
+ * releases that installations still run, a release published before
786
+ * descriptions were required loads as it was published.
787
+ */
788
+ export function defineExtension(value, options = {}) {
789
+ const manifest = validManifest(value);
790
+ if (!options.retained)
791
+ checkDescriptions(manifest);
792
+ return manifest;
793
+ }
794
+ function validManifest(value) {
795
+ bounded(value);
796
+ if (new TextEncoder().encode(JSON.stringify(value)).length > 1048576)
797
+ throw new Error('unsupported_manifest: maximum size is 1 MiB');
798
+ const manifest = manifestSchema.parse(value);
799
+ checkBindings(manifest);
800
+ if ((manifest.serverRange === undefined) === (manifest.serverVersions === undefined))
801
+ throw new Error('unsupported_manifest: give exactly one of serverRange or serverVersions');
802
+ if (manifest.serverRange !== undefined)
803
+ parseServerRange(manifest.serverRange);
804
+ const deletion = manifest.settings[SOURCE_DELETE_SETTING];
805
+ if (deletion &&
806
+ (!manifest.source ||
807
+ deletion.type !== 'string' ||
808
+ deletion.secret ||
809
+ (deletion.level ?? 'installation') !== 'installation' ||
810
+ !deletion.options?.length ||
811
+ // A client that leaves the setting out gets the release's policy, so
812
+ // the default the web fills in must be the same.
813
+ (deletion.default !== undefined && deletion.default !== manifest.onSourceDelete) ||
814
+ deletion.options.some((option) => !sourceDeletePolicies.safeParse(option).success) ||
815
+ (deletion.default !== undefined && !deletion.options.includes(String(deletion.default)))))
816
+ throw new Error('unsupported_manifest: onSourceDelete must be an installation choice of keep or retract on a source release');
817
+ const configure = manifest.functions.filter((fn) => fn.trigger.kind === 'configure');
818
+ if (configure.length > 1 ||
819
+ configure.some((fn) => fn.scopes?.length !== 1 ||
820
+ fn.scopes[0] !== 'read' ||
821
+ fn.mappedWrite ||
822
+ functionSecrets(manifest, fn).some((name) => manifest.settings[name]?.level === 'connection')))
823
+ throw new Error('unsupported_manifest: configure requires read-only installation access');
824
+ if (configure.length &&
825
+ (!manifest.scopes.includes('read') ||
826
+ (!manifest.bindings?.length &&
827
+ !Object.values(manifest.settings).some((s) => !s.secret && s.level !== 'connection'))))
828
+ throw new Error('unsupported_manifest: configure needs bindings or non-secret settings');
829
+ const ids = [
830
+ manifest.universalId,
831
+ ...manifest.functions.map((f) => f.universalId),
832
+ ...manifest.views.map((v) => v.universalId),
833
+ ...(manifest.bindings ?? []).flatMap((binding) => createdSchema(binding).map((item) => item.universalId)),
834
+ ];
835
+ if (manifest.functions.some((fn) => fn.universalId === SYSTEM_LIFECYCLE_FUNCTION_ID))
836
+ throw new Error('unsupported_manifest: reserved lifecycle function ID');
837
+ if (new Set(ids).size !== ids.length)
838
+ throw new Error('unsupported_manifest: duplicate universal ID');
839
+ if (new Set(manifest.scopes).size !== manifest.scopes.length)
840
+ throw new Error('unsupported_manifest: duplicate scope');
841
+ if (manifest.oauthClientId && manifest.execution !== 'standalone')
842
+ throw new Error('unsupported_manifest: OAuth clients require standalone execution');
843
+ // Signing in through Retainer needs accounts mode, which an OAuth client marks.
844
+ if (manifest.sidebarLink && !manifest.oauthClientId)
845
+ throw new Error('unsupported_manifest: a sidebar link requires a standalone OAuth client');
846
+ // A standalone app activates when it is approved, with no setup job, so it
847
+ // may declare only functions that need no activation: tools and their jobs.
848
+ if (manifest.execution === 'standalone' &&
849
+ manifest.functions.some((fn) => !STANDALONE_TRIGGERS.includes(fn.trigger.kind)))
850
+ throw new Error('unsupported_manifest: standalone apps may declare only tool and job functions');
851
+ for (const setting of Object.values(manifest.settings))
852
+ if (setting.generated && (!setting.secret || setting.required))
853
+ throw new Error('unsupported_manifest: generated secrets must be optional secret settings');
854
+ for (const setting of Object.values(manifest.settings)) {
855
+ if ((setting.default !== undefined &&
856
+ (setting.secret || typeof setting.default !== setting.type)) ||
857
+ (setting.options &&
858
+ (setting.secret ||
859
+ setting.type !== 'string' ||
860
+ new Set(setting.options).size !== setting.options.length ||
861
+ (setting.default !== undefined && !setting.options.includes(String(setting.default))))) ||
862
+ (setting.consent &&
863
+ (setting.secret ||
864
+ setting.type !== 'boolean' ||
865
+ !setting.required ||
866
+ setting.default === true)))
867
+ throw new Error('unsupported_manifest: invalid setting default, choices or consent');
868
+ }
869
+ checkConnections(manifest);
870
+ if (manifest.lastContact) {
871
+ const policy = manifest.lastContact;
872
+ const bindings = manifest.bindings ?? [];
873
+ if (!bindings.some((b) => b.key === policy.events && b.class === 'event' && b.access === 'read') ||
874
+ new Set(policy.destinations).size !== policy.destinations.length ||
875
+ !policy.destinations.every((key) => bindings.some((b) => b.key === key &&
876
+ b.class === 'entity' &&
877
+ b.access === 'write' &&
878
+ b.fields.some((field) => field.key === 'lastContact' &&
879
+ field.owned &&
880
+ field.types.join() === 'date_time' &&
881
+ field.create?.isNullable !== false &&
882
+ field.create?.isUnique !== true))))
883
+ throw new Error('unsupported_manifest: Last contact requires an event read binding and owned date-time fields.');
884
+ if (manifest.execution !== 'hosted' ||
885
+ !manifest.scopes.includes('read') ||
886
+ !manifest.scopes.includes('write') ||
887
+ new Set(policy.functionIds).size !== policy.functionIds.length ||
888
+ policy.functionIds.some((id) => !manifest.functions.some((fn) => fn.universalId === id && ['job', 'change', 'schedule'].includes(fn.trigger.kind))))
889
+ throw new Error('unsupported_manifest: last-contact requires owned nullable date-time fields and pinned runtime functions');
890
+ }
891
+ const hookRoutes = new Set();
892
+ for (const hook of manifest.webhooks ?? []) {
893
+ const verifier = manifest.functions.find((fn) => fn.universalId === hook.verifierFunctionId);
894
+ if (manifest.execution !== 'hosted' ||
895
+ !manifest.source ||
896
+ !manifest.source.syncFunctionIds.includes(hook.syncFunctionId) ||
897
+ !verifier ||
898
+ !['route', 'serverRoute'].includes(verifier.trigger.kind) ||
899
+ !('route' in verifier.trigger) ||
900
+ verifier.trigger.route !== hook.route ||
901
+ verifier.timeoutSeconds > 5 ||
902
+ !manifest.settings[hook.secretSetting]?.secret ||
903
+ new Set(hook.headers).size !== hook.headers.length ||
904
+ hookRoutes.has(hook.route) ||
905
+ (verifier.trigger.kind === 'serverRoute') !== (hook.accountHeader !== undefined) ||
906
+ (hook.accountHeader !== undefined &&
907
+ (manifest.source.identity !== 'account' || !hook.headers.includes(hook.accountHeader))))
908
+ throw new Error('unsupported_manifest: invalid pinned webhook contract');
909
+ hookRoutes.add(hook.route);
910
+ }
911
+ const routes = manifest.functions
912
+ .filter((f) => 'route' in f.trigger)
913
+ .map((f) => ('route' in f.trigger ? f.trigger.route : ''));
914
+ if (new Set(routes).size !== routes.length)
915
+ throw new Error('unsupported_manifest: duplicate route');
916
+ if (new Set(manifest.functions.map((f) => f.name)).size !== manifest.functions.length)
917
+ throw new Error('unsupported_manifest: duplicate function name');
918
+ for (const definition of Object.values(manifest.settings))
919
+ if (definition.secret && definition.type !== 'string')
920
+ throw new Error('unsupported_manifest: secrets must be strings');
921
+ for (const fn of manifest.functions) {
922
+ checkFunction(fn);
923
+ if (fn.trigger.kind === 'tool' && fn.trigger.connection !== manifest.connection)
924
+ throw new Error('unsupported_manifest: tool connection must match the release');
925
+ if (fn.secrets &&
926
+ (new Set(fn.secrets).size !== fn.secrets.length ||
927
+ fn.secrets.some((key) => !manifest.settings[key]?.secret)))
928
+ throw new Error('unsupported_manifest: function secrets must name distinct secret settings');
929
+ if (fn.scopes &&
930
+ (new Set(fn.scopes).size !== fn.scopes.length ||
931
+ fn.scopes.some((scope) => !manifest.scopes.includes(scope))))
932
+ throw new Error('unsupported_manifest: function scopes must be distinct release scopes');
933
+ if (fn.uses && new Set(fn.uses).size !== fn.uses.length)
934
+ throw new Error('unsupported_manifest: duplicate function use');
935
+ // Webhook verifiers have no network.
936
+ if (fn.uses?.length && ['route', 'serverRoute'].includes(fn.trigger.kind))
937
+ throw new Error('unsupported_manifest: webhook verifiers cannot use platform capabilities');
938
+ }
939
+ if (manifest.source) {
940
+ const source = manifest.source;
941
+ if (manifest.execution !== 'hosted' ||
942
+ !manifest.scopes.includes('write') ||
943
+ !manifest.scopes.includes('read'))
944
+ throw new Error('unsupported_manifest: managed sources require hosted write authority');
945
+ if (manifest.functions.find((f) => f.universalId === source.verifyFunctionId)?.trigger.kind !==
946
+ (manifest.connection === 'member' ? 'connect' : 'install'))
947
+ throw new Error(`unsupported_manifest: source verification requires a registered ${manifest.connection === 'member' ? 'connect' : 'install'} function`);
948
+ const binding = (key) => manifest.bindings?.find((b) => b.key === key);
949
+ if (binding(source.event)?.class !== 'event' ||
950
+ binding(source.event)?.access !== 'write' ||
951
+ !binding(source.event)?.required ||
952
+ !binding(source.event)?.creates)
953
+ throw new Error('unsupported_manifest: sources need a required write event binding that creates records');
954
+ if (source.people &&
955
+ (binding(source.people)?.class !== 'entity' || !binding(source.people)?.match))
956
+ throw new Error('unsupported_manifest: source people need an email match field');
957
+ if (source.tasks &&
958
+ (binding(source.tasks)?.class !== 'entity' ||
959
+ !binding(source.tasks)?.creates ||
960
+ binding(source.tasks)?.access !== 'write'))
961
+ throw new Error('unsupported_manifest: source tasks need an entity that creates records');
962
+ if (new Set(source.syncFunctionIds).size !== source.syncFunctionIds.length)
963
+ throw new Error('unsupported_manifest: duplicate source binding');
964
+ const scans = source.scanFunctionIds ?? [];
965
+ if (new Set(scans).size !== scans.length ||
966
+ scans.some((id) => source.syncFunctionIds.includes(id)))
967
+ throw new Error('unsupported_manifest: duplicate source scan binding');
968
+ for (const id of scans) {
969
+ const kind = manifest.functions.find((f) => f.universalId === id)?.trigger.kind;
970
+ if (kind !== 'job' && kind !== 'schedule')
971
+ throw new Error('unsupported_manifest: source scans require job or schedule functions');
972
+ }
973
+ for (const id of source.syncFunctionIds) {
974
+ const fn = manifest.functions.find((f) => f.universalId === id);
975
+ const input = fn?.inputSchema;
976
+ if (fn?.trigger.kind !== 'job' ||
977
+ input?.type !== 'object' ||
978
+ input.additionalProperties !== false ||
979
+ input.required?.length !== 1 ||
980
+ input.required[0] !== 'sourceItemId' ||
981
+ Object.keys(input.properties ?? {}).length !== 1 ||
982
+ input.properties?.sourceItemId?.type !== 'string' ||
983
+ input.properties.sourceItemId.maxLength !== 36)
984
+ throw new Error('unsupported_manifest: source jobs accept only a local sourceItemId');
985
+ }
986
+ }
987
+ checkBoundWrites(manifest);
988
+ return manifest;
989
+ }
990
+ export function defineFunction(value) {
991
+ bounded(value);
992
+ const fn = functionSchema.parse(value);
993
+ checkFunction(fn);
994
+ return fn;
995
+ }
996
+ export function defineTool(value) {
997
+ bounded(value);
998
+ const { title, effect, connection, outputSchema, ...fn } = toolDefinition.parse(value);
999
+ const tool = {
1000
+ ...fn,
1001
+ trigger: { kind: 'tool', title, effect, connection, outputSchema },
1002
+ };
1003
+ checkFunction(tool);
1004
+ return tool;
1005
+ }
1006
+ export const defineView = (value) => viewSchema.parse(value);
1007
+ export * from './agent.js';
1008
+ export * from './protocol.js';
1009
+ export * from './webhook.js';
1010
+ //# sourceMappingURL=index.js.map