-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathaction.zod.ts
More file actions
649 lines (607 loc) · 31.9 KB
/
Copy pathaction.zod.ts
File metadata and controls
649 lines (607 loc) · 31.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { FieldType } from '../data/field.zod';
import { SnakeCaseIdentifierSchema } from '../shared/identifiers.zod';
import { ExpressionInputSchema } from '../shared/expression.zod';
import { I18nLabelSchema, AriaPropsSchema } from './i18n.zod';
import { HookBodySchema } from '../data/hook-body.zod';
// Imported file-directly (not via the kernel barrel): the module is
// deliberately import-free, so this cannot introduce a cycle.
import { PUBLIC_AUTH_FEATURE_NAMES, lowerRequiresFeature } from '../kernel/public-auth-features';
/**
* Action Parameter Schema
*
* Defines inputs required before executing an action.
*
* Two declaration modes:
*
* 1. **Field-backed** (preferred) — reference an existing object field; the
* runtime resolves the field's label (i18n), type, validation rules,
* options, placeholder, help text, and widget mapping from object
* metadata. Cross-object references use `objectOverride`.
*
* ```ts
* params: [
* { field: 'email' }, // same object
* { field: 'role', objectOverride: 'sys_member' }, // different object
* ]
* ```
*
* 2. **Inline** (legacy / bespoke) — declare `name`, `label`, `type` etc.
* inline when no matching object field exists. Inline values may also be
* used alongside `field` to override individual properties. A `lookup` /
* `master_detail` param declared this way MUST name its target object via
* `reference` — there is no field to inherit it from:
*
* ```ts
* params: [
* { name: 'inspector', label: 'Inspector', type: 'lookup', reference: 'sys_user' },
* ]
* ```
*
* `name` is required unless `field` is provided (in which case it defaults
* to the field name and is used as the request-body key).
*/
import { lazySchema } from '../shared/lazy-schema';
export const ActionParamSchema = lazySchema(() => z.object({
/** Request-body key. Defaults to `field` when `field` is set. */
name: z.string().optional(),
/** Reference an existing object field for label/type/validation/options. */
field: SnakeCaseIdentifierSchema.optional(),
/** Object that owns the referenced field (defaults to the action's parent object). */
objectOverride: SnakeCaseIdentifierSchema.optional(),
/** Overrides the resolved field label (or sets it for inline params). */
label: I18nLabelSchema.optional(),
/** Overrides the resolved field type (or sets it for inline params). */
type: FieldType.optional(),
/**
* Required override; when omitted defaults to `false`. Consumers that wish
* to inherit the underlying field's `required` flag should leave this
* undefined in the source schema and resolve at runtime (the dialog
* renderers check truthiness, so `false === undefined` for UI purposes).
*/
required: z.boolean().optional().default(false),
/** Select/picklist options override. */
options: z.array(z.object({ label: I18nLabelSchema, value: z.string() })).optional(),
/** Placeholder override. */
placeholder: z.string().optional(),
/** Help/description override. */
helpText: z.string().optional(),
/** Default value for the dialog input. */
defaultValue: z.unknown().optional(),
/**
* Widget config for inline params (field-backed params inherit these from
* the referenced field at runtime; inline values override). The param
* dialog renders every param through the same field-widget renderer the
* object form uses (objectui ADR-0059), so these mirror the corresponding
* `FieldSchema` knobs.
*/
/** Allow multiple values (file/image/lookup/user params → array value). */
multiple: z.boolean().optional().describe('Allow multiple values (array value shape); mirrors FieldSchema.multiple.'),
/** Accepted upload types (MIME types / extensions) for `file`/`image` params. */
accept: z.array(z.string()).optional().describe('Accepted upload types (MIME types / extensions) for file/image params.'),
/** Max upload size in bytes for `file`/`image` params. */
maxSize: z.number().int().positive().optional().describe('Max upload size in bytes for file/image params.'),
/**
* Reference target for an inline `lookup` / `master_detail` param — the
* object whose records the picker searches. Field-backed params inherit it
* from the referenced field, so it is only needed inline.
*
* Without it the dialog cannot query anything and degrades to a plain text
* input asking for a raw record id, which is unusable for a human — hence
* the `.refine()` below rejects a targetless lookup param at parse time.
*
* Key name deliberately mirrors `FieldSchema.reference` so the same spelling
* works in both places.
*/
reference: SnakeCaseIdentifierSchema.optional().describe('Reference target object for inline lookup/master_detail params; mirrors FieldSchema.reference.'),
/**
* When true, the param's default value is pulled from the current row record
* (key = the resolved field name) when the action runs from a list_item
* context. Useful for edit dialogs that pre-fill from the selected row.
*/
defaultFromRow: z.boolean().optional(),
/**
* Visibility predicate (CEL) — same scope as the action-level `visible`
* (`current_user` / `app` / `data` / `features`). When it evaluates false the
* dialog omits this param entirely. Use it to hide a param that the backend
* only accepts under an opt-in capability, e.g. the create-user `phoneNumber`
* param gated on `features.phoneNumber` so the form never offers a field the
* default backend rejects. Absent = always visible.
*/
visible: ExpressionInputSchema.optional().describe('Param visibility predicate (CEL); omits the param when false.'),
/**
* Declarative capability gate (#2874): name a public auth feature flag
* (see `PUBLIC_AUTH_FEATURES` in `@objectstack/spec/kernel`) and the schema
* lowers it at parse time into the canonical `visible` predicate —
* `features.X == true` (opt-in flag) or `features.X != false` (default-on),
* AND-composed with any explicit `visible`. The sugar key is stripped from
* the parsed output, so renderers/lint only ever see `visible`. Prefer this
* over a hand-written `features.*` predicate: the flag name is
* enum-checked and the gate/registry stay in lockstep.
*/
requiresFeature: z.enum(PUBLIC_AUTH_FEATURE_NAMES).optional().describe('Public auth feature flag gating this param; lowered into `visible` at parse time.'),
}).refine(
(p) => Boolean(p.name) || Boolean(p.field),
{ message: 'ActionParam requires either "name" or "field"' },
).refine(
// An INLINE record-picker param must name its target object. Only inline
// params are checked: a field-backed one inherits the target from the
// referenced field's metadata, which is not visible at parse time.
(p) => !(!p.field && (p.type === 'lookup' || p.type === 'master_detail') && !p.reference),
{
path: ['reference'],
message:
'ActionParam with type "lookup"/"master_detail" requires "reference" (the target object) when declared inline — without it the param dialog degrades to a raw record-id text input. Set `reference: \'<object>\'`, or use a field-backed param (`{ field: \'<lookup_field>\' }`) to inherit it.',
},
).transform((p, ctx) => lowerRequiresFeature(p, ctx)));
/**
* Action type enum values.
*/
export const ActionType = z.enum(['script', 'url', 'modal', 'flow', 'api', 'form']);
/**
* Action types that require a `target` field.
* Derived from ActionType, excluding 'script' which allows inline handlers.
* These types reference an external resource (URL, flow, modal, or API endpoint)
* and cannot function without a target binding.
*/
const TARGET_REQUIRED_TYPES: ReadonlySet<string> = new Set(
ActionType.options.filter((t) => t !== 'script'),
);
/**
* Action Schema
*
* **NAMING CONVENTION:**
* Action names are machine identifiers used in code and must be lowercase snake_case.
*
* **TARGET BINDING:**
* The `target` field is the canonical way to bind an action to its handler.
* - `type: 'script'` — `target` is recommended (references a script/function name).
* - `type: 'url'` — `target` is **required** (the URL to navigate to).
* - `type: 'flow'` — `target` is **required** (the flow name to invoke).
* - `type: 'modal'` — `target` is **required** (the modal/page name to open).
* - `type: 'api'` — `target` is **required** (the API endpoint to call).
* - `type: 'form'` — `target` is **required** (the FormView name to open, routed to `/console/forms/:name`).
*
* The `execute` field is **deprecated** and will be removed in a future version.
* If `execute` is provided without `target`, it is automatically migrated to `target`.
*
* @example Good action names
* - 'on_close_deal'
* - 'send_welcome_email'
* - 'approve_contract'
* - 'export_report'
*
* @example Bad action names (will be rejected)
* - 'OnCloseDeal' (PascalCase)
* - 'sendEmail' (camelCase)
* - 'Send Email' (spaces)
*
* Note: The action name is the configuration ID. JavaScript function names can use camelCase,
* but the metadata ID must be lowercase snake_case.
*/
/**
* Action Location — where an action is allowed to surface in the UI.
*
* Canonical list (single source of truth for the whole platform). Renderers,
* the ActionEngine, the Studio designer dropdowns, and `objectui` consumers
* MUST import from this constant rather than re-declaring their own enum —
* adding a new location should require touching this one file only.
*
* Semantics:
* - `list_toolbar` — header/toolbar of a list view (bulk actions, "New", export).
* - `list_item` — per-row action on a list/grid row (Salesforce row-level menu).
* - `record_header` — primary actions in the record-detail title bar.
* - `record_more` — overflow menu under the "More" / ⋯ button on a record.
* - `record_related` — actions on a related list section inside a record.
* - `record_section` — actions surfaced inside a body section/tab of a record
* (e.g. a Security tab grouping change-password, 2FA, etc.).
* - `global_nav` — global navigation/command-palette level actions.
*/
export const ACTION_LOCATIONS = [
'list_toolbar',
'list_item',
'record_header',
'record_more',
'record_related',
'record_section',
'global_nav',
] as const;
export const ActionLocationSchema = z.enum(ACTION_LOCATIONS);
export type ActionLocation = z.infer<typeof ActionLocationSchema>;
/**
* Tool category values for {@link ActionAiSchema.category}.
*
* Mirrors `ToolCategorySchema` in `../ai/tool.zod`. Kept **inline** rather
* than imported to avoid a `ui → ai` import cycle (`ai/*.form.ts` already
* imports `defineForm` from `ui/view.zod`). If you change the canonical
* tool categories, update both sides.
*/
const ActionAiCategorySchema = z.enum([
'data',
'action',
'flow',
'integration',
'vector_search',
'analytics',
'utility',
]);
/**
* AI exposure block (ADR-0011 "Actions as AI Tools").
*
* **Opt-in, default off.** An action becomes an AI-callable tool only when
* `exposed: true`. This is a deliberate governance gate: in an AI-authoring
* world the platform's value is that a human can govern exactly which
* capabilities the agent fleet is allowed to invoke — a half-finished or
* unreviewed action must never be silently armed.
*
* When exposed, `description` is **required** — it is the LLM-facing contract
* (when/why to call), authored explicitly rather than derived from the
* UI `label`. The bridge in `@objectstack/service-ai` translates this block
* into an `AIToolDefinition`.
*/
export const ActionAiSchema = z.object({
/**
* Expose this action to AI agents as a callable tool. Default `false`.
* Setting `true` REQUIRES `description`.
*/
exposed: z.boolean().default(false).describe('Expose this action to AI agents. Requires `description` when true.'),
/**
* LLM-facing description: tells the model when and why to call this action.
* Distinct from the UI `label`. Plain English, ≥ 40 chars for useful tool
* selection. Required whenever `exposed` is true.
*/
description: z.string().min(40).optional().describe('LLM-facing description (≥40 chars). Required when exposed.'),
/**
* Override the derived tool category. Defaults to `action` (side-effect).
* Use `data` for read-only actions, `analytics` for aggregations, etc.
*/
category: ActionAiCategorySchema.optional().describe('Tool category override (defaults to "action").'),
/**
* Per-parameter AI hints, keyed by param name (or the injected `recordId`).
* Tightens the JSON Schema the LLM sees (e.g. add `enum`, override
* `description`, supply `examples`) WITHOUT changing the UI-facing field
* metadata. Keys must match a declared `params[].name` (or `recordId`).
*/
paramHints: z.record(z.string(), z.object({
description: z.string().optional(),
enum: z.array(z.union([z.string(), z.number()])).optional(),
examples: z.array(z.unknown()).optional(),
})).optional().describe('Per-parameter AI hints keyed by param name.'),
/**
* Output JSON Schema for the action's return value. Enables structured
* downstream tool chaining (one action's output feeds another's input) and
* is summarised into the tool description so the model knows what it gets
* back. Optional — when omitted the return value is treated as freeform.
*/
outputSchema: z.record(z.string(), z.unknown()).optional().describe('JSON Schema for the action return value.'),
/**
* Override confirmation for AI calls. When unset, the bridge defaults to
* `true` for actions that look destructive (`confirmText` set, `mode:'delete'`,
* or `variant:'danger'`). Set explicitly to `false` to assert a destructive-
* looking action is safe to run without human approval, or `true` to force a
* human-in-the-loop gate on an otherwise-safe action.
*/
requiresConfirmation: z.boolean().optional().describe('Override HITL confirmation for AI invocations.'),
});
export type ActionAi = z.infer<typeof ActionAiSchema>;
export const ActionSchema = lazySchema(() => z.object({
/** Machine name of the action */
name: SnakeCaseIdentifierSchema.describe('Machine name (lowercase snake_case)'),
/** Display label */
label: I18nLabelSchema.describe('Display label'),
/** Target object this action belongs to (optional, snake_case) */
objectName: z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe('Target object this action belongs to. When set, the action is auto-merged into the object\'s actions array by defineStack().'),
/** Icon name (Lucide) */
icon: z.string().optional().describe('Icon name'),
/** Where does this action appear? */
locations: z.array(ActionLocationSchema).optional().describe('Locations where this action is visible'),
/**
* Visual Component Type
* Defaults to 'button' or 'menu_item' based on location,
* but can be overridden.
*/
component: z.enum([
'action:button', // Standard Button
'action:icon', // Icon only
'action:menu', // Dropdown menu
'action:group' // Button Group
]).optional().describe('Visual component override'),
/** What type of interaction? */
type: ActionType.default('script').describe('Action functionality type'),
/**
* Payload / Target — the canonical binding for the action handler.
* Required for url, flow, modal, and api types.
* For `script` type: prefer `body` over `target`. `target` is kept only for
* legacy bundle.functions[name] references.
*
* **Interpolation** (renderer responsibility, all action types):
* `target` MAY contain `${param.X}` and `${ctx.X}` tokens. Renderers
* resolve them just before invocation:
* - `${param.X}` — value collected from the action's params dialog.
* - `${ctx.X}` — values from the action context: `ctx.origin`
* (window.origin), `ctx.recordId`, `ctx.user.id`, `ctx.org.id`, etc.
* Used by redirect-style actions like `link_social`, where the target is
* e.g. `/api/v1/auth/sign-in/social?provider=${param.provider}&callbackURL=${ctx.origin}/_console/apps/account/sys_account`.
* Renderers MUST `encodeURIComponent` interpolated values before
* substituting them into URL query positions.
*/
target: z.string().optional().describe('URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation.'),
/**
* For `type:'url'` — where to open `target`. A simple, declarative new-tab
* control for STATIC urls (no handler, no synchronous pre-open). objectui's
* ActionRunner.executeUrl reads `openIn` with priority over the legacy
* `params.newTab`/external-URL heuristic.
*
* - `'new-tab'` — opens `target` in a new browser tab.
* - `'self'` — navigates in place.
* - omitted — external/absolute URLs open in a new tab; relative URLs
* navigate in place.
*
* Distinct from `opensInNewTab`/`newTabUrl`, which pre-open an about:blank
* tab synchronously for ASYNC SSO-redirect handlers — do NOT use `openIn`
* for those. This is a STATIC execution option: keep it OUT of `params`
* (which is user-input-collection only).
*/
openIn: z.enum(['self', 'new-tab']).optional().describe("For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only)."),
/**
* Action Body (L1 expression or L2 sandboxed JS).
*
* Only meaningful when `type === 'script'`. When set, the runtime invokes
* the body inside the sandbox as `(input, ctx) => Promise<output>` and
* ignores `target`.
*
* - `{ language: 'expression', source: '...' }` — pure formula (L1).
* - `{ language: 'js', source: '...', capabilities: [...] }` — sandboxed JS (L2).
*
* Compiled-module bodies are not supported. Outbound IO (HTTP, etc.) goes
* through Connector recipes (separate spec).
*/
body: HookBodySchema.optional().describe('Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`.'),
/**
* @deprecated Use `target` instead. This field is auto-migrated to `target` during parsing.
*/
execute: z.string().optional().describe('@deprecated — Use target instead. Auto-migrated to target during parsing.'),
/** User Input Requirements */
params: z.array(ActionParamSchema).optional().describe('Input parameters required from user'),
/** Visual Style */
variant: z.enum(['primary', 'secondary', 'danger', 'ghost', 'link']).optional().describe('Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)'),
/**
* Explicit sort order WITHIN a UI location group (lower = higher / more
* prominent). Controls where the action lands in each `locations` group
* instead of relying on cross-file `defineStack({ actions })` registration
* order — which is fragile and couples unrelated features.
*
* In `record_header` the first visible action becomes the primary button, so
* a low (or negative) `order` promotes an action into the primary slot and a
* high `order` demotes it toward the `⋯` overflow menu. This is the
* declarative lever a plugin (e.g. plugin-approvals) or app author uses to
* make a decision like Approve/Reject stably outrank app actions, rather than
* hiding the other actions to "make room".
*
* Honoured by a STABLE sort in `mergeActionsIntoObjects()` (see stack.zod):
* actions that leave `order` unset are treated as `0` and keep their original
* registration order, so setting `order` on nobody is a no-op — fully
* backward compatible. Renderers MAY additionally prefer a `variant:'primary'`
* action when two actions tie on `order` (see objectui record-header renderer).
*/
order: z.number().optional().describe('Sort order within a location group (lower = higher). Promotes/demotes an action toward the record_header primary button; stable, so actions without `order` keep their registration order.'),
/** UX Behavior */
confirmText: I18nLabelSchema.optional().describe('Confirmation message before execution'),
successMessage: I18nLabelSchema.optional().describe('Success message to show after execution'),
// Runtime (ActionRunner) already honours this — declared here so authors can
// set a friendly failure toast instead of surfacing the raw error string.
errorMessage: I18nLabelSchema.optional().describe('Error message to show when the action fails (overrides the raw error).'),
refreshAfter: z.boolean().default(false).describe('Refresh view after execution'),
// Single-record update actions only. When true, the runtime captures the
// record's prior field values and offers an "Undo" affordance on the success
// toast (backed by the client UndoManager) to restore them.
undoable: z.boolean().optional().describe('Offer an Undo affordance after this single-record update action succeeds.'),
/**
* Result Dialog — describe how to render the API response on success.
*
* When set and the action returns successfully, the renderer SHOULD open a
* dialog showing the selected fields from `result.data` instead of the
* `successMessage` toast. The dialog has an acknowledge button only — the
* user must explicitly close it. Used for **one-shot reveals** of values
* the user must copy now because they cannot be retrieved later:
*
* - TOTP enrollment URI + secret (`enable_two_factor`)
* - Backup recovery codes (`regenerate_backup_codes`)
* - Freshly minted OAuth `client_secret` (`rotate_client_secret`,
* `create_oauth_application`)
*
* `fields` selects what to render and how. Each entry's `path` is a dot
* path into `result.data` (e.g. `'totpURI'`, `'backupCodes'`,
* `'client.client_secret'`). When `fields` is omitted, the renderer falls
* back to JSON-printing the whole response under a single block.
*
* `format` (dialog-level) is a default for fields that don't carry their
* own `format`; the per-field `format` always wins.
*
* Renderer contract (objectui):
* - `qrcode` — render the value as a QR code; also render the raw string
* underneath with a copy button (so the user can paste into apps that
* don't scan).
* - `code-list` — value must be an array of strings; render each in a
* monospace row with per-row copy and a "Copy all" affordance.
* - `secret` — render a single string masked by default with a reveal
* toggle and copy button.
* - `text` — plain text with copy.
* - `json` — pretty-printed JSON in a monospace block.
*
* The dialog SHOULD set `refreshAfter` to true on close (separate from
* the existing `refreshAfter` flag, which fires immediately on success).
*/
resultDialog: z.object({
title: I18nLabelSchema.optional(),
description: I18nLabelSchema.optional(),
acknowledge: I18nLabelSchema.optional().describe('Acknowledge button label, e.g. "I have saved this"'),
format: z.enum(['qrcode', 'code-list', 'secret', 'text', 'json']).optional().describe('Default format for fields without their own format. Defaults to json when omitted.'),
fields: z.array(z.object({
path: z.string().describe('Dot path into result.data (e.g. "totpURI", "client.client_secret").'),
label: I18nLabelSchema.optional(),
format: z.enum(['qrcode', 'code-list', 'secret', 'text', 'json']).optional().describe('Per-field format override.'),
})).optional().describe('Which fields from result.data to render. Omit to dump full JSON.'),
}).optional().describe('Render API response in a one-shot reveal dialog (suppresses successMessage when set).'),
/** Access */
visible: ExpressionInputSchema.optional().describe('Visibility predicate (CEL).'),
/**
* Declarative capability gate (#2874) — action-level twin of the param
* `requiresFeature`. Lowered at parse time into `visible` (`== true` for
* opt-in flags, `!= false` for default-on; AND-composed with an explicit
* `visible`) and stripped from the output. See `PUBLIC_AUTH_FEATURES` in
* `@objectstack/spec/kernel`.
*/
requiresFeature: z.enum(PUBLIC_AUTH_FEATURE_NAMES).optional().describe('Public auth feature flag gating this action; lowered into `visible` at parse time.'),
disabled: z.union([z.boolean(), ExpressionInputSchema]).optional().describe('Boolean or predicate (CEL) — action is disabled when TRUE.'),
/**
* [ADR-0066 D4] System capabilities required to INVOKE this action — a
* dual-surface gate from ONE declaration: the server (action route) rejects
* the call with 403 when the caller's systemPermissions don't cover these (the
* source of truth), and the objectui ActionRunner hides/disables the button
* using the same requirement. Independent of `visible` (CEL): this is the RBAC
* capability contract, mirroring `App.requiredPermissions`.
*/
requiredPermissions: z.array(z.string()).optional().describe('[ADR-0066 D4] Capabilities required to invoke this action (server-enforced 403 + UI hide/disable).'),
/** Keyboard Shortcut */
shortcut: z.string().optional().describe('Keyboard shortcut to trigger this action (e.g., "Ctrl+S")'),
/** Bulk Operations */
bulkEnabled: z.boolean().optional().describe('Whether this action can be applied to multiple selected records'),
/**
* AI exposure block (ADR-0011). Opt-in, default off: an action is exposed
* to AI agents only when `ai.exposed === true`, in which case `ai.description`
* is required. See {@link ActionAiSchema}.
*/
ai: ActionAiSchema.optional().describe('AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.'),
/**
* Row-context: when the action runs from a list_item location, this body key
* receives the row's id (or the field named by `recordIdField`). Defaults to
* `id` when omitted but `recordIdField` is set; otherwise no injection.
*/
recordIdParam: z.string().optional().describe('Body key to inject the row id into when running from a list_item context.'),
/**
* Row field whose value seeds `recordIdParam`. Defaults to `'id'` when
* `recordIdParam` is set. Use this when the body key expects a non-id value
* (e.g. `token` for `revoke-session`).
*/
recordIdField: z.string().optional().describe('Row field whose value seeds recordIdParam. Defaults to "id".'),
/**
* Request-body shape. `'flat'` (default) sends collected params at the top
* level. `{ wrap: 'data' }` nests the user-collected params under that key
* (used by better-auth `organization/update`), while `recordIdParam` and
* other top-level keys stay flat.
*/
bodyShape: z.union([
z.literal('flat'),
z.object({ wrap: z.string() }),
]).optional().describe('Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.'),
/**
* HTTP method to use when `type: 'api'`. Defaults to `POST`. Use `PATCH` to
* call data-API update endpoints (e.g. `/api/v1/sys_api_key/{id}` with
* `bodyExtra: { revoked: true }`).
*/
method: z.enum(['POST', 'PATCH', 'PUT', 'DELETE']).optional().describe('HTTP method for type:"api" actions. Defaults to POST.'),
/**
* Static body fragment merged into the outgoing request body for `type:'api'`
* actions. Useful for constants the user shouldn't (or can't) edit, e.g.
* `bodyExtra: { resend: true }` on a resend-invitation action that reuses
* better-auth's `invite-member` endpoint. Applied after user-collected
* params and `recordIdParam` so constants always win.
*/
bodyExtra: z.record(z.string(), z.unknown()).optional().describe('Constant body fields merged into the API request (applied last; overrides user params).'),
/**
* Semantic mode hint — UI / runtime can use this to pick confirm copy,
* default variants, success messaging. Pure metadata; no runtime branching.
*/
mode: z.enum(['create', 'edit', 'delete', 'custom']).optional().describe('Semantic mode of the action.'),
/**
* Open the action's result in a NEW TAB. The renderer pre-opens the tab
* synchronously on click (preserving the user gesture so popup blockers
* don't fire), paints a progress page, then drives the tab to the
* handler's returned `redirectUrl` — or, when `newTabUrl` is set, straight
* to that URL with no server round trip.
*/
opensInNewTab: z.boolean().optional().describe('Open the action result in a new tab. The renderer pre-opens the tab synchronously on click (popup-blocker-safe) and navigates it to the handler\'s redirectUrl.'),
/**
* Zero-roundtrip new-tab target. A path template the renderer navigates
* the pre-opened tab to IMMEDIATELY on click, skipping the action POST
* entirely. Only valid together with `opensInNewTab`. The target endpoint
* MUST perform all auth/authz itself (e.g. the cloud `/sso-open` endpoint,
* which re-runs every check the POST half would have done). Supports the
* `{recordId}` placeholder, URL-encoded on substitution.
*/
newTabUrl: z.string().optional().describe('Direct new-tab URL template ({recordId} placeholder). When set with opensInNewTab, the renderer navigates the pre-opened tab here immediately — no action POST. The endpoint must enforce auth itself.'),
/** ARIA accessibility attributes */
aria: AriaPropsSchema.optional().describe('ARIA accessibility attributes'),
}).transform((data) => {
// Auto-migrate deprecated `execute` → `target` for backward compatibility
if (data.execute && !data.target) {
return { ...data, target: data.execute };
}
return data;
}).refine((data) => {
// Require `target` for types that reference an external resource
if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) {
return false;
}
return true;
}, {
message: "Action 'target' is required when type is 'url', 'flow', 'modal', 'api', or 'form'.",
path: ['target'],
}).refine((data) => {
// A `script` action must be *executable*: it needs either an inline `body`
// (the runtime invokes it in the sandbox) or a `target` naming a registered
// bundle function. With neither, AppPlugin registers no engine handler and
// the action fails at runtime with `Action '<name>' on object '*' not found`
// (the #2169 Mark Done bug) — a soft failure invisible to build & shape
// tests. Reject it at author/compile time instead.
if (data.type === 'script' && !data.body && !data.target) {
return false;
}
return true;
}, {
message:
"A 'script' action requires either an inline `body` (sandboxed L1/L2 handler) or a `target` (a registered bundle function name).",
path: ['body'],
}).refine((data) => {
// ADR-0011: an exposed action must carry an LLM-facing description.
if (data.ai?.exposed === true && !data.ai.description) {
return false;
}
return true;
}, {
message: 'ai.description is required (≥40 chars) when ai.exposed is true.',
path: ['ai', 'description'],
}).refine((data) => {
// ADR-0011: paramHints keys must reference a declared param (or the
// auto-injected `recordId`), so a typo can't silently no-op.
const hints = data.ai?.paramHints;
if (!hints) return true;
const known = new Set<string>(['recordId']);
for (const p of data.params ?? []) {
const key = p.name ?? p.field;
if (key) known.add(key);
}
return Object.keys(hints).every((k) => known.has(k));
}, {
message: 'ai.paramHints keys must match a declared param name (or "recordId").',
path: ['ai', 'paramHints'],
}).transform((data, ctx) => lowerRequiresFeature(data, ctx)));
export type Action = z.infer<typeof ActionSchema>;
export type ActionParam = z.infer<typeof ActionParamSchema>;
export type ActionInput = z.input<typeof ActionSchema>;
/**
* Action Factory Helper
*/
export const Action = {
create: (config: z.input<typeof ActionSchema>): Action => ActionSchema.parse(config),
} as const;
/**
* Type-safe factory for a global or object action. Validates at authoring time via
* `.parse()` and accepts input-shape config (optional defaults, CEL
* shorthand) — preferred over a bare `: Action` literal.
*/
export function defineAction(config: z.input<typeof ActionSchema>): Action {
return ActionSchema.parse(config);
}