Repository navigation
Expand file tree
/
Copy pathaction-execution.ts
More file actions
2954 lines (2837 loc) · 155 KB
/
Copy pathaction-execution.ts
File metadata and controls
2954 lines (2837 loc) · 155 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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Action-execution subsystem — extracted dispatcher helpers (ADR-0076 D11
* step ③, PR-8). The shared machinery behind server-registered business
* actions: declaration collection/resolution, param enforcement
* (ADR-0104), permission/exposure gates, the engine facade + session shape
* handlers receive, invocation, and the `callData` protocol/ObjectQL data
* bridge. Consumed by the `/actions` domain and the MCP bridge (tool
* invocation path) — extracting it is what turns those two domains into
* mechanical extractions (PR-9).
*
* Depends only on {@link ActionExecutionDeps} — a narrow slice of the
* domain deps contract. NO env-resolution state (kernel/resolver) lives
* here; that stays with the route handlers.
*/
import { validateActionParams, type ActionSession, type ResolvedActionParam } from '@objectstack/spec/ui';
// [#15124] The facade's `find` judges its own parameter against the SAME
// declaration its type names, so the refusal and the type cannot drift apart.
import { EngineQueryOptionsSchema, DATA_ACTION_TO_API_OPERATION } from '@objectstack/spec/data';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import type { IObjectQLEngine, ServiceSlotContract, ServiceSlotContracts } from '@objectstack/spec/contracts';
// [#15942 / #16293] The confirmation member's SPELLING is the contract, so it
// is imported, never hand-spelled: the door that refuses and the client that
// retries have to agree on it, and two doors each writing their own 'confirm'
// is how one contract becomes two dialects (Prime Directive #12).
import {
AI_ACTION_CONFIRMATION_MEMBER,
type AIActionConfirmation,
type ActionConfirmationRequiredDetails,
} from '@objectstack/spec/contracts';
import { checkApiExposure, type ApiExposureDecision, type ObjectApiDef } from './api-exposure.js';
// [#22823] The ONE walk every door that hands a caller's filter to the engine
// takes to find its nested-relation conditions and each one's target — the data
// door's and the MCP stdio bridge's, imported rather than re-walked so this door
// cannot disagree with them about which conditions a filter holds.
import { relationConditionSites } from '@objectstack/core';
// [#9446] The ONE #9378 status table. Imported rather than re-read here: this
// door's blanket `FLOW_FAILED` was the second of three readings of one engine
// result, and a second definition of the rule is what let the doors diverge.
import {
classifyFlowRefusal,
flowIsUnknown,
flowNotFoundMessage,
FLOW_NOT_FOUND_STATUS,
type FlowRefusalCode,
} from './flow-dispatch-status.js';
// Who may START a flow by name — the one rule the trigger door, this door and
// the declared endpoint share (the maintainer's ruling, letters B and A).
import { ELEVATED_START_REFUSAL, refusesElevatedSelfTriggeredStart } from './flow-start-admission.js';
import type { FlowRunSummary } from '@objectstack/spec/automation';
// [#5138] The ONE 404 envelope a single-record path answers. Imported rather
// than re-spelled so `callData`'s ObjectQL fallback and the protocol service it
// falls back FROM cannot disagree about what "this id names no row" looks like.
// A pure factory — no service resolution — so importing it costs the fallback
// nothing on an assembly where the protocol plugin is absent, which is exactly
// when the fallback runs.
import { recordNotFoundError, omitInternalFieldsFromWriteResponse } from '@objectstack/metadata-protocol';
import { serveStoredMetadataRead, serveStoredMetadataReadsThrough } from './stored-metadata-reader-seam.js';
import { actorUserFromExecutionContext, resolveActorDisplayName } from './security/actor-user.js';
import type { HttpProtocolContext } from './http-dispatcher.js';
import {
GLOBAL_ACTION_OBJECT_KEY,
actionHandlerObjectKeys,
isObjectLessActionKey,
reconcileActionRegistrations as reconcileActionRegistrationsPure,
resolveActionHandlerKeys,
standaloneActionOwnerKey,
} from '@objectstack/objectql';
// [ADR-0110] The addressing vocabulary and the D5 reconciliation moved to
// @objectstack/objectql (the engine owns the map they describe, and its
// plugin now runs the boot inventory — AppPlugin, the previous host, is
// registered conditionally and never ran it on the `os dev` path). Runtime
// re-exports them so dispatch, the MCP bridge and existing importers keep
// reading the ONE implementation.
export {
GLOBAL_ACTION_OBJECT_KEY,
actionHandlerObjectKeys,
isObjectLessActionKey,
resolveActionHandlerKeys,
standaloneActionOwnerKey,
};
/** A `sys_`-prefixed object is a system table — off-limits to external MCP agents. */
export function isSystemObjectName(name: string): boolean {
return /^sys_/i.test(name);
}
/**
* Escape hatch: accept param bags that violate the declared contract, the way
* the pre-17 dispatcher did (ADR-0104 D2, 2026-07-30 addendum).
*
* Enforcement is the default. This exists for the operator whose integration
* hits an unforeseen rejection and needs it dispatching again before they can
* reach the caller's code — the violation still logs, so setting this makes the
* drift tolerated, not invisible.
*
* Spelled `OS_ALLOW_*` per Prime Directive #9 and ADR-0110 D6: an opt-OUT of a
* check that ships on, never an opt-IN to a check that ships off.
*/
function laxActionParams(): boolean {
return typeof process !== 'undefined' && process.env?.OS_ALLOW_LAX_ACTION_PARAMS === '1';
}
const _warnedActionParams = new Set<string>();
function warnActionParamsOnce(key: string, message: string): void {
if (_warnedActionParams.has(key)) return;
_warnedActionParams.add(key);
console.warn(message);
}
/**
* The dispatcher facilities the action subsystem may touch.
*
* [#4127 batch 4] `resolveService` is split the same way as the one on
* `DomainHandlerDeps`. This is a NARROWER re-declaration of the same facility
* and it kept returning `any` after the main one stopped — the third copy of
* the pattern, alongside `ResolveOptions` in security/resolve-execution-context.
* A lookup facade has to be typed everywhere it is re-declared, or the copy
* that still says `any` becomes the way around all the others.
*
* [#5155] Both lookups take the REQUEST as their first parameter, for the
* reason spelled out on `DomainHandlerDeps` (of which this is the narrow view
* `HttpDispatcher.actionExecutionDeps` hands out): the object is shared by
* every request the host serves, so the kernel to resolve against is the
* request's, never the facade's.
*/
export interface ActionExecutionDeps {
resolveService<K extends keyof ServiceSlotContracts>(context: HttpProtocolContext, name: K, environmentId?: string): Promise<ServiceSlotContract<K> | undefined>;
resolveService(context: HttpProtocolContext, name: string, environmentId?: string): any;
getObjectQL(context: HttpProtocolContext, environmentId?: string): Promise<IObjectQLEngine | null>;
}
/**
* Direct data service dispatch — replaces broker.call('data.*').
* Tries protocol service first (supports expand/populate), falls back to ObjectQL.
*
* @param requestContext - The request being served (#5155). Carries the kernel
* every service lookup below resolves against; see
* {@link HttpProtocolContext.kernel}.
* @param dataDriver - Optional environment-scoped driver to use instead of kernel default
* @param scopeId - Optional project ID for scoped service resolution (SharedProjectPlugin mode)
*/
/**
* The registered object schema a write mouth in this file applies the
* write-response rules (credential-class mask, `internal` omit) from: the
* engine's live registry first, then the metadata service. `undefined` when
* neither answers — callers FAIL CLOSED on that (echo no record), because an
* unjudged record is exactly the one that may carry a stored credential.
*
* [#22823] It is also the read {@link refuseUnservedRelationTargets} takes, for
* the filtered object's field map and each condition target's `enable` block:
* the engine's own registry first is the schema the engine's relation lowering
* reads. That caller falls OPEN on `undefined`, as the exposure gate does.
*/
export async function resolveWriteResponseSchema(
deps: ActionExecutionDeps,
requestContext: HttpProtocolContext | undefined,
ql: any,
object: string | undefined,
scopeId?: string,
): Promise<unknown> {
if (!object) return undefined;
try {
const fromEngine = ql?.registry?.getObject?.(object);
if (fromEngine) return fromEngine;
} catch {
// fall through to the metadata service
}
try {
const meta = await deps.resolveService(requestContext as HttpProtocolContext, 'metadata', scopeId);
return (await (meta as any)?.getObject?.(object)) ?? undefined;
} catch {
return undefined;
}
}
/**
* [#22823] The runtime action a NESTED-RELATION condition's TARGET is judged as
* by this door's exposure gate: `query`, which the spec's derivation
* (`DATA_ACTION_TO_API_OPERATION`) maps to `list`. A condition is a predicate
* over the whole target — the engine runs `find(target, { where: condition })`
* bounded by a match cap, not by ids the caller holds — which is the read the
* target's own filtered query performs. The data door judges the same target as
* `list` (its own `RELATION_CONDITION_TARGET_OPERATION`, `@objectstack/metadata-protocol`),
* and so does the MCP stdio bridge (`GATED_ACTIONS.query`).
*/
const RELATION_CONDITION_TARGET_ACTION = 'query';
/** The canonical operation that action derives to, named in the refusal. */
const RELATION_CONDITION_TARGET_OPERATION = DATA_ACTION_TO_API_OPERATION[RELATION_CONDITION_TARGET_ACTION];
/**
* [#22823] Census row 10 of #22661. `callData` hands a caller's `where` to the
* ObjectQL ENGINE on two arms: the `query`/`find` fallback that serves when no
* protocol service resolves, and the `aggregate` arm, which never takes the
* protocol. The engine lowers each NESTED-RELATION condition
* (`{ <lookup>: { <field of the related object>: … } }`) by reading the related
* object as the caller (`ObjectQL.lowerRelationConditions`) and keeping the
* rows whose related record matched, so the condition is a predicate over an
* object nobody addressed. The exposure gate at the top of `callData` judges
* only the ADDRESSED object.
*
* So each condition's TARGET is asked the same gate the addressed object is
* asked ({@link checkApiExposure}, for {@link RELATION_CONDITION_TARGET_ACTION}),
* before the engine is called, and a target the gate does not serve REFUSES the
* call. Refused, not withheld: dropping the condition would widen the result.
* The conditions are found by the one walk the data door
* (`refuseUnservedRelationTarget`, #22737) and the MCP stdio bridge
* (`enforceRelationTargetExposure`, #22777) take, `relationConditionSites` from
* `@objectstack/core`, and the refusal is the data door's: the protocol path
* this fallback stands in for answers the same condition `404
* OBJECT_API_DISABLED` / `405 OBJECT_API_METHOD_NOT_ALLOWED`, and one
* `callData` must not give two answers depending on whether the deployment
* registered the protocol slot (the #5138 rule this file already keeps).
*
* `callData` skips it for a system context on the one decision that skips the
* addressed gate: these flags govern API exposure, not the engine's own reads. A schema
* that cannot be resolved finds no condition (the filtered object) or serves
* (a target), the gate's own fail-open.
*/
async function refuseUnservedRelationTargets(
deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
engine: unknown,
object: string,
where: unknown,
scopeId?: string,
): Promise<void> {
if (where == null || typeof where !== 'object') return;
const schema = await resolveWriteResponseSchema(deps, requestContext, engine, object, scopeId);
const fields = (schema as { fields?: Record<string, any> } | undefined)?.fields;
for (const site of relationConditionSites(fields, where)) {
const target = await resolveWriteResponseSchema(deps, requestContext, engine, site.target, scopeId);
const gate = checkApiExposure(target as ObjectApiDef | undefined, RELATION_CONDITION_TARGET_ACTION);
if (!gate.allowed) throw unservedRelationTargetError(site.target, `where.${site.field}`, gate);
}
}
/**
* [#22823] The data door's refusal of an unserved nested-relation condition
* target, field for field (`refuseUnservedRelationTarget`): `code` and `status`
* by the gate's verdict, the TARGET as `object` (the route's object is not the
* one switched off), the condition's position as `param`, and the effective
* operation set as `allowed` on a 405.
*/
function unservedRelationTargetError(target: string, param: string, gate: ApiExposureDecision): Error {
const consequence = `, so the condition on it at '${param}' was not evaluated and the query was not run. `
+ 'Filter on the lookup\'s stored id instead, or remove the condition.';
const disabled = gate.status === 404;
const err: any = new Error(disabled
? `Object '${target}' is not exposed via the API${consequence}`
: `API operation '${RELATION_CONDITION_TARGET_OPERATION}' is not allowed on object '${target}'${consequence}`);
if (disabled) {
err.code = 'OBJECT_API_DISABLED';
err.status = 404;
} else {
err.code = 'OBJECT_API_METHOD_NOT_ALLOWED';
err.status = 405;
err.allowed = gate.allowedOperations ?? [];
}
err.object = target;
err.param = param;
return err;
}
/** The engine for a schema lookup, or `undefined` — a lookup failure is judged by the caller's fail-closed branch. */
async function resolveEngineQuietly(deps: ActionExecutionDeps, requestContext: HttpProtocolContext | undefined, envId?: string): Promise<unknown> {
try {
return (await deps.getObjectQL(requestContext as HttpProtocolContext, envId)) ?? undefined;
} catch {
return undefined;
}
}
export async function callData(deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
action: string,
params: any,
dataDriver?: any,
scopeId?: string,
executionContext?: ExecutionContext,
): Promise<any> {
// ── Object-level API exposure gate (ADR-0049, #1889) ─────
// Honour the object's `apiEnabled` / `apiMethods` declarations for
// external traffic. System/internal contexts bypass — these flags
// govern API *exposure*, not internal engine self-writes.
// [#22823] Decided ONCE, here: the same bypass covers each nested-relation
// condition's target, asked below on the two arms that hand the engine a
// caller's `where` ({@link refuseUnservedRelationTargets}).
const exposureGated = !executionContext?.isSystem;
if (exposureGated && params?.object) {
let def: any;
try {
const meta = await deps.resolveService(requestContext, 'metadata', scopeId);
def = await (meta as any)?.getObject?.(params.object);
} catch {
def = undefined; // fall open to schema defaults (apiEnabled=true)
}
const gate = checkApiExposure(def, action);
if (!gate.allowed) {
throw { statusCode: gate.status ?? 403, message: gate.reason ?? 'API access denied' };
}
}
const protocol = await deps.resolveService(requestContext, 'protocol', scopeId);
const qlService = dataDriver ?? await deps.getObjectQL(requestContext, scopeId);
const ql = qlService ?? await deps.resolveService(requestContext, 'objectql', scopeId);
const qlOpts = executionContext ? { context: executionContext } : undefined;
const findOpts = (extra?: any) => {
const base = qlOpts ? { ...qlOpts } : {};
return extra ? { ...base, ...extra } : (qlOpts ? base : undefined);
};
const writeResponseSchema = () =>
resolveWriteResponseSchema(deps, requestContext, ql, params?.object, scopeId);
if (action === 'create') {
// Prefer the protocol service (validations + RLS + audit), mirroring
// the read paths below. The MCP bridge passes `context.dataDriver` as
// `ql`, which in the multi-env runtime is a RAW db driver with no ORM
// `insert` — so going straight to `ql.insert` broke MCP create_record
// ("ql.insert is not a function") while REST (which uses `createData`)
// worked. Routing writes through the protocol keeps them aligned.
if (protocol && typeof protocol.createData === 'function') {
return await protocol.createData({ object: params.object, data: params.data, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && typeof ql.insert === 'function') {
const res = await ql.insert(params.object, params.data, qlOpts);
const record = { ...params.data, ...res };
// The engine's write result keeps the stored row whole, so this
// fallback mouth owes the same write-response rules the protocol
// ingress applies (credential-class mask, `internal` omit).
// Fail closed: with no schema to judge the fields by, no record
// is echoed at all — only the receipt.
const schema = await writeResponseSchema();
if (!schema) return { object: params.object, id: record.id };
omitInternalFieldsFromWriteResponse(schema, record);
return { object: params.object, id: record.id, record };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'get') {
if (protocol && typeof protocol.getData === 'function') {
return await protocol.getData({ object: params.object, id: params.id, expand: params.expand, select: params.select, context: executionContext });
}
if (ql) {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const match = (all as any[]).find((i: any) => i.id === params.id);
// [#5138] Was `: null` — a miss resolved, and `/data` wrapped it as
// `200 { data: null }`. The protocol path this falls back from has
// answered `404 RECORD_NOT_FOUND` since #4435, so the same GET
// answered 200 or 404 depending only on whether the deployment
// registered the protocol slot — a difference the caller cannot see
// and never asked for.
if (!match) throw recordNotFoundError(params.object, params.id);
return { object: params.object, id: params.id, record: match };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'update') {
// [#23462] `expectedVersion` rides through to `updateData`, whose
// version check refuses a stale update. This arm forwarded only
// `{ object, id, data }`, so a token the `/data` domain read was
// dropped here a second time. Present only when a caller sent one:
// every other caller hands `{ object, id, data }` and reaches
// `updateData` as before. The `delete` arm below does the same.
const expectedVersion = params?.expectedVersion;
if (protocol && typeof protocol.updateData === 'function') {
return await protocol.updateData({
object: params.object,
id: params.id,
data: params.data,
...(expectedVersion !== undefined ? { expectedVersion } : {}),
...(scopeId ? { environmentId: scopeId } : {}),
context: executionContext,
});
}
// [#23462] The fallback below updates by id and nothing else, so it
// cannot judge a version. A caller who sent one is refused `501`
// before anything is read, never updated unguarded: that is the very
// drop the arm above just closed. The `delete` arm's fallback refuses
// it the same way.
if (expectedVersion !== undefined) {
throw {
statusCode: 501,
message: 'This host has no protocol updateData, so it cannot honour expectedVersion or If-Match on an '
+ 'update. Send the update without them, or update through a host whose protocol implements updateData.',
};
}
if (ql && params.id && typeof ql.update === 'function') {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
// [#5138] Was `throw new Error('[ObjectStack] Not Found')`. That
// error carried neither `.status` nor `.statusCode`, so BOTH
// dispatcher exits fell through to their 500 fallback
// (`HttpDispatcher.errorFromThrown`, `dispatcher-plugin`'s
// `errorResponseBase`, and the endpoint executor's `errorAnswer`
// all read `.status` → `.statusCode` → 500). A caller mistake was
// reported as an internal fault and taken to the error reporter
// with it.
if (!existing) throw recordNotFoundError(params.object, params.id);
await ql.update(params.object, params.data, findOpts({ where: { id: params.id } }));
const record = { ...existing, ...params.data };
// The echo carries the caller's own patch: a credential-class value
// in it is masked like a read of the stored row would be. Fail
// closed, as on create: no schema ⇒ the receipt only.
const schema = await writeResponseSchema();
if (!schema) return { object: params.object, id: params.id };
omitInternalFieldsFromWriteResponse(schema, record);
return { object: params.object, id: params.id, record };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'delete') {
// [#23265] `expectedVersion` rides through to `deleteData`, whose
// version check refuses a stale delete. This arm forwarded only
// `{ object, id }`, so a token the `/data` domain read was dropped here
// a second time. Present only when a caller sent one: every other
// caller hands `{ object, id }` and reaches `deleteData` as before.
const expectedVersion = params?.expectedVersion;
if (protocol && typeof protocol.deleteData === 'function') {
return await protocol.deleteData({
object: params.object,
id: params.id,
...(expectedVersion !== undefined ? { expectedVersion } : {}),
...(scopeId ? { environmentId: scopeId } : {}),
context: executionContext,
});
}
// [#23265] The fallback below deletes by id and nothing else, so it
// cannot judge a version. A caller who sent one is refused `501`
// before anything is read, never deleted unguarded: that is the very
// drop the arm above just closed. The `/meta` save refuses a
// precondition its fallback writer cannot honour the same way.
if (expectedVersion !== undefined) {
throw {
statusCode: 501,
message: 'This host has no protocol deleteData, so it cannot honour ?expectedVersion or If-Match on a '
+ 'delete. Send the delete without them, or delete through a host whose protocol implements deleteData.',
};
}
if (ql && typeof ql.delete === 'function') {
// [#5138] There was NO existence check here: the delete ran and the
// answer was `200 { deleted: true }` for any string in the path, so
// a typo'd id, an already-deleted row and a real deletion were
// indistinguishable — the exact shape #4435 removed from the
// protocol's `deleteData`, still live on the path that stands in
// for it. The "assume it worked" answer is the worst of the three
// this fallback gave, because an integrator reading 200 records the
// cleanup as done.
//
// The existence PROBE is a `find`, not a read of what `ql.delete`
// returned. `deleteData` can read its result because `IDataDriver.
// delete` declares `Promise<boolean>` ("true if deleted, false if
// not found"); `ql` here is the ObjectQL ENGINE (or, on the MCP
// multi-env path, a raw driver), and `IDataEngine.delete` declares
// `Promise<any>` — the engine passes its driver's result through
// the hook chain and returns `opCtx.result`. Testing that for
// `=== false` would be reading a signal the contract does not
// promise, which fails silently in the direction this issue is
// about: back to reporting a delete that removed nothing. The probe
// is the same one the sibling `get`/`update` fallbacks already run.
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
if (!existing) throw recordNotFoundError(params.object, params.id);
await ql.delete(params.object, findOpts({ where: { id: params.id } }));
// [#5581] `success`, not `deleted`. The success body was the other
// half of the same "one `callData`, two answers" defect #5138 fixed
// on the not-found side: the protocol path returns the SPEC's shape
// (`DeleteDataResponseSchema` — `{ object, id, success }`,
// `packages/spec/src/api/protocol.zod.ts:472`) and this fallback
// returned `{ object, id, deleted: true }` — `success` missing, and
// `deleted` declared nowhere in the spec. A client written against
// the declared shape read `success === undefined` off an HTTP 200
// on any deployment that did not register the `protocol` slot, and
// had no way to tell which path had served it.
//
// The spec is the authority, not this literal: `success` is what
// `DeleteDataResponseSchema` declares, what the protocol path has
// returned since #4435, and what the public HTTP docs already
// document (`content/docs/protocol/kernel/http-protocol.mdx`).
// Teaching consumers to read `success ?? deleted` would have been
// the contract-first-forbidden shape — two spellings of one fact,
// kept alive by every reader.
return { object: params.object, id: params.id, success: true };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'query' || action === 'find') {
// Build query: use explicit params.query if provided, otherwise extract
// query fields from params. Shared by both paths below — the fallback
// must serve the SAME request the protocol path would have served.
const query = params.query || (() => {
const { object, ...rest } = params;
return rest;
})();
if (protocol && typeof protocol.findData === 'function') {
return await protocol.findData({ object: params.object, query, context: executionContext });
}
if (ql) {
// [#4386] This fallback used to pass only `{ context }` — the
// caller's entire query (where/orderBy/limit/…) was dropped and the
// FULL table came back as an ordinary-looking `{ records, total }`.
// Serve the canonical QueryAST keys both possible recipients
// actually execute (`ql` here is the engine, or on the MCP
// multi-env path a RAW driver reading a QueryAST — same canonical
// keys by design). Anything else — wire spellings (`sort`,
// `select`, …) that need the protocol layer's fold/lowering, or
// capabilities a raw driver would silently drop (`search`,
// `expand`) — is refused loudly rather than part-served: a
// fallback that cannot reproduce the query's semantics must not
// pretend to (route-ownership rule 3).
const FALLBACK_QUERY_KEYS = ['where', 'fields', 'orderBy', 'limit', 'offset'];
const bag: any = {};
const unservable: string[] = [];
for (const [k, v] of Object.entries((query ?? {}) as Record<string, unknown>)) {
if (v == null) continue;
// `context` is SERVER-derived on this path, same as findData's
// unconditional `delete options.context` — a caller-supplied
// one is dropped, never an error and never honoured.
if (k === 'context') continue;
if (FALLBACK_QUERY_KEYS.includes(k)) bag[k] = v;
else unservable.push(k);
}
if (unservable.length > 0) {
throw {
statusCode: 501,
message: `Data query fallback cannot serve ${unservable.map((k) => `'${k}'`).join(', ')}: ` +
'the protocol service (metadata-protocol plugin) is not registered, and without its ' +
`normalization this path serves only canonical QueryAST keys (${FALLBACK_QUERY_KEYS.join(', ')}).`,
};
}
// [#22823] …and each nested-relation condition's TARGET, before the
// engine reads it — the protocol path asks the same of the same
// sites (`refuseUnservedRelationTarget`).
if (exposureGated) {
await refuseUnservedRelationTargets(deps, requestContext, ql, params.object, bag.where, scopeId);
}
let all = await ql.find(params.object, findOpts(bag));
if (!Array.isArray(all) && all && (all as any).value) all = (all as any).value;
if (!all) all = [];
return { object: params.object, records: all, total: all.length };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'aggregate') {
// Aggregate MUST run through the ObjectQL ENGINE (never the raw
// `dataDriver` the MCP bridge threads through for the other verbs):
// only the engine's middleware chain injects RLS/tenant scoping and
// the FLS aggregate-input gate. A raw driver.aggregate() would
// evaluate the query verbatim over every row.
//
// At least one aggregation is REQUIRED: with neither aggregations
// nor groupBy the engine's in-memory path degrades to raw rows,
// and the FLS result masker does not cover the `aggregate` op —
// grouped/aggregated output must stay the only thing this action
// can ever return.
if (!Array.isArray(params.aggregations) || params.aggregations.length === 0) {
throw { statusCode: 400, message: 'aggregate requires at least one aggregation' };
}
const engine = (await deps.getObjectQL(requestContext, scopeId))
?? await deps.resolveService(requestContext, 'objectql', scopeId).catch(() => null);
if (engine && typeof engine.aggregate === 'function') {
// [#22823] This arm takes no protocol, so it is the engine's door on
// every assembly: each nested-relation condition's TARGET in `where`
// is asked before the engine aggregates, as the query fallback asks
// it (the engine lowers relation conditions in `where` only, never
// in an aggregation's own `filter`).
if (exposureGated) {
await refuseUnservedRelationTargets(deps, requestContext, engine, params.object, params.where, scopeId);
}
const rows = await engine.aggregate(
params.object,
{
...(params.where ? { where: params.where } : {}),
...(params.groupBy ? { groupBy: params.groupBy } : {}),
...(params.aggregations ? { aggregations: params.aggregations } : {}),
...(params.timezone ? { timezone: params.timezone } : {}),
...(executionContext ? { context: executionContext } : {}),
},
);
return { object: params.object, rows: rows ?? [] };
}
throw { statusCode: 503, message: 'Data service not available' };
}
// [#5856] `batch` deliberately has NO arm here. It used to answer
// `{ object, results: [] }` — an HTTP 200 whose body a consumer cannot
// tell apart from "the batch ran and matched nothing" — on a path that
// opened no transaction and wrote nothing. Its safety was never its own:
// no caller of `callData` can spell `batch` (`domains/data.ts` compares
// `parts[1]` against the literal `'query'`; `domains/mcp.ts`,
// `domains/actions.ts` and `invokeBusinessAction` pass literals; the
// declarative endpoint executor is bounded by
// `ApiEndpointSchema.objectParams.operation`, a closed enum of
// find/get/create/update/delete; and `callData` is not part of this
// package's export surface), so the arm's only live effect was to
// pre-decide — wrongly — what the FIRST caller to arrive would get:
// a silent success where every other unhandled action gets a loud
// refusal. Removed under ADR-0049 enforce-or-remove, so `batch` falls to
// the same 400 as any other unknown action. Batching itself is untouched
// and keeps its ONE owner (route-ownership rule 1): both the atomic
// cross-object `POST /batch` and the per-object `POST /data/:object/batch`
// are mounted by `@objectstack/rest`'s `registerBatchEndpoints`
// (ADR-0119) — which is exactly why this dispatcher answers
// `capabilities.transactionalBatch: false` (#5672,
// `http-dispatcher.ts`). Pinned by
// `action-execution-calldata-batch-retired.test.ts`.
throw { statusCode: 400, message: `Unknown data action: ${action}` };
}
/**
* [ADR-0066 D4] Shared capability gate for an action invocation. Returns a
* human-readable error string when the caller's `systemPermissions` don't
* cover the action's declared `requiredPermissions`, or `null` when allowed.
* System/engine self-invocation (`isSystem`) bypasses; an action without
* `requiredPermissions` is ungated. Single-sourced so the REST `/actions/...`
* route and the MCP `run_action` bridge enforce the SAME declaration.
*/
export function actionPermissionError(_deps: ActionExecutionDeps, actionDef: any, ec: any, objectName?: string): string | null {
const required: string[] = Array.isArray(actionDef?.requiredPermissions)
? actionDef.requiredPermissions
: [];
if (required.length === 0) return null;
if (ec?.isSystem) return null;
const held = new Set<string>(ec?.systemPermissions ?? []);
const missing = required.filter((perm) => !held.has(perm));
if (missing.length === 0) return null;
const on = objectName ? ` on '${objectName}'` : '';
return (
`Action '${actionDef?.name ?? 'unknown'}'${on} requires capability ` +
`[${required.join(', ')}] — caller is missing [${missing.join(', ')}]`
);
}
/**
* [ADR-0126 §8 item 2] The activation refusal a DISABLED packaged action is
* answered with — `409 ACTION_DISABLED`.
*
* ## Why 409, and why its own code
*
* The artifact exists and is well-formed; only its current STATE conflicts with
* running it, and flipping the switch makes the identical request succeed —
* 409's meaning, and the same reading `FLOW_DISABLED` got in the #9378 table.
* The code is the action's own rather than a borrowed `FLOW_DISABLED`: a
* `script` action refused under a code naming a flow would send an operator
* looking for a flow that does not exist, and a machine-readable surface must
* not lie about which artifact it is talking about (Route & surface ownership
* rule 4). It joins the `*_DISABLED` family already registered in the ADR-0112
* ledger (`FLOW_DISABLED`, `OBJECT_API_DISABLED`, `OBJECT_PACKAGE_DISABLED`) —
* one census row, no new condition class.
*/
export const ACTION_DISABLED_CODE = 'ACTION_DISABLED';
export const ACTION_DISABLED_STATUS = 409;
/** The shape both doors serve — the wire envelope's three fields (ADR-0112). */
export interface DisabledActionRefusal {
code: typeof ACTION_DISABLED_CODE;
status: typeof ACTION_DISABLED_STATUS;
message: string;
}
/**
* [ADR-0126 §8 item 2] THE CONSULT POINT for the action activation ledger —
* asked by every door that dispatches a DECLARED action.
*
* ## Where this sits, and why it is not one seam deeper
*
* The flow leg could put its consult at `execute()`, "the one seam every entry
* path crosses". Actions have no such seam that can answer the question: the
* two per-type primitives below it (`executeRegisteredAction` →
* `ql.executeAction`, and `dispatchFlowAction`) are addressed by HANDLER KEY
* and by target flow name respectively, and ADR-0110 D2 is explicit that a
* registration key is NOT an action's identity ("`AppPlugin` auto-registers
* body actions under `name`, while user code registers a target-bound script
* action under `target`"). The ledger addresses the declarative NAME, so the
* consult belongs exactly where a resolved DECLARATION exists: the REST
* `/actions` door and the MCP `run_action` bridge, each pinned by its own test.
* Placing it lower would silently miss every target-bound action — a gate that
* looks present and is not.
*
* ⚠️ ObjectQL's `ScopedRepo.execute()` — a hook/action BODY reaching another
* handler in-process via `ctx.api.object(x).execute(...)` — is the third
* `executeAction` caller and is deliberately NOT a consult point: it dispatches
* by key with no declaration, carries no caller identity, and is package code
* calling package code (the class ADR-0126 §2 keeps outside the model for
* `hook`). Recorded rather than left to be discovered.
*
* ## Ordering: authorization first, activation second
*
* Both doors call this AFTER the ADR-0066 D4 capability gate. An unentitled
* caller therefore learns nothing about which packaged actions this
* installation has switched off — the same reason `/automation`'s gates run
* ahead of its service probe (a 403 must not become an oracle).
*
* Returns `undefined` when the action may run. An engine that cannot answer
* (no `isActionEnabled` — a host on an older engine, or a test double) yields
* `undefined` too: absence of a ledger means the packaged default, ACTIVE
* (ADR-0126 §4), which is what a stock boot has always done.
*/
export function disabledActionRefusal(
_deps: ActionExecutionDeps,
ql: any,
actionDef: any,
): DisabledActionRefusal | undefined {
const name = actionDef?.name;
if (typeof name !== 'string' || name === '') return undefined;
if (typeof ql?.isActionEnabled !== 'function') return undefined;
if (ql.isActionEnabled(name) !== false) return undefined;
// The SENTENCE is the engine's (`describeDisabledAction`), so both doors
// state one refusal instead of two that agree today; the fallback covers an
// engine that answers the boolean but not the prose.
const message = typeof ql.describeDisabledAction === 'function'
? String(ql.describeDisabledAction(name))
: `Action '${name}' is disabled for this installation (ADR-0126 §8).`;
return { code: ACTION_DISABLED_CODE, status: ACTION_DISABLED_STATUS, message };
}
/**
* [#2849 / ADR-0011] AI-exposure gate for the MCP action surface. Returns a
* human-readable error string unless the action's author explicitly opted it
* into the AI surface with `ai.exposed: true`, or `null` when exposed.
*
* This gate is the REAL agent-facing boundary for actions: script/body
* handlers execute as TRUSTED application code (the engine facade and
* `ctx.api` run `isSystem` — see {@link buildActionExecutionContext}), so once
* invoked, a body's reads/writes are NOT bounded by the caller's RLS/FLS or an
* agent's data ceiling (ADR-0090 D10). The author's explicit opt-in — not a
* data-layer backstop — therefore decides what AI may trigger. Fail-closed by
* default.
*/
export function actionAiExposureError(_deps: ActionExecutionDeps, actionDef: any, objectName?: string): string | null {
if (actionDef?.ai?.exposed === true) return null;
const on = objectName ? ` on '${objectName}'` : '';
return (
`Action '${actionDef?.name ?? 'unknown'}'${on} is not exposed to AI — ` +
`the app author must opt it in with \`ai: { exposed: true, description: … }\``
);
}
/**
* [#15079] The one row-level `operation` the spec admits (`ActionSchema.
* operation`, `z.enum(['update'])` — #14092, maintainer ruling 2026-09-01).
* Named rather than inlined so the predicate below, the two doors and their
* pins all read ONE spelling.
*/
export const DECLARATIVE_UPDATE_OPERATION = 'update';
/**
* [#15079] Is this the DECLARATIVE single-record field write?
*
* ## `operation` is read BEFORE `type` — everywhere, without exception
*
* This is contract point 1 of the executor contract pinned on the spec half
* (PR #15077), and it is a rule about ORDER, not just about a new branch. The
* declarative write is spelled as a key PARALLEL to `type`: `type` answers
* WHERE an action dispatches (`'script'` = the platform action route, which is
* where the write is performed) and `operation` answers WHAT the platform does
* there. Its parsed shape is therefore always `{ type: 'script', operation:
* 'update', patch }` — `type` carries no information at all for it, and the
* spec refuses every other explicit `type` beside it.
*
* So a `type`-keyed reader that runs first gets the RIGHT answer to the WRONG
* question: `isHeadlessInvokableAction` sees a `script` action with neither
* `target` nor `body` and says "not invokable"; `headlessActionTypeError` would
* hand a Studio-authored `type: 'flow'` + `operation: 'update'` row the flow
* prescription. Both are the same defect — the executor's own discriminator
* consulted second. Every reader below asks this function first.
*
* Deliberately a bare equality on the declared key, with no `type` clause: an
* action carrying `operation: 'update'` IS the declarative write, whatever
* `type` says. Data at rest that never went through `ActionSchema` (a Studio
* row, a `strict: false` bundle) is exactly the population where the two keys
* can contradict, and the ruling's answer for it is `operation`.
*/
export function isDeclarativeUpdateAction(action: any): boolean {
return action?.operation === DECLARATIVE_UPDATE_OPERATION;
}
/**
* Whether an action has a headless invocation path (so MCP can run it).
* Mirrors the supported-type set of the (now cloud-side) action-tools
* bridge: `script` needs a handler binding (`target`) or an inline `body`;
* `flow` needs a `target` and an automation service. UI-only types
* (`url`, `modal`, `form`) and `api` have no server dispatch here.
*
* [#15079] …and the DECLARATIVE update is invokable with none of those: it
* carries no handler binding by construction (the spec refuses `target` and
* `body` beside `operation: 'update'`), because the platform performs the
* write. Read first, per {@link isDeclarativeUpdateAction} — the `script` arm
* below answers `false` for it, which would have hidden every declarative
* update action from the MCP `run_action` bridge's listing while the HTTP door
* ran it. That divergence is the failure the card names these predicates to
* prevent.
*/
export function isHeadlessInvokableAction(_deps: ActionExecutionDeps, action: any, hasAutomation: boolean): boolean {
if (isDeclarativeUpdateAction(action)) return true;
const type: string = action?.type ?? 'script';
if (type === 'script') return Boolean(action?.target || action?.body);
if (type === 'flow') return Boolean(action?.target) && hasAutomation;
return false;
}
/**
* The action types a headless caller can actually invoke through a server
* dispatch — the two {@link isHeadlessInvokableAction} accepts. Kept next to
* it so the predicate and the explanation below can never drift apart.
*
* [#15079] Deliberately still a set of TYPES, and deliberately not consulted
* for the declarative update: `operation` is not a type, and adding `'update'`
* here would be the member spelling the ruling rejected. What learned
* `operation` is the READER — {@link headlessActionTypeError} asks
* {@link isDeclarativeUpdateAction} before it reaches this set, so an update
* action never has its `type` classified at all.
*/
const SERVER_DISPATCHED_ACTION_TYPES: ReadonlySet<string> = new Set(['script', 'flow']);
/**
* Explain why a declared action has NO server-side dispatch — `null` when it
* does have one (`script` / `flow`).
*
* The spec is explicit (`packages/spec/src/ui/action.zod.ts`): every
* non-`script` type dispatches on `target`, and only `flow` has a server-side
* runner (the automation engine). `url` / `modal` / `form` are renderer
* navigation and `api` names a *different* endpoint the client calls itself —
* none of them is the script-handler registry. Pre-#3915 the REST route had
* no type branching at all, so every one of them fell through to
* `executeAction` and came back as the misleading
* `Action '' on object '*' not found`. Naming the type and the prescription
* turns that dead end into an actionable 400.
*/
export function headlessActionTypeError(_deps: ActionExecutionDeps, action: any, objectName?: string): string | null {
// [#15079] `operation` before `type`. The declarative update HAS a server
// dispatch — this file performs it — so classifying its `type` could only
// produce a wrong prescription. For the parsed shape (`type: 'script'`)
// the set below already answers `null`; this line is what keeps the answer
// right for data at rest whose `type` contradicts its `operation`.
if (isDeclarativeUpdateAction(action)) return null;
const type: string = action?.type ?? 'script';
if (SERVER_DISPATCHED_ACTION_TYPES.has(type)) return null;
const name: string = action?.name ?? 'unknown';
const on = objectName ? ` on '${objectName}'` : '';
const target: string | undefined = typeof action?.target === 'string' ? action.target : undefined;
if (type === 'api') {
return (
`Action '${name}'${on} is \`type: 'api'\` — it dispatches on \`target\`, ` +
`not through the action registry. Call ${target ? `\`${target}\`` : 'its `target` endpoint'} directly` +
`${typeof action?.method === 'string' ? ` (${action.method})` : ''}.`
);
}
return (
`Action '${name}'${on} is \`type: '${type}'\` — a client-side action with no server dispatch. ` +
`The renderer opens its \`target\`${target ? ` ('${target}')` : ''}; there is nothing for the server to run.`
);
}
/**
* The automation service when this kernel has a usable one, else `null` —
* the single availability probe behind `type: 'flow'` dispatch (both the
* headless-invokability filter and the two invoke paths ask through it).
*/
export async function resolveAutomationService(deps: ActionExecutionDeps, requestContext: HttpProtocolContext, envId?: string): Promise<any | null> {
try {
// [#4127 batch 4] Was `: any`, which voided the gate here. `execute` is
// declared on IAutomationService, so this needed no contract work — only
// for someone to notice, and three grep sweeps over `domains/*.ts` never
// reached this file. The lint rule did.
const svc = await deps.resolveService(requestContext, 'automation', envId);
return svc && typeof svc.execute === 'function' ? svc : null;
} catch {
return null; // no automation service on this kernel
}
}
/** Message for a flow action on a kernel with no automation service (a 503-shaped condition). */
export function flowActionUnavailableError(action: any): string {
return `Action '${action?.name ?? 'unknown'}' is a flow but no automation service is available`;
}
/**
* The params bag a flow action hands the automation engine.
*
* Three seeds, weakest first — each only fills a key the stronger one left
* unset:
* 1. the subject record's fields, which populate a flow's named `isInput`
* variables the way the record-change trigger does;
* 2. the row id under the keys a flow author actually writes —
* `recordId` and the `<objectName>Id` camelCase alias — the SAME two
* `POST /automation/:name/trigger` seeds (`domains/automation.ts`), plus
* the action's own declared `recordIdParam` (seeded from `recordIdField`,
* default `id`) when it names a third key;
* 3. the caller's explicit action params, which win outright.
*
* Seed 2 is the one #3915's first pass missed, and only a real run caught it:
* the params bag carried the record's `id` but never `recordId`, so the CRM's
* own `crm_convert_lead` action — which declares `recordIdParam: 'recordId'`
* and whose flow reads `{recordId}` — reached the engine and died at its first
* node ("1 filter condition(s) resolved to nothing"), while the identical run
* through `/automation/crm_convert_lead_wizard/trigger` succeeded. A declared
* `recordIdParam` that nothing honours is the `declared ≠ enforced` shape in
* miniature.
*/
export function seedFlowActionParams(_deps: ActionExecutionDeps,
action: any,
input: {
objectName: string;
record: Record<string, unknown>;
params: Record<string, unknown>;
recordId?: string;
},
): Record<string, unknown> {
const { objectName, record, params, recordId } = input;
const seeded: Record<string, unknown> = { ...record };
// `recordIdField` names the row field whose value seeds the key (default
// `id`) — a declaration may want a non-id value (spec: `token` for
// revoke-session). Fall back to the explicit recordId when the record
// never loaded (a record-less / new-record invocation).
const idField: string = typeof action?.recordIdField === 'string' && action.recordIdField
? action.recordIdField
: 'id';
const rowId: unknown = record?.[idField] ?? (idField === 'id' ? recordId : undefined);
if (rowId != null) {
for (const key of flowActionRowIdKeys(action, objectName)) {
if (seeded[key] === undefined) seeded[key] = rowId;
}
}
return { ...seeded, ...params };
}
/**
* The keys this door uses to carry the launched row's id into a flow's params
* bag: `recordId`, the camelCase `<objectName>Id` alias (object-bound actions
* only), and the action's own declared `recordIdParam`. ONE definition, read by
* {@link seedFlowActionParams} to seed them and by
* {@link flowActionCallerParamKeys} to keep them out of the caller-provenance
* signal — a second copy of this set is how the two would drift.
*/
function flowActionRowIdKeys(action: any, objectName: string): Set<string> {
const keys = new Set<string>(['recordId']);
// [066dd3bd06 — the card this comment cited no longer resolves] ONE
// predicate for "object-less", the same one
// `dispatchFlowAction` asks before it decides whether to hand the
// automation service an `object` at all. This used to be a second,
// narrower comparison (`objectName !== GLOBAL_ACTION_OBJECT_KEY`), and the
// two parted on exactly one input: a route resolved at the legacy `'*'` was
// object-less to the envelope and object-BOUND here, so the bag grew a
// nonsense `'*Id'` alias. The empty-string leg was never the divergence —
// the `objectName &&` truthiness test this replaces already covered it.
if (!isObjectLessActionKey(objectName)) {
keys.add(`${objectName.replace(/_([a-z])/g, (_m: string, c: string) => c.toUpperCase())}Id`);
}
if (typeof action?.recordIdParam === 'string' && action.recordIdParam) {
keys.add(action.recordIdParam);
}
return keys;
}
/**
* [#19846] `AutomationContext.callerParamKeys` for this door: the keys of the
* CALLER's own `params`, read before {@link seedFlowActionParams} spreads the
* subject row and the row id in — so the screen node's headless verdict is told
* which values the caller supplied instead of inferring it from the merged bag.
*
* The row-id keys ({@link flowActionRowIdKeys}) are left out even when the
* caller's bag names them: a client that mirrors the row id into
* `params.recordId` is addressing the row, not answering a screen. That is also
* what closes the two constructions the inference could not: with a non-default
* `recordIdField` and a `recordIdParam` naming a key the record lacks, the
* seeded row id reached the screen under a name no inference leg could refuse;
* here that name is simply not in the caller's list.
*/
function flowActionCallerParamKeys(action: any, objectName: string, params: Record<string, unknown>): string[] {
const rowIdKeys = flowActionRowIdKeys(action, objectName);
return Object.keys(params).filter((key) => !rowIdKeys.has(key));
}
/**
* Brand for {@link FlowActionRefusal} — `Symbol.for`, so recognition keeps
* working even if two module instances of this file ever coexist (src vs
* dist), where an `instanceof` would silently answer false.
*/
const FLOW_ACTION_REFUSAL_BRAND = Symbol.for('objectstack.runtime.flowActionRefusal');