-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathaction.zod.ts
More file actions
873 lines (823 loc) · 42.8 KB
/
Copy pathaction.zod.ts
File metadata and controls
873 lines (823 loc) · 42.8 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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { retiredKey } from '../shared/retired-key';
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';
import { strictUnknownKeyError } from '../shared/suggestions.zod';
/**
* 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';
/**
* Keys `ActionParamSchema` declares.
*
* Kept beside the schema rather than derived from `.shape`: the schema body is
* allocated lazily (see `lazySchema`), and the error map below has to name a
* canonical key *while* that first parse is still in flight. `action.zod.test.ts`
* asserts every entry here is really accepted, so the list cannot rot silently.
*/
const ACTION_PARAM_KEYS = [
'name', 'field', 'objectOverride', 'label', 'type', 'required', 'options',
'placeholder', 'helpText', 'defaultValue', 'multiple', 'accept', 'maxSize',
'reference', 'defaultFromRow', 'visible', 'requiresFeature',
] as const;
/**
* Semantic near-misses — a different **word** for the same intent, usually
* borrowed from a neighbouring schema where that word is correct. Edit distance
* cannot reach these (`visibleWhen` → `visible` is 4 apart), so they are named
* explicitly; plain case/underscore slips (`help_text` → `helpText`) are left to
* the factory's edit-distance fallback. Mirrors the `FIELD_TYPE_ALIASES`
* pattern in `shared/suggestions.zod.ts`.
*
* Keys are matched case-insensitively with separators removed (see
* {@link strictUnknownKeyError}).
*/
const ACTION_PARAM_KEY_ALIASES: Readonly<Record<string, string>> = {
// The objectql/runtime field shape spells a lookup target `reference_to`, and
// objectui's resolved param calls it `referenceTo`. Dropping either is the
// exact #3405 failure: a targetless picker degrades to a raw-UUID text box.
referenceto: 'reference',
referenceobject: 'reference',
referencedobject: 'reference',
targetobject: 'reference',
// ADR-0089 made `visibleWhen` the canonical predicate on view/page schemas.
// An author who learned it there would silently lose a param's capability
// gate here — the param would render unconditionally.
visiblewhen: 'visible',
visibleon: 'visible',
visibility: 'visible',
description: 'helpText',
help: 'helpText',
default: 'defaultValue',
};
/**
* Custom zod `error` for the `.strict()` {@link ActionParamSchema} (#3405 part 3).
*
* Before this, the schema was zod-default `.strip`: a key it does not declare was
* **silently discarded**, and the param went on parsing. That is how a correctly
* intended `reference: 'sys_user'` became a text box asking a human to paste a
* UUID, with no error anywhere — the config was eaten and the UI lied about why
* (ADR-0078 no-silently-inert-metadata, ADR-0049 enforce-or-remove).
*
* Built by {@link strictUnknownKeyError} — the shared factory this schema's
* hand-rolled #3746 map was generalized into (#4001): it names the offending
* key(s) and, when one is a recognisable spelling of a declared key, points at
* the canonical one.
*/
const actionParamUnknownKeyError = strictUnknownKeyError({
surface: 'this action param',
knownKeys: ACTION_PARAM_KEYS,
aliases: ACTION_PARAM_KEY_ALIASES,
history:
'Until #3405 these were dropped silently — the param still parsed, so a mis-spelled ' +
'config shipped as a control that quietly ignored it.',
});
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.'),
}, { error: actionParamUnknownKeyError }).strict().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` alias was **removed in protocol 17** (#3855). `target` is the
* only handler slot, so no consumer has a second slot to disagree about. An
* authored `execute` is rejected with the rename prescription rather than
* silently stripped; `os migrate meta --from 16` rewrites it for you.
*
* @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>;
/**
* The object half of {@link ActionSchema}, before its refinements.
*
* A factory rather than a schema so `lazySchema`'s deferral still holds — the
* fields are built on first use of whichever schema derives from them, not at
* module load.
*
* It exists because `.pick()` is a `ZodObject` method and `ActionSchema` is
* `z.object(…).refine(…).refine(…)`, so nothing can derive a subset from the
* exported schema. {@link InlineActionSchema} derives from this instead of
* restating a dozen field definitions and their `describe()` text, which is how
* a second action vocabulary would start.
*/
const actionObject = () => 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`.'),
/**
* [REMOVED in protocol 17 — #3855] The deprecated alias of `target`.
* Tombstoned rather than deleted: `ActionSchema` is not `.strict()`, so a
* plain deletion would silently strip the key and the action would bind no
* handler at all — the #2169 "Mark Done does nothing" shape, restored.
*/
execute: retiredKey(
'`execute` was removed in @objectstack/spec 17 (#3855) — use `target`. ' +
'Rename the key; the value (a handler / flow / URL ref) is unchanged. ' +
'Run `os migrate meta --from 16` to rewrite it automatically.',
),
/** 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 PLATFORM ACTION ROUTE rejects
* the call with 403 when the caller's systemPermissions don't cover these (the
* source of truth), and the objectui action surfaces hide the button using the
* same requirement. Independent of `visible` (CEL): this is the RBAC
* capability contract, mirroring `App.requiredPermissions`.
*
* **Server enforcement covers the platform's own invocation paths only** —
* `POST /api/v1/actions/<object>/<action>` (and the MCP/AI path), which is
* where `type: 'script' | 'flow' | 'modal'` actions land. A `type: 'api'`
* action whose `target` is a self-authored endpoint is called by the browser
* DIRECTLY: the platform never sees the request, so nothing checks this
* declaration server-side. Such an endpoint MUST re-check the capability
* itself (framework#3923) — treat the UI gate there as a courtesy, not a
* boundary.
*/
requiredPermissions: z.array(z.string()).optional().describe('[ADR-0066 D4] Capabilities required to invoke this action. Enforced with 403 on the platform action route (script/flow/modal + MCP) and mirrored as a UI hide; a `type: api` action pointed at a custom endpoint must re-check it there.'),
/** Keyboard Shortcut */
// `shortcut` and `bulkEnabled` REMOVED by the 2026-07 #3896 audit close-out —
// both were authorable capability claims nothing enforced (ledger: dead,
// #3686 re-verification): ActionEngine registered them but no keydown path
// ever dispatched a shortcut, and the multi-select toolbar reads the LIST
// VIEW's bulkActions, never this flag. Tombstoned with the prescription;
// `action-inert-keys-removed` strips them from authored sources.
shortcut: retiredKey(
'`action.shortcut` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — ' +
'it never triggered anything: no keydown listener feeds ActionEngine.getShortcuts(), and ' +
"objectui's keyboard stack (useKeyboardShortcuts) is hand-registered and never consults " +
'action metadata. Delete the key. For a real shortcut, register the key in the Console ' +
'keyboard stack and have its handler invoke the action by name.',
),
bulkEnabled: retiredKey(
'`action.bulkEnabled` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — ' +
'the multi-select toolbar is driven by the LIST VIEW\'s `bulkActions` / `bulkActionDefs`, ' +
'never by this flag, so setting it changed nothing. Delete the key and declare the action ' +
"in the view's `bulkActions` instead.",
),
/**
* 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'),
});
export const ActionSchema = lazySchema(() => actionObject().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) => {
// The mirror image of the rule above: a `body` on a NON-script action never
// runs. `type: 'modal' | 'url' | 'flow' | 'api' | 'form'` all dispatch on
// `target` (the page to open, the URL, the flow, the endpoint), so the
// renderer has no point at which it would invoke a body — the action opens
// its target and the body is silently skipped.
//
// This is the same invisible-failure shape as #2169: it passes build, passes
// shape tests, and only shows up as "the modal opened but nothing was
// written" (#3530, where `type: 'modal'` + `params` + `body` was authored
// expecting the body to run on submit). Reject it at author time and name the
// fix — `type: 'script'` collects the same `params` and DOES run the body.
if (data.type !== 'script' && data.body) {
return false;
}
return true;
}, {
message:
"`body` only runs for `type: 'script'` — a non-script action dispatches on `target` and silently ignores its body. " +
"To collect `params` and then run the body, use `type: 'script'`; to open a page/modal, drop the `body` and keep `type: 'modal'` with `target` naming the page.",
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>;
/**
* Legacy spellings an inline action may carry, folded to canonical on parse.
*
* `navigation` is a `type` no spec enum ever declared, and `to` a `target` no
* spec schema ever declared — yet both are what cloud's tenant pages actually
* write on an `element:button` (`{ type: 'navigation', to: PRICING_ROUTE }`,
* five sites across the billing and pricing funnel). They reached a real
* dispatcher: objectui's `ActionRunner` has a `navigation` case reading
* `nav.to ?? nav.target`.
*
* `url` + `target` is the canonical pair, and it is also the *better* one — the
* runner's `url` path adds `${param.X}` / `${ctx.X}` interpolation, `apiBase`
* promotion for `/api/…` paths, and popup-blocker-safe `openIn` handling, none
* of which the `navigation` path has. So this is a bridge with an end state, not
* a second vocabulary: authored `navigation`/`to` keep validating, parse output
* is always `url`/`target`, and the aliases get a `retiredKey` tombstone once
* the producers are migrated.
*
* Exported so a producer can normalize before writing, rather than inventing its
* own fold. objectstack-ai/objectui#2997.
*/
export function normalizeInlineAction(value: unknown): unknown {
if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
const v = value as Record<string, unknown>;
const needsType = v.type === 'navigation';
const needsTarget = v.target === undefined && typeof v.to === 'string';
if (!needsType && !needsTarget && !('to' in v)) return value;
const out: Record<string, unknown> = { ...v };
if (needsType) out.type = 'url';
if (needsTarget) out.target = v.to;
delete out.to;
return out;
}
/**
* An action declared **inline** on a UI surface, rather than registered by name.
*
* The execution half of {@link ActionSchema} — `.pick()`ed from the same field
* definitions, so the `describe()` text, the operator vocabulary and the
* `target`-required rule are shared rather than restated — minus everything that
* only means something for a *registered* action: `objectName`, `locations`,
* `order`, `ai` exposure, `requiredPermissions`, `visible`/`disabled`
* predicates, `resultDialog`.
*
* `name` and `label` are optional here, which is the substantive difference.
* `ActionSchema` requires both because a registry entry needs an identity and a
* menu label; an inline action has neither — the host supplies the label (an
* `element:button` has its own `label` prop, and requiring `action.label` too
* would mean writing it twice).
*
* Scoped deliberately to what a host actually honours. `element:button`'s
* renderer forwards exactly these fields to the `ActionRunner`; `icon` and
* `variant` are excluded because the button has its own, and `body` because a
* page button running an inline sandboxed script is a separate decision. Widen
* this when a renderer widens, not before — a declared field no renderer reads
* is the failure this schema exists to stop.
*/
export const InlineActionSchema = lazySchema(() => z.preprocess(
normalizeInlineAction,
actionObject().pick({
type: true,
name: true,
label: true,
target: true,
openIn: true,
method: true,
params: true,
confirmText: true,
successMessage: true,
errorMessage: true,
refreshAfter: true,
opensInNewTab: true,
}).partial({
name: true,
label: true,
}).refine((data) => {
// The same rule ActionSchema's first refinement applies, for the same
// reason: a `url`/`flow`/`modal`/`api`/`form` action with no `target` has
// nothing to dispatch to and fails silently at click time.
if (TARGET_REQUIRED_TYPES.has(data.type) && !data.target) return false;
return true;
}, {
message: "Inline action 'target' is required when type is 'url', 'flow', 'modal', 'api', or 'form' (`to` is accepted as a legacy spelling).",
path: ['target'],
}),
));
export type InlineAction = z.infer<typeof InlineActionSchema>;
export type InlineActionInput = z.input<typeof InlineActionSchema>;
/**
* 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);
}