apps 0.0.1-beta.115 → 0.0.1-beta.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  prepareElicitation
3
- } from "./chunk-27DVBAB5.js";
3
+ } from "./chunk-OSVCX4MV.js";
4
4
  import {
5
5
  failOnNetworkRefusal
6
6
  } from "./chunk-HLMJBE4T.js";
@@ -2,9 +2,10 @@ import {
2
2
  skillFromFiles
3
3
  } from "./chunk-PBGPES67.js";
4
4
  import {
5
+ PartialListing,
5
6
  joinPath,
6
7
  mergeMeta
7
- } from "./chunk-ZXG7RMCB.js";
8
+ } from "./chunk-OIMMQRYE.js";
8
9
  import {
9
10
  isShortenedStated,
10
11
  parseProviderError,
@@ -831,17 +832,32 @@ var readCatalog = (root, options) => Effect_exports.gen(function* () {
831
832
  const tools = [];
832
833
  const routers = [];
833
834
  const { wanted, secrets } = options;
835
+ const listing = (read) => sourced(
836
+ () => read().pipe(
837
+ Effect_exports.map((tools2) => ({ tools: tools2, error: void 0 })),
838
+ Effect_exports.catchIf(
839
+ Schema_exports.is(PartialListing),
840
+ ({ tools: tools2, error }) => Effect_exports.succeed({ tools: tools2, error: safeFailure(error, secrets) })
841
+ )
842
+ ),
843
+ secrets
844
+ );
834
845
  const readSource = (source, path, relative) => Effect_exports.gen(function* () {
835
846
  const describe = source.describe;
836
- const [meta, listed] = yield* Effect_exports.all(
847
+ const [meta, { tools: listed, error }] = yield* Effect_exports.all(
837
848
  [
838
849
  routerMeta(source, secrets),
839
- options.summary && source.summaries !== void 0 ? sourced(source.summaries, secrets) : relative !== void 0 && describe !== void 0 ? sourced(
850
+ options.summary && source.summaries !== void 0 ? listing(source.summaries) : relative !== void 0 && describe !== void 0 ? sourced(
840
851
  () => Effect_exports.forEach(relative, (name) => describe(name), {
841
852
  concurrency: "unbounded"
842
853
  }),
843
854
  secrets
844
- ).pipe(Effect_exports.map((tools2) => tools2.filter((tool) => tool !== void 0))) : sourced(source.list, secrets)
855
+ ).pipe(
856
+ Effect_exports.map((tools2) => ({
857
+ tools: tools2.filter((tool) => tool !== void 0),
858
+ error: void 0
859
+ }))
860
+ ) : listing(source.list)
845
861
  ],
846
862
  { concurrency: "unbounded" }
847
863
  );
@@ -861,18 +877,18 @@ var readCatalog = (root, options) => Effect_exports.gen(function* () {
861
877
  annotations: { ...tool.annotations, readOnlyHint: readOnly }
862
878
  });
863
879
  }
864
- return { meta, found };
880
+ return { meta, found, error };
865
881
  });
866
882
  const include = (source, path, relative) => Effect_exports.gen(function* () {
867
883
  if (path === "") {
868
- const { meta, found } = yield* readSource(source, path, relative);
884
+ const { meta, found, error } = yield* readSource(source, path, relative);
869
885
  tools.push(...found);
870
- return { meta, error: void 0 };
886
+ return { meta, error };
871
887
  }
872
888
  const result = yield* Effect_exports.result(readSource(source, path, relative));
873
889
  if (Result_exports.isFailure(result)) return { meta: source.overrides, error: result.failure };
874
890
  tools.push(...result.success.found);
875
- return { meta: result.success.meta, error: void 0 };
891
+ return { meta: result.success.meta, error: result.success.error };
876
892
  });
877
893
  const visit = (node, path) => Effect_exports.gen(function* () {
878
894
  if (path !== "" || wanted === void 0 && node.meta !== void 0)
@@ -905,8 +921,8 @@ var readCatalog = (root, options) => Effect_exports.gen(function* () {
905
921
  if (root?.kind === "router") yield* visit(root, "");
906
922
  else if (root?.kind === "dynamic" && options.scheduled !== true) {
907
923
  const read = yield* include(root, "", wanted === void 0 ? void 0 : [...wanted]);
908
- if (wanted === void 0 && read.meta !== void 0)
909
- routers.push(yield* entry("", read.meta));
924
+ if (wanted === void 0 && (read.meta !== void 0 || read.error !== void 0))
925
+ routers.push(yield* entry("", read.meta, read.error));
910
926
  }
911
927
  return { tools, routers };
912
928
  });
@@ -2,7 +2,7 @@ import {
2
2
  declaredOperations,
3
3
  nativeOperation,
4
4
  nativeRouter
5
- } from "./chunk-ZXG7RMCB.js";
5
+ } from "./chunk-OIMMQRYE.js";
6
6
  import {
7
7
  fromPromise,
8
8
  method
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  fixedRouter
3
- } from "./chunk-7XZKCNGB.js";
3
+ } from "./chunk-6A6P5TYV.js";
4
4
  import {
5
5
  nativeOperation,
6
6
  operationDeclaration,
7
7
  routerDeclaration
8
- } from "./chunk-ZXG7RMCB.js";
8
+ } from "./chunk-OIMMQRYE.js";
9
9
 
10
10
  // src/implementation/protocol-operations.ts
11
11
  var protocolOperations = (operations, kinds = {}) => {
@@ -0,0 +1,572 @@
1
+ import {
2
+ accountProviderError,
3
+ fromPromise
4
+ } from "./chunk-OIH73VFM.js";
5
+ import {
6
+ HostedTool,
7
+ HostedToolSummary,
8
+ RouterKey,
9
+ RouterMeta,
10
+ reservedRouterKeys
11
+ } from "./chunk-2RGJMA7N.js";
12
+ import {
13
+ combineJsonSchemas,
14
+ decoderOf,
15
+ importedJsonSchema,
16
+ once,
17
+ schemaArgument,
18
+ withLazyJsonSchemaDocument
19
+ } from "./chunk-VAI3EVCS.js";
20
+ import {
21
+ JsonObject
22
+ } from "./chunk-7HG422GB.js";
23
+ import {
24
+ Effect_exports,
25
+ Result_exports,
26
+ Schema_exports
27
+ } from "./chunk-ZKDXML77.js";
28
+
29
+ // src/implementation/operations.ts
30
+ var NativeOperation = /* @__PURE__ */ Symbol("apps.Operation");
31
+ var NativeRouterKey = /* @__PURE__ */ Symbol("apps.Router");
32
+ var operationDeclaration = (operation) => ({
33
+ kind: operation.kind,
34
+ [NativeOperation]: operation
35
+ });
36
+ var nativeOperation = (value) => {
37
+ if (typeof value !== "object" || value === null || !(NativeOperation in value)) return void 0;
38
+ return value[NativeOperation];
39
+ };
40
+ var operationOptions = (options) => {
41
+ const approval = options.approval;
42
+ return {
43
+ ...options.description === void 0 ? {} : { description: options.description },
44
+ ...options.title === void 0 ? {} : { title: options.title },
45
+ ...options.annotations === void 0 ? {} : { annotations: options.annotations },
46
+ ...options._meta === void 0 ? {} : { _meta: options._meta },
47
+ input: decoderOf(options.input),
48
+ ...approval === void 0 ? {} : {
49
+ approval: (context) => fromPromise(async () => approval(context), "approval")()
50
+ }
51
+ };
52
+ };
53
+ var approvedOperation = (operation, approval) => {
54
+ const copy = Object.defineProperties({}, Object.getOwnPropertyDescriptors(operation));
55
+ return Object.defineProperty(copy, "approval", {
56
+ enumerable: true,
57
+ value: (context) => fromPromise(async () => approval(context), "approval")()
58
+ });
59
+ };
60
+ var withApproval = (operation, approval) => (
61
+ // SAFETY: `Approved` is a type-only mark; the native operation now carries the approval.
62
+ {
63
+ ...operation,
64
+ [NativeOperation]: approvedOperation(operation[NativeOperation], approval)
65
+ }
66
+ );
67
+ var toolAnnotations = (operation) => nativeOperation(operation)?.annotations;
68
+ var make = (kind, options, run) => operationDeclaration({
69
+ ...operationOptions({ ...options, input: schemaArgument(options.input, `The ${kind} input`) }),
70
+ kind,
71
+ // The host always validates JSON serialization, even without a stronger output declaration.
72
+ ...options.output === void 0 ? {} : { output: decoderOf(schemaArgument(options.output, `The ${kind} output`)) },
73
+ // SAFETY: defineApp checks the handler context against its requirements.
74
+ // The host validates account bindings and creates the matching storage facade.
75
+ run: (context, input) => fromPromise(run, "handler")(context, input)
76
+ });
77
+ var query = (options, run) => make("query", options, run);
78
+ function mutation(options, run) {
79
+ return make("mutation", options, run);
80
+ }
81
+
82
+ // src/implementation/router.ts
83
+ var routerDeclaration = (node) => ({
84
+ [NativeRouterKey]: node
85
+ });
86
+ var nativeRouter = (value) => {
87
+ if (typeof value !== "object" || value === null || !(NativeRouterKey in value)) return void 0;
88
+ return value[NativeRouterKey];
89
+ };
90
+ var nativeNode = (value) => nativeOperation(value) ?? nativeRouter(value);
91
+ var metaOf = (options) => {
92
+ if (options === void 0) return void 0;
93
+ const defined = Object.fromEntries(
94
+ Object.entries(options).filter(([, value]) => value !== void 0)
95
+ );
96
+ return Object.keys(defined).length === 0 ? void 0 : Schema_exports.decodeUnknownSync(RouterMeta)(defined);
97
+ };
98
+ var mergeMeta = (base, override) => base === void 0 ? override : override === void 0 ? base : { ...base, ...override };
99
+ function router(children, options) {
100
+ const meta = metaOf(options);
101
+ const existing = nativeRouter(children);
102
+ if (existing !== void 0)
103
+ return routerDeclaration(
104
+ existing.kind === "router" ? { ...existing, ...withMeta(mergeMeta(existing.meta, meta)) } : { ...existing, ...withOverrides(mergeMeta(existing.overrides, meta)) }
105
+ );
106
+ const nodes = {};
107
+ for (const [key, value] of Object.entries(children)) {
108
+ if (reservedRouterKeys.has(key)) throw new Error(`Router key "${key}" is reserved`);
109
+ if (!Schema_exports.is(RouterKey)(key))
110
+ throw new Error(`Router key "${key}" must start with a letter or _ and contain no dots`);
111
+ const node = nativeNode(value);
112
+ if (node === void 0)
113
+ throw new Error(`Router key "${key}" must be a query, mutation or router`);
114
+ nodes[key] = node;
115
+ }
116
+ return routerDeclaration({ kind: "router", ...withMeta(meta), children: nodes });
117
+ }
118
+ var withMeta = (meta) => meta === void 0 ? {} : { meta };
119
+ var withOverrides = (overrides) => overrides === void 0 ? {} : { overrides };
120
+ var dynamicRouter = (source) => {
121
+ const meta = source.meta;
122
+ return routerDeclaration({
123
+ kind: "dynamic",
124
+ ...meta === void 0 ? {} : {
125
+ meta: () => fromPromise(async () => meta(), "router")().pipe(
126
+ Effect_exports.flatMap((options) => Schema_exports.decodeUnknownEffect(RouterMeta)(options))
127
+ )
128
+ },
129
+ list: () => fromPromise(async () => source.list(), "router")().pipe(
130
+ Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(Schema_exports.Array(HostedTool)))
131
+ ),
132
+ resolve: (name) => fromPromise(async () => source.resolve(name), "router")().pipe(
133
+ Effect_exports.map((value) => {
134
+ if (value === void 0) return void 0;
135
+ const operation = nativeOperation(value);
136
+ if (operation === void 0) throw new Error("Expected an operation declaration");
137
+ return operation;
138
+ })
139
+ )
140
+ });
141
+ };
142
+ var joinPath = (path, name) => path === "" ? name : `${path}.${name}`;
143
+ var locate = (root, name) => {
144
+ if (root?.kind === "dynamic") return { kind: "dynamic", source: root, router: "", name };
145
+ let current = root;
146
+ let path = "";
147
+ let rest = name;
148
+ while (current !== void 0) {
149
+ const dot = rest.indexOf(".");
150
+ const key = dot < 0 ? rest : rest.slice(0, dot);
151
+ const child = Object.hasOwn(current.children, key) ? current.children[key] : void 0;
152
+ if (child === void 0) return void 0;
153
+ const remaining = dot < 0 ? void 0 : rest.slice(dot + 1);
154
+ switch (child.kind) {
155
+ case "query":
156
+ case "mutation":
157
+ return remaining === void 0 ? { kind: "operation", operation: child, router: path } : void 0;
158
+ case "dynamic":
159
+ return remaining === void 0 || remaining === "" ? void 0 : { kind: "dynamic", source: child, router: joinPath(path, key), name: remaining };
160
+ case "router":
161
+ if (remaining === void 0) return void 0;
162
+ current = child;
163
+ path = joinPath(path, key);
164
+ rest = remaining;
165
+ }
166
+ }
167
+ return void 0;
168
+ };
169
+ var declaredOperations = (root, path = "") => Object.entries(root?.children ?? {}).flatMap(([key, child]) => {
170
+ const name = joinPath(path, key);
171
+ switch (child.kind) {
172
+ case "query":
173
+ case "mutation":
174
+ return [{ name, router: path, operation: child }];
175
+ case "router":
176
+ return declaredOperations(child, name);
177
+ case "dynamic":
178
+ return [];
179
+ }
180
+ });
181
+ var withApprovals = (source, policy) => {
182
+ const native = nativeRouter(source);
183
+ if (native === void 0) throw new Error("withApprovals expects a router");
184
+ const operation = (node, name) => {
185
+ const approval = policy(operationDeclaration(node), name);
186
+ return approval === void 0 ? node : approvedOperation(node, approval);
187
+ };
188
+ const child = (node, name) => {
189
+ switch (node.kind) {
190
+ case "query":
191
+ case "mutation":
192
+ return operation(node, name);
193
+ case "router":
194
+ case "dynamic":
195
+ return walk(node, name);
196
+ }
197
+ };
198
+ const walk = (node, path) => node.kind === "dynamic" ? {
199
+ ...node,
200
+ resolve: (name) => node.resolve(name).pipe(
201
+ Effect_exports.flatMap(
202
+ (resolved) => resolved === void 0 ? Effect_exports.succeed(void 0) : Effect_exports.try({
203
+ try: () => operation(resolved, joinPath(path, name)),
204
+ catch: (error) => error
205
+ })
206
+ )
207
+ )
208
+ } : {
209
+ ...node,
210
+ children: Object.fromEntries(
211
+ Object.entries(node.children).map(([key, value]) => [
212
+ key,
213
+ child(value, joinPath(path, key))
214
+ ])
215
+ )
216
+ };
217
+ return routerDeclaration(walk(native, ""));
218
+ };
219
+ var renameTools = (source, rename) => {
220
+ const native = nativeRouter(source);
221
+ if (native?.kind !== "dynamic") throw new Error("renameTools expects a protocol router");
222
+ const exposed = (tools) => {
223
+ const seen = /* @__PURE__ */ new Set();
224
+ return tools.flatMap((tool) => {
225
+ const name = rename(tool.name);
226
+ if (name === void 0 || seen.has(name)) return [];
227
+ seen.add(name);
228
+ return [{ ...tool, name, source: tool.name }];
229
+ });
230
+ };
231
+ const listed = native.summaries ?? native.list;
232
+ const original = (name) => listed().pipe(Effect_exports.map((tools) => exposed(tools).find((tool) => tool.name === name)?.source));
233
+ const strip = ({
234
+ source: _source,
235
+ ...tool
236
+ }) => tool;
237
+ return routerDeclaration({
238
+ ...native,
239
+ list: () => native.list().pipe(Effect_exports.map((tools) => exposed(tools).map(strip))),
240
+ ...native.summaries === void 0 ? {} : {
241
+ summaries: () => listed().pipe(Effect_exports.map((tools) => exposed(tools).map(strip)))
242
+ },
243
+ describe: (name) => original(name).pipe(
244
+ Effect_exports.flatMap(
245
+ (found) => found === void 0 ? Effect_exports.succeed(void 0) : native.describe?.(found) ?? native.list().pipe(Effect_exports.map((tools) => tools.find((tool) => tool.name === found)))
246
+ ),
247
+ Effect_exports.map((tool) => tool === void 0 ? void 0 : { ...tool, name })
248
+ ),
249
+ resolve: (name) => original(name).pipe(
250
+ Effect_exports.flatMap(
251
+ (found) => found === void 0 ? Effect_exports.succeed(void 0) : native.resolve(found)
252
+ )
253
+ )
254
+ });
255
+ };
256
+
257
+ // src/implementation/account-router.ts
258
+ var PartialListing = class extends Schema_exports.TaggedError()("PartialListing", {
259
+ tools: Schema_exports.Array(Schema_exports.Unknown),
260
+ error: Schema_exports.Unknown
261
+ }) {
262
+ };
263
+ var decoderDocument = (decoder) => {
264
+ const imported = importedJsonSchema(decoder);
265
+ if (imported !== void 0) return Schema_exports.decodeUnknownSync(JsonObject)(imported);
266
+ const document = Schema_exports.toJsonSchemaDocument(decoder);
267
+ return Schema_exports.decodeUnknownSync(JsonObject)({ ...document.schema, $defs: document.definitions });
268
+ };
269
+ var accountBranches = (variants) => {
270
+ const groups = /* @__PURE__ */ new Map();
271
+ for (const [accountId, schema] of variants) {
272
+ const key = JSON.stringify(schema);
273
+ const group = groups.get(key);
274
+ if (group === void 0) groups.set(key, { schema, first: accountId, rest: [] });
275
+ else group.rest.push(accountId);
276
+ }
277
+ const branches = [...groups.values()];
278
+ const { $defs, schemas } = combineJsonSchemas(
279
+ branches.map(({ schema }) => schema),
280
+ (index) => `#/anyOf/${index}/properties/input`
281
+ );
282
+ return {
283
+ type: "object",
284
+ ...$defs === void 0 ? {} : { $defs },
285
+ anyOf: schemas.map((input, index) => {
286
+ const { first, rest } = branches[index];
287
+ return {
288
+ type: "object",
289
+ properties: {
290
+ accountId: rest.length === 0 ? { type: "string", const: first } : { type: "string", enum: [first, ...rest] },
291
+ input
292
+ },
293
+ required: ["accountId", "input"]
294
+ };
295
+ })
296
+ };
297
+ };
298
+ var outputBranches = (outputs) => {
299
+ const { $defs, schemas } = combineJsonSchemas(
300
+ [...new Map(outputs.map((output) => [JSON.stringify(output), output])).values()],
301
+ (index) => `#/anyOf/${index}`
302
+ );
303
+ return { ...$defs === void 0 ? {} : { $defs }, anyOf: schemas };
304
+ };
305
+ var declaresOutput = (operation) => {
306
+ if (operation.output !== void 0) return true;
307
+ const property = Object.getOwnPropertyDescriptor(operation, "outputSchema");
308
+ return property !== void 0 && (property.get !== void 0 || property.value !== void 0);
309
+ };
310
+ var outputDocument = (operation) => operation.output === void 0 ? operation.outputSchema : decoderDocument(operation.output);
311
+ var combineOperation = (accounts, failed = /* @__PURE__ */ new Map()) => {
312
+ const variants = [...accounts.values()];
313
+ const first = variants[0];
314
+ if (first === void 0) throw new Error("An account operation must have at least one account");
315
+ const kind = variants.every((operation) => operation.kind === "query") ? "query" : "mutation";
316
+ const select = (input2) => {
317
+ const operation = accounts.get(input2.accountId);
318
+ if (operation === void 0)
319
+ throw new Error("Account selection must be decoded before execution");
320
+ return operation;
321
+ };
322
+ const input = Schema_exports.Union([
323
+ ...[...accounts].map(
324
+ ([accountId, operation]) => Schema_exports.Struct({ accountId: Schema_exports.Literal(accountId), input: operation.input })
325
+ ),
326
+ ...[...failed.keys()].map(
327
+ (accountId) => Schema_exports.Struct({ accountId: Schema_exports.Literal(accountId), input: Schema_exports.Unknown })
328
+ )
329
+ ]);
330
+ const inputSchema = () => accountBranches(
331
+ [...accounts].map(([accountId, operation]) => [accountId, decoderDocument(operation.input)])
332
+ );
333
+ const declaration = operationDeclaration({
334
+ kind,
335
+ ...first.description === void 0 ? {} : { description: first.description },
336
+ ...first.title === void 0 ? {} : { title: first.title },
337
+ ...first.annotations === void 0 || !variants.every(
338
+ (operation) => JSON.stringify(operation.annotations) === JSON.stringify(first.annotations)
339
+ ) ? {} : { annotations: first.annotations },
340
+ ...first._meta === void 0 || !variants.every((operation) => JSON.stringify(operation._meta) === JSON.stringify(first._meta)) ? {} : { _meta: first._meta },
341
+ input: withLazyJsonSchemaDocument(input, inputSchema),
342
+ approval: (context) => {
343
+ if (failed.has(context.toolInput.accountId)) return Effect_exports.succeed("approved");
344
+ const operation = select(context.toolInput);
345
+ return operation.approval === void 0 ? Effect_exports.succeed("approved") : operation.approval({ ...context, toolInput: context.toolInput.input });
346
+ },
347
+ run: (context, input2) => {
348
+ if (failed.has(input2.accountId))
349
+ return Effect_exports.fail(accountProviderError(failed.get(input2.accountId), input2.accountId));
350
+ const operation = select(input2);
351
+ return operation.run(context, input2.input).pipe(
352
+ Effect_exports.mapError((error) => accountProviderError(error, input2.accountId)),
353
+ Effect_exports.flatMap(
354
+ (output) => operation.output === void 0 ? Effect_exports.succeed(output) : Schema_exports.decodeUnknownEffect(operation.output)(output)
355
+ )
356
+ );
357
+ }
358
+ });
359
+ if (variants.every(declaresOutput)) {
360
+ const outputSchema = once(
361
+ () => outputBranches(
362
+ variants.flatMap((operation) => {
363
+ const output = outputDocument(operation);
364
+ return output === void 0 ? [] : [output];
365
+ })
366
+ )
367
+ );
368
+ const native2 = nativeOperation(declaration);
369
+ if (native2 !== void 0)
370
+ Object.defineProperty(native2, "outputSchema", { enumerable: true, get: outputSchema });
371
+ }
372
+ const native = nativeOperation(declaration);
373
+ if (native === void 0) throw new Error("Expected a combined operation");
374
+ return native;
375
+ };
376
+ var sameAcross = (key, variants) => {
377
+ const first = variants[0]?.[1][key];
378
+ return first !== void 0 && variants.every(([, tool]) => JSON.stringify(tool[key]) === JSON.stringify(first)) ? { [key]: first } : {};
379
+ };
380
+ var mergeSummary = (name, variants) => {
381
+ const first = variants[0]?.[1];
382
+ if (first === void 0) throw new Error("Expected a source operation");
383
+ return Schema_exports.decodeUnknownSync(HostedToolSummary)({
384
+ name,
385
+ description: first.description,
386
+ ...first.title === void 0 ? {} : { title: first.title },
387
+ readOnly: variants.every(([, tool]) => tool.readOnly === true),
388
+ ...variants.every(([, tool]) => tool.kindConfirmed === true) ? { kindConfirmed: true } : {},
389
+ ...sameAcross("annotations", variants)
390
+ });
391
+ };
392
+ var merge = (name, variants) => Schema_exports.decodeUnknownSync(HostedTool)({
393
+ ...mergeSummary(name, variants),
394
+ inputSchema: accountBranches(
395
+ variants.map(([accountId, tool]) => [accountId, tool.inputSchema])
396
+ ),
397
+ ...variants.every(([, tool]) => tool.outputSchema !== void 0) ? {
398
+ outputSchema: outputBranches(
399
+ variants.flatMap(
400
+ ([, tool]) => tool.outputSchema === void 0 ? [] : [tool.outputSchema]
401
+ )
402
+ )
403
+ } : {},
404
+ ...sameAcross("_meta", variants)
405
+ });
406
+ var eachAccount = (sources, read) => Effect_exports.gen(function* () {
407
+ const values = /* @__PURE__ */ new Map();
408
+ const failed = /* @__PURE__ */ new Map();
409
+ for (const [accountId, source] of sources) {
410
+ const result = yield* Effect_exports.result(
411
+ read(source).pipe(Effect_exports.mapError((error) => accountProviderError(error, accountId)))
412
+ );
413
+ if (Result_exports.isSuccess(result)) values.set(accountId, result.success);
414
+ else failed.set(accountId, result.failure);
415
+ }
416
+ return { values, failed };
417
+ });
418
+ var firstFailure = (failed) => [...failed.values()][0];
419
+ var combineDynamic = (sources) => {
420
+ const first = [...sources.values()][0];
421
+ const grouped = (read, merged) => Effect_exports.gen(function* () {
422
+ const { values: listed, failed } = yield* eachAccount(sources, read);
423
+ if (listed.size === 0 && failed.size > 0) return yield* Effect_exports.fail(firstFailure(failed));
424
+ const groups = /* @__PURE__ */ new Map();
425
+ for (const [accountId, tools2] of listed)
426
+ for (const tool of tools2) {
427
+ const variants = groups.get(tool.name) ?? [];
428
+ if (variants.some(([id]) => id === accountId))
429
+ return yield* Effect_exports.die(new Error("Duplicate source operation"));
430
+ variants.push([accountId, tool]);
431
+ groups.set(tool.name, variants);
432
+ }
433
+ const tools = [...groups].map(([name, variants]) => merged(name, variants));
434
+ if (failed.size === 0) return tools;
435
+ return yield* new PartialListing({ tools, error: firstFailure(failed) });
436
+ });
437
+ return {
438
+ kind: "dynamic",
439
+ // Accounts share one source, so the first account that can describe it describes the router.
440
+ ...first?.meta === void 0 ? {} : {
441
+ meta: () => Effect_exports.gen(function* () {
442
+ const failures = [];
443
+ for (const source of sources.values()) {
444
+ if (source.meta === void 0) continue;
445
+ const result = yield* Effect_exports.result(source.meta());
446
+ if (Result_exports.isSuccess(result)) return result.success;
447
+ failures.push(result.failure);
448
+ }
449
+ return yield* Effect_exports.fail(failures[0]);
450
+ })
451
+ },
452
+ ...first?.overrides === void 0 ? {} : { overrides: first.overrides },
453
+ list: () => grouped((source) => source.list(), merge),
454
+ summaries: () => grouped(
455
+ (source) => source.summaries === void 0 ? source.list() : source.summaries(),
456
+ mergeSummary
457
+ ),
458
+ describe: (name) => eachAccount(
459
+ sources,
460
+ (source) => source.describe === void 0 ? source.list().pipe(Effect_exports.map((tools) => tools.find((tool) => tool.name === name))) : source.describe(name)
461
+ ).pipe(
462
+ Effect_exports.flatMap(({ values, failed }) => {
463
+ const variants = [...values].flatMap(
464
+ ([accountId, tool]) => tool === void 0 ? [] : [[accountId, tool]]
465
+ );
466
+ if (variants.length === 0)
467
+ return failed.size > 0 ? Effect_exports.fail(firstFailure(failed)) : Effect_exports.succeed(void 0);
468
+ return Effect_exports.succeed(merge(name, variants));
469
+ })
470
+ ),
471
+ resolve: (name) => eachAccount(sources, (source) => source.resolve(name)).pipe(
472
+ Effect_exports.flatMap(({ values, failed }) => {
473
+ const operations = new Map(
474
+ [...values].flatMap(
475
+ ([accountId, operation]) => operation === void 0 ? [] : [[accountId, operation]]
476
+ )
477
+ );
478
+ if (operations.size === 0)
479
+ return failed.size > 0 ? Effect_exports.fail(firstFailure(failed)) : Effect_exports.succeed(void 0);
480
+ return Effect_exports.succeed(combineOperation(operations, failed));
481
+ })
482
+ )
483
+ };
484
+ };
485
+ var combineNode = (variants) => {
486
+ const nodes = [...variants.values()];
487
+ const first = nodes[0];
488
+ if (first === void 0) throw new Error("An account operation must have at least one account");
489
+ switch (first.kind) {
490
+ case "query":
491
+ case "mutation":
492
+ return combineOperation(
493
+ narrow(
494
+ variants,
495
+ (node) => node.kind === "query" || node.kind === "mutation"
496
+ )
497
+ );
498
+ case "dynamic":
499
+ return combineDynamic(
500
+ narrow(variants, (node) => node.kind === "dynamic")
501
+ );
502
+ case "router": {
503
+ const routers = narrow(variants, (node) => node.kind === "router");
504
+ const keys = new Set([...routers.values()].flatMap((router2) => Object.keys(router2.children)));
505
+ return {
506
+ kind: "router",
507
+ ...first.meta === void 0 ? {} : { meta: first.meta },
508
+ children: Object.fromEntries(
509
+ [...keys].map((key) => {
510
+ const children = /* @__PURE__ */ new Map();
511
+ for (const [accountId, router2] of routers) {
512
+ const child = Object.hasOwn(router2.children, key) ? router2.children[key] : void 0;
513
+ if (child !== void 0) children.set(accountId, child);
514
+ }
515
+ return [key, combineNode(children)];
516
+ })
517
+ )
518
+ };
519
+ }
520
+ }
521
+ };
522
+ var narrow = (variants, is) => {
523
+ const narrowed = /* @__PURE__ */ new Map();
524
+ for (const [accountId, node] of variants) {
525
+ if (!is(node)) throw new Error("Each account's router must have the same shape");
526
+ narrowed.set(accountId, node);
527
+ }
528
+ return narrowed;
529
+ };
530
+ var accountRouter = (accounts, discover, options) => Effect_exports.runPromise(
531
+ Effect_exports.gen(function* () {
532
+ const routers = /* @__PURE__ */ new Map();
533
+ for (const account of accounts) {
534
+ const declaration = yield* Effect_exports.tryPromise({
535
+ try: async () => discover(account),
536
+ catch: (error) => accountProviderError(error, account.id)
537
+ });
538
+ if (routers.has(account.id))
539
+ return yield* Effect_exports.die(new Error("Account selections must be unique"));
540
+ const router2 = nativeRouter(declaration);
541
+ if (router2 === void 0) return yield* Effect_exports.die(new Error("Expected a protocol router"));
542
+ routers.set(account.id, router2);
543
+ }
544
+ if (routers.size === 0) return routerDeclaration({ kind: "router", children: {} });
545
+ const combined = combineNode(routers);
546
+ if (combined.kind !== "router" && combined.kind !== "dynamic")
547
+ return yield* Effect_exports.die(new Error("Expected a protocol router"));
548
+ return routerDeclaration(combined);
549
+ }),
550
+ options
551
+ );
552
+
553
+ export {
554
+ operationDeclaration,
555
+ nativeOperation,
556
+ withApproval,
557
+ toolAnnotations,
558
+ query,
559
+ mutation,
560
+ routerDeclaration,
561
+ nativeRouter,
562
+ mergeMeta,
563
+ router,
564
+ dynamicRouter,
565
+ joinPath,
566
+ locate,
567
+ declaredOperations,
568
+ withApprovals,
569
+ renameTools,
570
+ PartialListing,
571
+ accountRouter
572
+ };