-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathexecutor.ts
More file actions
3310 lines (3081 loc) · 127 KB
/
Copy pathexecutor.ts
File metadata and controls
3310 lines (3081 loc) · 127 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
import { Effect, Inspectable, Layer, Option, Predicate, Schema } from "effect";
import { FetchHttpClient, type HttpClient } from "effect/unstable/http";
import { fumadb } from "@executor-js/fumadb";
import { memoryAdapter } from "@executor-js/fumadb/adapters/memory";
import { withQueryContext, type Condition, type ConditionBuilder } from "@executor-js/fumadb/query";
import { schema as fumaSchema, type RelationsMap } from "@executor-js/fumadb/schema";
import type { AnyColumn } from "@executor-js/fumadb/schema";
import { generateKeyBetween } from "fractional-indexing";
import {
StorageError,
isStorageFailure,
makeFumaClient,
type FumaDb,
type FumaRow,
type FumaTables,
type StorageFailure,
} from "./fuma-runtime";
import { makeFumaBlobStore, pluginBlobStore, type BlobStore, type OwnerPartitions } from "./blob";
import { coreToolsPlugin } from "./core-tools";
import type {
Connection,
ConnectionInputOrigin,
ConnectionRef,
CreateConnectionInput,
ConnectionValueInput,
UpdateConnectionInput,
} from "./connection";
import {
coreSchema,
isToolPolicyAction,
TOOL_INVOCATION_COLUMNS,
type ConnectionRow,
type CoreSchema,
type IntegrationRow,
type OAuthClientRow,
type ToolInvocationRow,
type ToolRow,
type ToolPolicyRow,
} from "./core-schema";
import {
ElicitationDeclinedError,
ElicitationResponse,
FormElicitation,
type ElicitationHandler,
type ElicitationRequest,
type OnElicitation,
type InvokeOptions,
} from "./elicitation";
export type { OnElicitation, InvokeOptions } from "./elicitation";
import {
ConnectionNotFoundError,
CredentialProviderNotRegisteredError,
CredentialResolutionError,
IntegrationNotFoundError,
InvalidConnectionInputError,
IntegrationRemovalNotAllowedError,
NoHandlerError,
PluginNotLoadedError,
ToolBlockedError,
ToolInvocationError,
ToolNotFoundError,
type ExecuteError,
} from "./errors";
import {
AuthTemplateSlug,
ConnectionAddress,
ConnectionName,
IntegrationSlug,
NO_AUTH_TEMPLATE,
OAuthClientSlug,
Owner,
PolicyId,
ProviderItemId,
ProviderKey,
Subject,
Tenant,
ToolAddress,
ToolName,
} from "./ids";
import type {
AuthMethodDescriptor,
Integration,
IntegrationConfig,
RegisterIntegrationInput,
} from "./integration";
import { makeOAuthService, type MintOAuthConnectionInput } from "./oauth-service";
import type { OAuthService } from "./oauth-client";
import {
comparePolicyRow,
isValidPattern,
resolveEffectivePolicy,
rowToToolPolicy,
type CreateToolPolicyInput,
type EffectivePolicy,
type RemoveToolPolicyInput,
type ToolPolicy,
type UpdateToolPolicyInput,
} from "./policies";
import type { CredentialProvider, ProviderEntry } from "./provider";
import type {
AnyPlugin,
Elicit,
IntegrationConfigureSchema,
IntegrationPresetCatalogEntry,
IntegrationRecord,
OwnerBinding,
PluginCtx,
PluginExtensions,
ResolveToolsResult,
StaticSourceDecl,
StaticToolDecl,
StorageDeps,
ToolInvocationCredential,
} from "./plugin";
import {
pluginStorageId,
type PluginStorageCollectionData,
type PluginStorageCollectionDefinition,
type PluginStorageCollectionQueryInput,
type PluginStorageEntry,
type PluginStorageFacade,
type PluginStorageRuntimeCollectionDefinition,
type PluginStorageRuntimeIndexSpec,
} from "./plugin-storage";
import {
assertExecutorOwnerPolicyTable,
ORG_SUBJECT,
type ExecutorOwnerPolicyContext,
} from "./owner-policy";
import { ToolSchemaView, type IntegrationDetectionResult } from "./types";
import { type Tool, type ToolAnnotations, type ToolDef, type ToolListFilter } from "./tool";
import { buildToolTypeScriptPreview } from "./schema-types";
import { collectReferencedDefinitions } from "./schema-refs";
import {
refreshAccessToken,
exchangeClientCredentials,
shouldRefreshToken,
type OAuthEndpointUrlPolicy,
} from "./oauth-helpers";
import { connectionIdentifier } from "./connection-name-identifier";
import { annotateToolResultOutcome } from "./tool-result";
const PLUGIN_STORAGE_DELETE_KEY_BATCH_SIZE = 90;
const PLUGIN_STORAGE_CREATE_ROW_BATCH_SIZE = 90;
const MAX_APPROVAL_ARGUMENT_PREVIEW_CHARS = 4_000;
// ---------------------------------------------------------------------------
// Elicitation handler — resolved once at `createExecutor({ onElicitation })`
// and overridable per `execute`. A tool that requests user input mid-execution
// suspends the fiber and the handler decides how to respond. The "accept-all"
// sentinel auto-accepts (tests / non-interactive hosts).
// ---------------------------------------------------------------------------
const acceptAllHandler: ElicitationHandler = () =>
Effect.succeed(ElicitationResponse.make({ action: "accept" }));
const resolveElicitationHandler = (onElicitation: OnElicitation): ElicitationHandler =>
onElicitation === "accept-all" ? acceptAllHandler : onElicitation;
// ---------------------------------------------------------------------------
// Address scheme — `tools.<integration>.<owner>.<connection>.<tool>`.
// ---------------------------------------------------------------------------
const ADDRESS_PREFIX = "tools";
export interface ParsedToolAddress {
readonly integration: IntegrationSlug;
readonly owner: Owner;
readonly connection: ConnectionName;
readonly tool: ToolName;
}
const isOwner = (value: string): value is Owner => value === "org" || value === "user";
/** Parse a callable address; null when it's not a well-formed
* `tools.<integration>.<owner>.<connection>.<tool>`.
*
* The four leading segments (prefix, integration, owner, connection) are
* slug-like and never contain a `.`; the `<tool>` segment is the *entire*
* remainder after the 4th dot, so it may itself contain dots. That lets a tool
* whose name is a structured `group.leaf` path (e.g. an OpenAPI
* `aliases.deleteAlias`) address naturally as
* `tools.<integration>.<owner>.<connection>.aliases.deleteAlias` — the same
* dotted nesting the sandbox `tools` proxy produces from property access. */
export const parseToolAddress = (address: string): ParsedToolAddress | null => {
// Walk to the 4th dot; everything past it is the tool (dots and all).
let cut = -1;
for (let i = 0; i < 4; i++) {
cut = address.indexOf(".", cut + 1);
if (cut === -1) return null;
}
const [prefix, integration, owner, connection] = address.slice(0, cut).split(".") as [
string,
string,
string,
string,
];
const tool = address.slice(cut + 1);
if (prefix !== ADDRESS_PREFIX) return null;
if (!isOwner(owner)) return null;
if (integration.length === 0 || connection.length === 0 || tool.length === 0) {
return null;
}
return {
integration: IntegrationSlug.make(integration),
owner,
connection: ConnectionName.make(connection),
tool: ToolName.make(tool),
};
};
export const connectionAddress = (
owner: Owner,
integration: IntegrationSlug,
connection: ConnectionName,
): ConnectionAddress =>
ConnectionAddress.make(`${ADDRESS_PREFIX}.${integration}.${owner}.${connection}`);
export const toolAddress = (
owner: Owner,
integration: IntegrationSlug,
connection: ConnectionName,
tool: ToolName,
): ToolAddress =>
ToolAddress.make(`${ADDRESS_PREFIX}.${integration}.${owner}.${connection}.${tool}`);
// ---------------------------------------------------------------------------
// Owner key helpers — every owned-row write stamps `tenant`, `owner`,
// `subject` (org → subject="").
// ---------------------------------------------------------------------------
interface OwnedKeys {
readonly tenant: string;
readonly owner: Owner;
readonly subject: string;
}
// ---------------------------------------------------------------------------
// Executor — public surface. Every list/execute/schema call is a direct
// core-table query unioned with the in-memory static pool.
// ---------------------------------------------------------------------------
export type Executor<TPlugins extends readonly AnyPlugin[] = readonly []> = {
readonly integrations: {
readonly list: () => Effect.Effect<readonly Integration[], StorageFailure>;
readonly get: (slug: IntegrationSlug) => Effect.Effect<Integration | null, StorageFailure>;
readonly update: (
slug: IntegrationSlug,
patch: { readonly name?: string; readonly description?: string },
) => Effect.Effect<void, IntegrationNotFoundError | StorageFailure>;
readonly remove: (
slug: IntegrationSlug,
) => Effect.Effect<void, IntegrationRemovalNotAllowedError | StorageFailure>;
readonly detect: (
url: string,
) => Effect.Effect<readonly IntegrationDetectionResult[], StorageFailure>;
};
readonly connections: {
readonly create: (
input: CreateConnectionInput,
) => Effect.Effect<
Connection,
| IntegrationNotFoundError
| CredentialProviderNotRegisteredError
| InvalidConnectionInputError
| StorageFailure
>;
readonly list: (filter?: {
readonly integration?: IntegrationSlug;
readonly owner?: Owner;
}) => Effect.Effect<readonly Connection[], StorageFailure>;
readonly get: (ref: ConnectionRef) => Effect.Effect<Connection | null, StorageFailure>;
/** Edit user-curated metadata (description, identityLabel). Credentials and
* OAuth lifecycle fields are not editable here. */
readonly update: (
ref: ConnectionRef,
input: UpdateConnectionInput,
) => Effect.Effect<Connection, ConnectionNotFoundError | StorageFailure>;
readonly remove: (
ref: ConnectionRef,
) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>;
readonly refresh: (
ref: ConnectionRef,
) => Effect.Effect<
readonly Tool[],
ConnectionNotFoundError | IntegrationNotFoundError | StorageFailure
>;
};
/** Shared OAuth service. Hosts use this through the core HTTP OAuth group;
* plugins see the same service as `ctx.oauth`. */
readonly oauth: OAuthService;
readonly tools: {
readonly list: (filter?: ToolListFilter) => Effect.Effect<readonly Tool[], StorageFailure>;
readonly schema: (address: ToolAddress) => Effect.Effect<ToolSchemaView | null, StorageFailure>;
};
readonly providers: {
readonly list: () => Effect.Effect<readonly ProviderKey[]>;
readonly items: (key: ProviderKey) => Effect.Effect<readonly ProviderEntry[], StorageFailure>;
};
readonly policies: {
readonly list: () => Effect.Effect<readonly ToolPolicy[], StorageFailure>;
readonly create: (input: CreateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;
readonly update: (input: UpdateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;
readonly remove: (input: RemoveToolPolicyInput) => Effect.Effect<void, StorageFailure>;
readonly resolve: (address: ToolAddress) => Effect.Effect<EffectivePolicy, StorageFailure>;
};
readonly execute: (
address: ToolAddress,
args: unknown,
options?: InvokeOptions,
) => Effect.Effect<unknown, ExecuteError>;
readonly close: () => Effect.Effect<void, StorageFailure>;
} & PluginExtensions<TPlugins>;
export interface ExecutorDb {
readonly db: FumaDb<any>;
readonly close?: () => Effect.Effect<void, StorageFailure> | Promise<void> | void;
}
export type ExecutorDbInput = FumaDb<any> | ExecutorDb;
export type ExecutorDbFactory = (config: {
readonly tables: FumaTables;
}) => ExecutorDbInput | Effect.Effect<ExecutorDbInput, StorageFailure>;
export interface ExecutorConfig<TPlugins extends readonly AnyPlugin[] = readonly []> {
/** The org / workspace this executor is bound to. `owner: "org"` rows file
* here. */
readonly tenant: Tenant;
/** The acting member, or omit for a pure-org executor (no `owner:"user"`). */
readonly subject?: Subject;
readonly db?: ExecutorDbInput | ExecutorDbFactory;
/**
* Backend for the plugin blob seam (`StorageDeps.blobs`). Defaults to the
* FumaDB `blob` table over `db`. Hosts with an object store hand one in
* (e.g. the R2 store in `@executor-js/cloudflare/blob-store`) so multi-MB
* values stay out of the relational tier.
*/
readonly blobs?: BlobStore;
readonly plugins?: TPlugins;
/** Config-level credential providers, merged with every
* `plugin.credentialProviders`. Config providers register first, so the
* default (first writable) store is selected from them when present. */
readonly providers?: readonly CredentialProvider[];
/**
* How to respond when a tool requests user input mid-invocation. Pass
* `"accept-all"` for tests / non-interactive hosts, or a handler.
*/
readonly onElicitation: OnElicitation;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
/**
* Fetch API implementation for dependencies that cannot consume `httpClientLayer`.
* Prefer `httpClientLayer` for normal SDK and plugin HTTP.
*/
readonly fetch?: typeof globalThis.fetch;
/**
* The OAuth callback URL (`${webBaseUrl}/oauth/callback`) the host serves and
* sends to providers. There is NO localhost default: omit it (or pass
* undefined) only for executors that never run interactive OAuth — the
* redirect-requiring flows then fail loudly instead of guessing a callback.
* Hosts serving OAuth derive this from the request origin / web base URL.
*/
readonly redirectUri?: string;
readonly oauthEndpointUrlPolicy?: OAuthEndpointUrlPolicy;
/**
* Enable the built-in `core-tools` plugin which contributes agent-facing
* static tools over the v2 surface (integrations / connections / policies).
*/
readonly coreTools?: {
readonly webBaseUrl?: string;
readonly orgSlug?: string;
readonly includeProviders?: boolean;
};
}
// ---------------------------------------------------------------------------
// collectTables — return the executor-owned Fuma table set. Plugins persist
// through host-owned facades (`pluginStorage`, `blobs`) instead of contributing
// table definitions, so the schema is fixed and plugin-independent.
// ---------------------------------------------------------------------------
export const collectTables = (): FumaTables => {
validateExecutorOwnerPolicyTables(coreSchema);
return { ...coreSchema };
};
const validateExecutorOwnerPolicyTables = (tables: FumaTables): void => {
for (const [tableKey, tableDef] of Object.entries(tables)) {
assertExecutorOwnerPolicyTable(tableDef, tableKey);
}
};
const validateExecutorDbTables = (required: FumaTables, actual: FumaTables): void => {
const missing = Object.keys(required)
.filter((tableName) => !actual[tableName])
.sort();
if (missing.length === 0) return;
// oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: synchronous startup validation before Executor services are built
throw new StorageError({
message: `Executor database is missing required table definitions: ${missing.join(", ")}`,
cause: {
missing,
available: Object.keys(actual).sort(),
},
});
};
const storageFailureFromUnknown = (message: string, cause: unknown): StorageFailure =>
isStorageFailure(cause) ? cause : new StorageError({ message, cause });
const pluginStorageFailure = (pluginId: string, hook: string, cause: unknown): StorageFailure =>
storageFailureFromUnknown(`${hook} failed for plugin ${pluginId}`, cause);
const createDefaultMemoryDb = (tables: FumaTables): ExecutorDb => {
const version = "1.0.0";
const latestSchema = fumaSchema<string, FumaTables, RelationsMap<FumaTables>>({
version,
tables,
});
const factory = fumadb({
namespace: "executor_memory",
schemas: [latestSchema],
});
// oxlint-disable-next-line executor/no-double-cast -- boundary: fumadb's generic ORM client type doesn't structurally match the FumaDb facade
const db = factory.client(memoryAdapter()).orm(version) as unknown as FumaDb;
return { db };
};
// ---------------------------------------------------------------------------
// JSON helpers + row → public projection conversions
// ---------------------------------------------------------------------------
const decodeJsonFromString = Schema.decodeUnknownOption(Schema.UnknownFromJsonString);
const decodeJsonColumn = (value: unknown): unknown => {
if (value === null || value === undefined) return undefined;
if (typeof value !== "string") return value;
return decodeJsonFromString(value).pipe(Option.getOrElse(() => value));
};
const rowToIntegration = (
row: IntegrationRow,
authMethods: readonly AuthMethodDescriptor[] = [],
displayUrl?: string,
): Integration => ({
slug: IntegrationSlug.make(row.slug),
// Pre-split rows have no `name`; their description WAS the display name.
name: row.name ?? row.description ?? row.slug,
// `description` is now nullable (cleared where it only held a duplicated
// title); present it as "" so the public Integration type stays a string.
description: row.description ?? "",
kind: row.plugin_id,
canRemove: Boolean(row.can_remove),
canRefresh: Boolean(row.can_refresh),
authMethods,
...(displayUrl ? { displayUrl } : {}),
});
const rowToIntegrationRecord = (
row: IntegrationRow,
authMethods: readonly AuthMethodDescriptor[] = [],
): IntegrationRecord => ({
...rowToIntegration(row, authMethods),
config: decodeJsonColumn(row.config),
});
const rowToConnection = (row: ConnectionRow): Connection => {
const owner = row.owner as Owner;
const integration = IntegrationSlug.make(row.integration);
const name = ConnectionName.make(row.name);
return {
owner,
name,
integration,
template: AuthTemplateSlug.make(row.template),
provider: ProviderKey.make(row.provider),
address: connectionAddress(owner, integration, name),
identityLabel: row.identity_label ?? null,
description: row.description ?? null,
expiresAt: row.expires_at == null ? null : Number(row.expires_at),
oauthClient: row.oauth_client == null ? null : OAuthClientSlug.make(String(row.oauth_client)),
oauthClientOwner:
row.oauth_client_owner == null ? null : (String(row.oauth_client_owner) as Owner),
oauthScope: row.oauth_scope == null ? null : String(row.oauth_scope),
};
};
/** The canonical credential variable for a single-secret connection. OAuth tokens
* and the primary apiKey value resolve through it. */
const PRIMARY_INPUT_VARIABLE = "token";
interface NormalizedConnectionInput {
readonly variable: string;
readonly origin: ConnectionInputOrigin;
}
/** Flatten any `ConnectionValueInput` form (single `value`/`from` sugar, pasted
* `values` map, or the canonical per-variable `inputs` map) into a uniform list
* of named origins. */
const normalizeConnectionInputs = (
input: ConnectionValueInput,
): readonly NormalizedConnectionInput[] => {
if ("inputs" in input) {
return Object.entries(input.inputs).map(([variable, origin]) => ({ variable, origin }));
}
if ("values" in input) {
return Object.entries(input.values).map(([variable, value]) => ({
variable,
origin: { value },
}));
}
if ("from" in input) {
return [{ variable: PRIMARY_INPUT_VARIABLE, origin: { from: input.from } }];
}
return [{ variable: PRIMARY_INPUT_VARIABLE, origin: { value: input.value } }];
};
/** Decode a connection row's `item_ids` JSON map (`variable → provider item id`).
* Tolerates the historically-single shape by returning `{}` for anything that
* isn't an object. */
const connectionItemIds = (row: ConnectionRow): Record<string, string> => {
const decoded = decodeJsonColumn(row.item_ids);
if (decoded == null || typeof decoded !== "object") return {};
return decoded as Record<string, string>;
};
// Accepts a projected row (the invoke/list paths select away the heavy
// schema columns); `Tool.inputSchema`/`outputSchema` are optional and stay
// absent for those callers — `tools.schema` is the schema-bearing surface.
const rowToTool = (
row: ToolInvocationRow & Partial<Pick<ToolRow, "input_schema" | "output_schema">>,
annotations?: ToolAnnotations,
): Tool => {
const owner = row.owner as Owner;
const integration = IntegrationSlug.make(row.integration);
const connection = ConnectionName.make(row.connection);
const name = ToolName.make(row.name);
return {
address: toolAddress(owner, integration, connection, name),
owner,
integration,
connection,
name,
pluginId: row.plugin_id,
description: row.description,
inputSchema: decodeJsonColumn(row.input_schema),
outputSchema: decodeJsonColumn(row.output_schema),
annotations: annotations ?? (decodeJsonColumn(row.annotations) as ToolAnnotations | undefined),
};
};
// ---------------------------------------------------------------------------
// Condition builders
// ---------------------------------------------------------------------------
type AnyCb = ConditionBuilder<Record<string, AnyColumn>>;
type CoreTableName = keyof CoreSchema & string;
type CoreRow<TName extends CoreTableName> = FumaRow<CoreSchema[TName]>;
type CoreColumn<TName extends CoreTableName> = keyof CoreRow<TName> & string;
type CoreWhere = (b: AnyCb) => Condition | boolean;
type CoreFindManyOptions<TName extends CoreTableName = CoreTableName> = {
readonly where?: CoreWhere;
readonly limit?: number;
readonly offset?: number;
readonly orderBy?:
| readonly [string, "asc" | "desc"]
| readonly (readonly [string, "asc" | "desc"])[];
/** Column projection (fumadb `select`). Omit for all columns. Use on hot
* paths whose rows carry heavy JSON columns the caller discards — e.g. a
* tool row is ~KBs of schemas but invoke routing needs only the names. */
readonly select?: readonly CoreColumn<TName>[];
};
type CoreFindFirstOptions<TName extends CoreTableName = CoreTableName> = Omit<
CoreFindManyOptions<TName>,
"limit" | "offset"
>;
/** The narrowed row a projected query returns: the selected columns keep
* their types, everything else is absent. */
type CoreProjectedRow<TName extends CoreTableName, TSelect> = TSelect extends readonly (infer K)[]
? Pick<CoreRow<TName>, Extract<K, keyof CoreRow<TName>>>
: CoreRow<TName>;
type LooseStorageDb = {
readonly count: (tableName: string, options?: unknown) => Promise<number>;
readonly create: (
tableName: string,
row: Record<string, unknown>,
) => Promise<Record<string, unknown>>;
readonly createMany: (
tableName: string,
rows: readonly Record<string, unknown>[],
) => Promise<readonly unknown[]>;
readonly deleteMany: (tableName: string, options?: unknown) => Promise<void>;
readonly findFirst: (
tableName: string,
options?: unknown,
) => Promise<Record<string, unknown> | null>;
readonly findMany: (
tableName: string,
options?: unknown,
) => Promise<readonly Record<string, unknown>[]>;
readonly updateMany: (tableName: string, options: unknown) => Promise<void>;
};
const asLooseStorageDb = (db: unknown): LooseStorageDb => db as LooseStorageDb;
const makeCoreDb = (fuma: ReturnType<typeof makeFumaClient>) => ({
count: <TName extends CoreTableName>(
tableName: TName,
options?: { readonly where?: CoreWhere },
): Effect.Effect<number, StorageFailure> =>
fuma.use(`${tableName}.count`, (db) => asLooseStorageDb(db).count(tableName, options)),
create: <TName extends CoreTableName>(
tableName: TName,
row: Record<string, unknown>,
): Effect.Effect<CoreRow<TName>, StorageFailure> =>
fuma.use(`${tableName}.create`, (db) =>
asLooseStorageDb(db).create(tableName, row),
) as Effect.Effect<CoreRow<TName>, StorageFailure>,
createMany: <TName extends CoreTableName>(
tableName: TName,
rows: readonly Record<string, unknown>[],
): Effect.Effect<void, StorageFailure> =>
rows.length === 0
? Effect.void
: fuma
.use(`${tableName}.createMany`, (db) => asLooseStorageDb(db).createMany(tableName, rows))
.pipe(Effect.asVoid),
deleteMany: <TName extends CoreTableName>(
tableName: TName,
options: { readonly where?: CoreWhere } = {},
): Effect.Effect<void, StorageFailure> =>
fuma.use(`${tableName}.deleteMany`, (db) =>
asLooseStorageDb(db).deleteMany(tableName, options),
),
findFirst: <TName extends CoreTableName, const TOptions extends CoreFindFirstOptions<TName>>(
tableName: TName,
options: TOptions,
): Effect.Effect<CoreProjectedRow<TName, TOptions["select"]> | null, StorageFailure> =>
fuma.use(`${tableName}.findFirst`, (db) =>
asLooseStorageDb(db).findFirst(tableName, options),
) as Effect.Effect<CoreProjectedRow<TName, TOptions["select"]> | null, StorageFailure>,
findMany: <TName extends CoreTableName, const TOptions extends CoreFindManyOptions<TName>>(
tableName: TName,
options: TOptions = {} as TOptions,
): Effect.Effect<readonly CoreProjectedRow<TName, TOptions["select"]>[], StorageFailure> =>
fuma.use(`${tableName}.findMany`, (db) =>
asLooseStorageDb(db).findMany(tableName, options),
) as Effect.Effect<readonly CoreProjectedRow<TName, TOptions["select"]>[], StorageFailure>,
updateMany: <TName extends CoreTableName>(
tableName: TName,
options: {
readonly where?: CoreWhere;
readonly set: Record<string, unknown>;
},
): Effect.Effect<void, StorageFailure> =>
fuma.use(`${tableName}.updateMany`, (db) =>
asLooseStorageDb(db).updateMany(tableName, options),
),
});
type CoreDb = ReturnType<typeof makeCoreDb>;
// ---------------------------------------------------------------------------
// Plugin storage facade — owner-scoped (was scope-keyed). Reads fall through
// [user, org]; writes/deletes name an explicit owner.
// ---------------------------------------------------------------------------
const pluginStorageEntryFromRow = <T>(row: CoreRow<"plugin_storage">): PluginStorageEntry<T> => ({
id: pluginStorageId({
pluginId: row.plugin_id,
collection: row.collection,
key: row.key,
}),
owner: row.owner as Owner,
pluginId: row.plugin_id,
collection: row.collection,
key: row.key,
data: row.data as T,
createdAt: row.created_at instanceof Date ? row.created_at : new Date(row.created_at),
updatedAt: row.updated_at instanceof Date ? row.updated_at : new Date(row.updated_at),
});
const pluginStorageIndexSpecFields = (spec: PluginStorageRuntimeIndexSpec): readonly string[] =>
typeof spec === "string" ? [spec] : spec;
const pluginStorageCollectionIndexedFields = (
definition: PluginStorageRuntimeCollectionDefinition,
): ReadonlySet<string> =>
new Set(definition.indexes.flatMap((spec) => pluginStorageIndexSpecFields(spec)));
const pluginStorageQueryValidationError = (
definition: PluginStorageRuntimeCollectionDefinition,
query: PluginStorageCollectionQueryInput<PluginStorageCollectionDefinition> | undefined,
): StorageError | null => {
if (!query) return null;
const indexedFields = pluginStorageCollectionIndexedFields(definition);
const fields = new Set<string>([
...Object.keys(query.where ?? {}),
...(query.orderBy ?? []).map((order) => order.field),
]);
for (const field of fields) {
if (!indexedFields.has(field)) {
return new StorageError({
message: `Plugin storage collection "${definition.name}" cannot query field "${field}" because it is not declared as an index`,
cause: undefined,
});
}
}
if (query.limit !== undefined && (!Number.isInteger(query.limit) || query.limit < 0)) {
return new StorageError({
message: `Plugin storage collection "${definition.name}" received an invalid query limit`,
cause: undefined,
});
}
if (query.offset !== undefined && (!Number.isInteger(query.offset) || query.offset < 0)) {
return new StorageError({
message: `Plugin storage collection "${definition.name}" received an invalid query offset`,
cause: undefined,
});
}
return null;
};
const isPluginStorageRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
value !== null && typeof value === "object" && !Array.isArray(value);
const pluginStorageWhereOperators = ["eq", "in", "gt", "gte", "lt", "lte"] as const;
const isPluginStorageWhereFilter = (value: unknown): value is Readonly<Record<string, unknown>> =>
isPluginStorageRecord(value) && pluginStorageWhereOperators.some((operator) => operator in value);
const pluginStorageComparableValue = (value: unknown): string | number | boolean | null => {
if (value instanceof Date) return value.getTime();
if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
return value;
}
if (value == null) return null;
return JSON.stringify(value);
};
const comparePluginStorageValues = (left: unknown, right: unknown): number => {
const leftValue = pluginStorageComparableValue(left);
const rightValue = pluginStorageComparableValue(right);
if (leftValue === rightValue) return 0;
if (leftValue === null) return -1;
if (rightValue === null) return 1;
return leftValue < rightValue ? -1 : 1;
};
const pluginStorageDataField = (data: unknown, field: string): unknown =>
isPluginStorageRecord(data) ? data[field] : undefined;
const matchesWhereOperator = (operator: string, value: unknown, operand: unknown): boolean => {
if (operator === "eq") return comparePluginStorageValues(value, operand) === 0;
if (operator === "in") {
return (
Array.isArray(operand) &&
operand.some((item) => comparePluginStorageValues(value, item) === 0)
);
}
if (operator === "gt") return comparePluginStorageValues(value, operand) > 0;
if (operator === "gte") return comparePluginStorageValues(value, operand) >= 0;
if (operator === "lt") return comparePluginStorageValues(value, operand) < 0;
if (operator === "lte") return comparePluginStorageValues(value, operand) <= 0;
return false;
};
const matchesWhereOperators = (
value: unknown,
filter: Readonly<Record<string, unknown>>,
): boolean => {
for (const [operator, operand] of Object.entries(filter)) {
if (!matchesWhereOperator(operator, value, operand)) return false;
}
return true;
};
const rowMatchesPluginStorageWhere = (
row: CoreRow<"plugin_storage">,
where: Readonly<Record<string, unknown>> | undefined,
): boolean => {
if (!where) return true;
for (const [field, condition] of Object.entries(where)) {
const value = pluginStorageDataField(row.data, field);
if (isPluginStorageWhereFilter(condition)) {
if (!matchesWhereOperators(value, condition)) return false;
} else if (comparePluginStorageValues(value, condition) !== 0) {
return false;
}
}
return true;
};
const makePluginStorageFacade = (input: {
readonly core: CoreDb;
readonly pluginId: string;
readonly owner: OwnerBinding;
}): PluginStorageFacade => {
// Owner partitions: org always, plus this subject's user partition.
const readOwners: readonly Owner[] = input.owner.subject == null ? ["org"] : ["user", "org"];
const ownerSubject = (owner: Owner): { owner: Owner; subject: string } | null => {
if (owner === "org") return { owner: "org", subject: ORG_SUBJECT };
if (input.owner.subject == null) return null;
return { owner: "user", subject: String(input.owner.subject) };
};
const tenant = String(input.owner.tenant);
const whereFor =
(collection: string, key?: string): CoreWhere =>
(b: AnyCb) =>
b.and(
b("plugin_id", "=", input.pluginId),
b("collection", "=", collection),
key === undefined ? true : b("key", "=", key),
);
const whereOwner = (owner: Owner, collection: string, key: string): CoreWhere => {
const os = ownerSubject(owner);
return (b: AnyCb) =>
b.and(
b("plugin_id", "=", input.pluginId),
b("collection", "=", collection),
b("key", "=", key),
b("owner", "=", owner),
b("subject", "=", os ? os.subject : ORG_SUBJECT),
);
};
const ownerRank = (owner: Owner): number => readOwners.indexOf(owner);
const sortByOwnerPrecedence = (rows: readonly CoreRow<"plugin_storage">[]) =>
[...rows].sort((left, right) => {
const l = ownerRank(left.owner as Owner);
const r = ownerRank(right.owner as Owner);
return l - r || left.key.localeCompare(right.key);
});
const getVisible = <T>(collection: string, key: string) =>
input.core.findMany("plugin_storage", { where: whereFor(collection, key) }).pipe(
Effect.map((rows) => sortByOwnerPrecedence(rows)[0] ?? null),
Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null)),
);
const getForOwnerImpl = <T>(owner: Owner, collection: string, key: string) =>
input.core
.findFirst("plugin_storage", {
where: whereOwner(owner, collection, key),
})
.pipe(Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null)));
const putImpl = <T>(owner: Owner, collection: string, key: string, data: unknown) =>
Effect.gen(function* () {
const os = ownerSubject(owner);
if (!os) {
return yield* new StorageError({
message: `Cannot write plugin storage for owner "user": executor has no subject.`,
cause: undefined,
});
}
const existing = yield* input.core.findFirst("plugin_storage", {
where: whereOwner(owner, collection, key),
});
const now = new Date();
if (existing) {
yield* input.core.updateMany("plugin_storage", {
where: whereOwner(owner, collection, key),
set: { data, updated_at: now },
});
return pluginStorageEntryFromRow<T>({
...existing,
data,
updated_at: now,
});
}
const created = yield* input.core.create("plugin_storage", {
tenant,
owner: os.owner,
subject: os.subject,
plugin_id: input.pluginId,
collection,
key,
data,
created_at: now,
updated_at: now,
});
return pluginStorageEntryFromRow<T>(created);
});
const removeImpl = (owner: Owner, collection: string, key: string) =>
Effect.gen(function* () {
const os = ownerSubject(owner);
if (!os) {
return yield* new StorageError({
message: `Cannot delete plugin storage for owner "user": executor has no subject.`,
cause: undefined,
});
}
yield* input.core.deleteMany("plugin_storage", {
where: whereOwner(owner, collection, key),
});
});
const keysByCollection = (
entries: readonly { readonly collection: string; readonly key: string }[],
) => {
const grouped = new Map<string, Set<string>>();
for (const entry of entries) {
const keys = grouped.get(entry.collection);
if (keys) {
keys.add(entry.key);
} else {
grouped.set(entry.collection, new Set([entry.key]));
}
}
return grouped;
};
const deleteManyImpl = (
owner: Owner,
subject: string,
entries: readonly { readonly collection: string; readonly key: string }[],
) =>
Effect.gen(function* () {
for (const [collection, keys] of keysByCollection(entries)) {
const uniqueKeys = [...keys];
for (
let offset = 0;
offset < uniqueKeys.length;
offset += PLUGIN_STORAGE_DELETE_KEY_BATCH_SIZE
) {
const batchKeys = uniqueKeys.slice(offset, offset + PLUGIN_STORAGE_DELETE_KEY_BATCH_SIZE);
yield* input.core.deleteMany("plugin_storage", {
where: (b) =>
b.and(
b("plugin_id", "=", input.pluginId),
b("collection", "=", collection),
b("key", "in", batchKeys),
b("owner", "=", owner),
b("subject", "=", subject),
),
});
}
}
});
const putManyImpl = (
owner: Owner,
entries: readonly {
readonly collection: string;
readonly key: string;
readonly data: unknown;
}[],
) =>
Effect.gen(function* () {
const os = ownerSubject(owner);
if (!os) {
return yield* new StorageError({
message: `Cannot write plugin storage for owner "user": executor has no subject.`,
cause: undefined,
});
}
const entriesById = new Map(
entries.map((entry) => [
pluginStorageId({
pluginId: input.pluginId,
collection: entry.collection,
key: entry.key,
}),
entry,
]),
);
const uniqueEntries = [...entriesById.values()];
if (uniqueEntries.length === 0) return;
yield* deleteManyImpl(owner, os.subject, uniqueEntries);
const now = new Date();
for (
let offset = 0;
offset < uniqueEntries.length;
offset += PLUGIN_STORAGE_CREATE_ROW_BATCH_SIZE
) {
const batchEntries = uniqueEntries.slice(
offset,
offset + PLUGIN_STORAGE_CREATE_ROW_BATCH_SIZE,
);