stitchkit 0.123.5 → 0.123.7

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/dist/entrypoints/application/diagnostic-journal.js +1 -1
  3. package/dist/entrypoints/application/directory-inbox.js +3 -3
  4. package/dist/entrypoints/cli/publish.js +2 -2
  5. package/dist/entrypoints/cli.js +2 -1
  6. package/dist/entrypoints/files.js +2 -2
  7. package/dist/entrypoints/node.js +2 -2
  8. package/dist/entrypoints/server.js +5 -5
  9. package/dist/entrypoints/telegram/grammy.d.ts +1 -0
  10. package/dist/entrypoints/telegram/grammy.d.ts.map +1 -1
  11. package/dist/entrypoints/telegram/grammy.js +81 -3
  12. package/dist/entrypoints/telegram/screens.js +1 -1
  13. package/dist/entrypoints/telegram.d.ts +1 -0
  14. package/dist/entrypoints/telegram.d.ts.map +1 -1
  15. package/dist/entrypoints/telegram.js +18 -6
  16. package/dist/entrypoints/tools/contract.js +4 -2
  17. package/dist/entrypoints/tools/toolkit.js +2 -1
  18. package/dist/entrypoints/tools.js +33 -27
  19. package/dist/{index-xjb131sc.js → index-1a741dpf.js} +188 -51
  20. package/dist/{index-yfpt7sxr.js → index-6qrspvxp.js} +5 -3
  21. package/dist/index-81t0bf0f.js +18 -0
  22. package/dist/{index-d9cg0gen.js → index-8yky60kq.js} +1 -1
  23. package/dist/{index-bph35vpy.js → index-9cxxfkhb.js} +21 -1
  24. package/dist/index-bgj9hbm3.js +93 -0
  25. package/dist/index-bknzva6n.js +39 -0
  26. package/dist/{index-73dappvg.js → index-ezwvsqx9.js} +1 -1
  27. package/dist/{index-303qne11.js → index-f56ct5gb.js} +27 -4
  28. package/dist/{index-chz7c830.js → index-mqttte96.js} +39 -6
  29. package/dist/{index-eabx6qjh.js → index-tnnmekgb.js} +1 -6
  30. package/dist/index-zs8cze4j.js +6 -0
  31. package/dist/internal/exclusive-lock.d.ts.map +1 -1
  32. package/dist/internal/media-extension.d.ts +3 -0
  33. package/dist/internal/media-extension.d.ts.map +1 -0
  34. package/dist/telegram/send-failure.d.ts +2 -2
  35. package/dist/telegram/send-failure.d.ts.map +1 -1
  36. package/dist/telegram/widget-api.d.ts +106 -0
  37. package/dist/telegram/widget-api.d.ts.map +1 -0
  38. package/dist/telegram/widget.d.ts +121 -0
  39. package/dist/telegram/widget.d.ts.map +1 -0
  40. package/dist/tools/cli/args.d.ts +1 -1
  41. package/dist/tools/cli/args.d.ts.map +1 -1
  42. package/dist/tools/cli/command.d.ts +7 -1
  43. package/dist/tools/cli/command.d.ts.map +1 -1
  44. package/dist/tools/cli/config.d.ts +5 -2
  45. package/dist/tools/cli/config.d.ts.map +1 -1
  46. package/dist/tools/cli/download.d.ts +25 -4
  47. package/dist/tools/cli/download.d.ts.map +1 -1
  48. package/dist/tools/cli/inline-files.d.ts +70 -0
  49. package/dist/tools/cli/inline-files.d.ts.map +1 -0
  50. package/dist/tools/cli/session.d.ts.map +1 -1
  51. package/dist/tools/transfer/download-core.d.ts +2 -0
  52. package/dist/tools/transfer/download-core.d.ts.map +1 -1
  53. package/dist/tools/transfer/view-file-contract.d.ts +34 -4
  54. package/dist/tools/transfer/view-file-contract.d.ts.map +1 -1
  55. package/dist/tools/transfer/view-file.d.ts.map +1 -1
  56. package/llms/cli.txt +63 -3
  57. package/llms/stitchkit.txt +2 -2
  58. package/llms/telegram-grammy.txt +10 -3
  59. package/llms/telegram.2.txt +5 -0
  60. package/llms/telegram.txt +70 -0
  61. package/llms/tools.2.txt +5 -0
  62. package/llms-full.txt +152 -8
  63. package/llms.txt +6 -6
  64. package/package.json +1 -1
  65. package/dist/index-6j725ez5.js +0 -25
  66. package/dist/index-sba3e6m4.js +0 -52
@@ -30,6 +30,10 @@ import {
30
30
  import {
31
31
  isRepeatableRead
32
32
  } from "./index-332d0m9g.js";
33
+ import {
34
+ McpImageContentSchema,
35
+ McpAudioContentSchema
36
+ } from "./index-bknzva6n.js";
33
37
  import {
34
38
  readContractStreamItems,
35
39
  contractStreamLifetimeExceeded
@@ -43,8 +47,9 @@ import {
43
47
  containedEntryMetadata
44
48
  } from "./index-ww3gss55.js";
45
49
  import {
46
- pollUntil
47
- } from "./index-bph35vpy.js";
50
+ pollUntil,
51
+ mediaExtension
52
+ } from "./index-9cxxfkhb.js";
48
53
  import {
49
54
  collectToolSurface
50
55
  } from "./index-993vtv1w.js";
@@ -59,6 +64,9 @@ import {
59
64
  isUnsafeKey,
60
65
  safeJsonParse
61
66
  } from "./index-zsarb5xp.js";
67
+ import {
68
+ assertPositiveSafeInteger
69
+ } from "./index-0s4xebbg.js";
62
70
  import {
63
71
  formatZodError2
64
72
  } from "./index-1eeqpadm.js";
@@ -189,17 +197,20 @@ function prepareCliCommandEmission(policy, result, options) {
189
197
  };
190
198
  }
191
199
  }
192
- function emitCliCommandResult(policy, result, options, writers, emit) {
200
+ function emitCliCommandResult(policy, result, options, writers, emit, shown) {
193
201
  const emission = prepareCliCommandEmission(policy, result, options);
194
- if (emission.result.ok && emission.presentationFailure !== undefined) {
195
- return emitPresentationFailure(emission.result, emission.presentationFailure, writers, emit);
196
- }
197
- if (emission.result.ok && emission.presentation !== undefined) {
202
+ if (!emission.result.ok)
203
+ return emitResult2(emission.result, writers, emit);
204
+ if (emission.presentation !== undefined) {
198
205
  writers.stdout(emission.presentation);
199
206
  return emission.successExitCode;
200
207
  }
201
- const emitted = emitResult2(emission.result, writers, emit);
202
- return emission.result.ok ? emission.successExitCode : emitted;
208
+ const printed = shown ?? emission.result;
209
+ if (emission.presentationFailure !== undefined) {
210
+ return emitPresentationFailure(printed, emission.presentationFailure, writers, emit);
211
+ }
212
+ emitResult2(printed, writers, emit);
213
+ return emission.successExitCode;
203
214
  }
204
215
  function cliCommandPresentationSchema(definition) {
205
216
  return buildToolPresentationSchema({
@@ -931,7 +942,8 @@ function createCliIo(config) {
931
942
  }
932
943
 
933
944
  // src/tools/cli/download.ts
934
- import { basename, resolve } from "node:path";
945
+ import { createHash } from "node:crypto";
946
+ import { basename as basename2, resolve } from "node:path";
935
947
 
936
948
  // src/internal/write-download.ts
937
949
  import path from "node:path";
@@ -949,39 +961,145 @@ async function writeDownload(root, name, data) {
949
961
  });
950
962
  }
951
963
 
964
+ // src/tools/cli/inline-files.ts
965
+ import { basename } from "node:path";
966
+ import { pathToFileURL } from "node:url";
967
+ import { z as z2 } from "zod";
968
+ var EmbeddedResourceSchema = z2.object({
969
+ type: z2.literal("resource"),
970
+ resource: z2.union([
971
+ z2.object({ uri: z2.string(), mimeType: z2.string().optional(), blob: z2.string() }),
972
+ z2.object({ uri: z2.string(), mimeType: z2.string().optional(), text: z2.string() })
973
+ ])
974
+ });
975
+ var InlineFileSchema = z2.discriminatedUnion("type", [
976
+ McpImageContentSchema,
977
+ McpAudioContentSchema,
978
+ EmbeddedResourceSchema
979
+ ]);
980
+ function inlineFileBlocks(data) {
981
+ if (!isRecord(data) || !Array.isArray(data.content))
982
+ return [];
983
+ return data.content.flatMap((part, index) => {
984
+ const parsed = InlineFileSchema.safeParse(part);
985
+ return parsed.success ? [{ index, file: parsed.data }] : [];
986
+ });
987
+ }
988
+ function decodeBase64(data, maxBytes) {
989
+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
990
+ const decodedLength = Math.floor((data.length - padding) * 3 / 4);
991
+ if (data.length > Math.ceil(maxBytes / 3) * 4 || decodedLength > maxBytes) {
992
+ throw new Error(`file exceeds the ${maxBytes}-byte cap`);
993
+ }
994
+ if (data.length % 4 === 1 || padding > 0 && data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)) {
995
+ throw new Error("invalid base64");
996
+ }
997
+ const bytes = Buffer.from(data, "base64");
998
+ if (!bytes.toString("base64").startsWith(data))
999
+ throw new Error("invalid base64");
1000
+ return bytes;
1001
+ }
1002
+ function encodeText(text, maxBytes) {
1003
+ const bytes = text.length > maxBytes ? undefined : Buffer.from(text, "utf8");
1004
+ if (!bytes || bytes.length > maxBytes) {
1005
+ throw new Error(`file exceeds the ${maxBytes}-byte cap`);
1006
+ }
1007
+ return bytes;
1008
+ }
1009
+ function inlineFileBytes(file, maxBytes) {
1010
+ if (file.type !== "resource")
1011
+ return decodeBase64(file.data, maxBytes);
1012
+ return "blob" in file.resource ? decodeBase64(file.resource.blob, maxBytes) : encodeText(file.resource.text, maxBytes);
1013
+ }
1014
+ function uriFileName(uri) {
1015
+ try {
1016
+ return basename(new URL(uri).pathname);
1017
+ } catch {
1018
+ return "";
1019
+ }
1020
+ }
1021
+ function inlineFileMimeType(file) {
1022
+ return file.type === "resource" ? file.resource.mimeType : file.mimeType;
1023
+ }
1024
+ function inlineFileName(file, digest) {
1025
+ const own = file.type === "resource" ? uriFileName(file.resource.uri) || undefined : file.name;
1026
+ return own ?? `${file.type}-${digest}${mediaExtension(inlineFileMimeType(file) ?? "") ?? ".bin"}`;
1027
+ }
1028
+ function linkSavedFiles(data, blocks, saved) {
1029
+ if (!isRecord(data) || !Array.isArray(data.content))
1030
+ return data;
1031
+ const links = new Map;
1032
+ for (const block of blocks) {
1033
+ const file = saved(block);
1034
+ if (!file)
1035
+ continue;
1036
+ const mimeType = inlineFileMimeType(block.file);
1037
+ links.set(block.index, {
1038
+ type: "resource_link",
1039
+ uri: pathToFileURL(file.path).href,
1040
+ name: file.name,
1041
+ ...mimeType !== undefined && { mimeType },
1042
+ size: file.size
1043
+ });
1044
+ }
1045
+ if (links.size === 0)
1046
+ return data;
1047
+ return { ...data, content: data.content.map((part, index) => links.get(index) ?? part) };
1048
+ }
1049
+
952
1050
  // src/tools/cli/download.ts
953
1051
  var DEFAULT_DOWNLOAD_MAX_BYTES = 100 * 1024 * 1024;
954
- async function downloadResults(files, dir, stderr, quiet, allowPrivate, maxBytes, timeoutMs) {
1052
+ async function saveResultMedia(data, options) {
1053
+ const blocks = inlineFileBlocks(data);
1054
+ const sources = [...options.download?.(data) ?? [], ...blocks];
1055
+ if (sources.length === 0) {
1056
+ if (!options.quiet)
1057
+ options.stderr(`--output-dir: the result carries no files to save
1058
+ `);
1059
+ return { ok: true, data };
1060
+ }
1061
+ const batch = await saveBatch(sources, options);
1062
+ return {
1063
+ ok: batch.ok,
1064
+ data: linkSavedFiles(data, blocks, (block) => batch.files.get(block))
1065
+ };
1066
+ }
1067
+ async function saveBatch(sources, { dir, allowPrivateHosts, maxBytes, timeoutMs, quiet, stderr }) {
955
1068
  const root = resolve(dir);
956
- if (files.length === 0)
957
- return true;
1069
+ const files = new Map;
958
1070
  let directory;
959
1071
  try {
960
1072
  directory = await openPinnedDirectory(root, { create: true, readable: false });
961
1073
  } catch (error) {
962
1074
  stderr(`failed to prepare download directory: ${error instanceof Error ? error.message : String(error)}
963
1075
  `);
964
- return false;
1076
+ return { ok: false, files };
965
1077
  }
966
- let succeeded = true;
1078
+ let ok = true;
1079
+ const digests = new Map;
967
1080
  try {
968
- for (const file of files) {
1081
+ for (const source of sources) {
969
1082
  try {
970
- const res = await fetchGuarded(new URL(file.url), allowPrivate, { timeoutMs });
971
- if (!res.ok)
972
- throw new Error(`HTTP ${res.status}`);
973
- const buffer = await readCapped(res, maxBytes);
974
- if (!buffer)
975
- throw new Error(`file exceeds the ${maxBytes}-byte cap`);
976
- const name = basename(file.name);
977
- await writeDownload(directory, name, buffer);
978
- if (!quiet)
979
- stderr(`saved ${resolve(root, name)} (${(buffer.length / 1024).toFixed(0)}KB)
1083
+ const bytes = "url" in source ? await fetchDownload(source.url, allowPrivateHosts, maxBytes, timeoutMs) : inlineFileBytes(source.file, maxBytes);
1084
+ const digest = createHash("sha256").update(bytes).digest("hex");
1085
+ const name = basename2("url" in source ? source.name : inlineFileName(source.file, digest));
1086
+ const path = resolve(root, name);
1087
+ const written = digests.get(name);
1088
+ if (written === undefined) {
1089
+ await writeDownload(directory, name, bytes);
1090
+ digests.set(name, digest);
1091
+ if (!quiet)
1092
+ stderr(`saved ${path} (${(bytes.length / 1024).toFixed(0)}KB)
980
1093
  `);
1094
+ } else if (written !== digest) {
1095
+ throw new Error(`another file of this batch is already saved as ${JSON.stringify(name)}`);
1096
+ }
1097
+ files.set(source, { path, name, size: bytes.length });
981
1098
  } catch (err) {
982
- succeeded = false;
1099
+ ok = false;
983
1100
  const reason = errnoOf(err) ?? (err instanceof Error ? err.message : String(err));
984
- stderr(`failed to download ${file.url}: ${reason}
1101
+ const subject = "url" in source ? `failed to download ${source.url}` : `failed to save content[${source.index}]`;
1102
+ stderr(`${subject}: ${reason}
985
1103
  `);
986
1104
  }
987
1105
  }
@@ -989,12 +1107,21 @@ async function downloadResults(files, dir, stderr, quiet, allowPrivate, maxBytes
989
1107
  try {
990
1108
  await directory.close();
991
1109
  } catch (error) {
992
- succeeded = false;
1110
+ ok = false;
993
1111
  stderr(`failed to close download directory: ${error instanceof Error ? error.message : String(error)}
994
1112
  `);
995
1113
  }
996
1114
  }
997
- return succeeded;
1115
+ return { ok, files };
1116
+ }
1117
+ async function fetchDownload(url, allowPrivateHosts, maxBytes, timeoutMs) {
1118
+ const res = await fetchGuarded(new URL(url), allowPrivateHosts, { timeoutMs });
1119
+ if (!res.ok)
1120
+ throw new Error(`HTTP ${res.status}`);
1121
+ const bytes = await readCapped(res, maxBytes);
1122
+ if (!bytes)
1123
+ throw new Error(`file exceeds the ${maxBytes}-byte cap`);
1124
+ return bytes;
998
1125
  }
999
1126
 
1000
1127
  // src/tools/cli/help.ts
@@ -1002,7 +1129,7 @@ var GLOBAL_OPTIONS = [
1002
1129
  ["--json", "Emit compact success/error JSON records (for scripts)"],
1003
1130
  ["--wait", "Block-poll an async result to a terminal state"],
1004
1131
  ["--wait-timeout <s>", "Override the --wait timeout in seconds"],
1005
- ["--output-dir <dir>", "Download result media into a directory"],
1132
+ ["--output-dir <dir>", "Save the files a result names or carries into a directory"],
1006
1133
  ["--quiet", "Suppress non-essential stderr output"],
1007
1134
  ["--dry-run", "Print the resolved call without executing it"],
1008
1135
  ["--schema", "Print the JSON Schema of a command input and output"],
@@ -1410,7 +1537,7 @@ async function buildManagedSurface(session, typedGlobals, forExecution) {
1410
1537
  }
1411
1538
 
1412
1539
  // src/tools/cli/args.ts
1413
- import { z as z2 } from "zod";
1540
+ import { z as z3 } from "zod";
1414
1541
 
1415
1542
  // src/tools/cli/args-json.ts
1416
1543
  function cliFieldOption(option, fields) {
@@ -1818,7 +1945,7 @@ function extractCliGlobalOptions2(argv, schema) {
1818
1945
  try {
1819
1946
  coerced = coerceJsonArgs2(args, schema);
1820
1947
  } catch (error) {
1821
- if (error instanceof z2.ZodError)
1948
+ if (error instanceof z3.ZodError)
1822
1949
  refuseGlobalOption(error.issues[0]);
1823
1950
  throw error;
1824
1951
  }
@@ -1914,6 +2041,7 @@ function createCliSession(config, io) {
1914
2041
  if (config.auth !== undefined && config.resolveAuth !== undefined) {
1915
2042
  throw new Error("[stitchkit] createCli: use either auth or resolveAuth, not both");
1916
2043
  }
2044
+ assertPositiveSafeInteger("createCli maxDownloadBytes", config.maxDownloadBytes);
1917
2045
  const applicationOptions = config.globalOptions ? jsonSchemaFields(buildToolPresentationSchema({
1918
2046
  inputSchema: config.globalOptions,
1919
2047
  unrepresentable: "any"
@@ -2451,11 +2579,6 @@ async function runManagedCommand(session, route, command, managed) {
2451
2579
  }
2452
2580
  if (options.waitTimeout !== undefined && !options.wait) {
2453
2581
  stderr(`--wait-timeout requires --wait
2454
- `);
2455
- return exit(2);
2456
- }
2457
- if (options.outputDir !== undefined && !config.download) {
2458
- stderr(`--output-dir is not configured for this CLI
2459
2582
  `);
2460
2583
  return exit(2);
2461
2584
  }
@@ -2525,40 +2648,54 @@ async function executeManagedTool(session, route, command, managed, tool, { tool
2525
2648
  }
2526
2649
  return result;
2527
2650
  }
2528
- async function emitManagedResult(session, command, initial, options, repeatable) {
2651
+ async function emitManagedResult(session, command, result, options, repeatable) {
2529
2652
  const { config } = session;
2530
2653
  const { stdout, stderr, exit } = session.io;
2531
- let result = initial;
2532
- let downloadsOk = true;
2533
- if (options.outputDir && result.ok && config.download) {
2534
- downloadsOk = await downloadResults(config.download(result.data), options.outputDir, stderr, options.quiet, config.allowPrivateDownloadHosts ?? false, config.maxDownloadBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES, config.downloadTimeoutMs);
2654
+ const emit = { ...emitOptionsFor(config, options.json, command), repeatable };
2655
+ if (!result.ok)
2656
+ return exit(emitResult2(result, { stdout, stderr }, emit));
2657
+ let shown = result;
2658
+ let mediaExitCode = 0;
2659
+ if (options.outputDir !== undefined) {
2660
+ const saved = await saveResultMedia(result.data, {
2661
+ dir: options.outputDir,
2662
+ download: config.download,
2663
+ allowPrivateHosts: config.allowPrivateDownloadHosts ?? false,
2664
+ maxBytes: config.maxDownloadBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES,
2665
+ timeoutMs: config.downloadTimeoutMs,
2666
+ quiet: options.quiet,
2667
+ stderr
2668
+ });
2669
+ shown = { ...result, data: saved.data };
2670
+ if (!saved.ok)
2671
+ mediaExitCode = 1;
2535
2672
  }
2536
- if (options.view && result.ok) {
2673
+ if (options.view) {
2537
2674
  let viewed;
2538
2675
  try {
2539
- viewed = renderCliView2(result.data, options.view);
2676
+ viewed = renderCliView2(shown.data, options.view);
2540
2677
  } catch (error) {
2541
2678
  const failure = error instanceof CliArgumentError2 ? {
2542
2679
  ok: false,
2543
2680
  code: "BAD_REQUEST",
2544
2681
  details: { message: error.message }
2545
2682
  } : toolResultFromError(error);
2546
- return exit(emitPresentationFailure(result, failure, { stdout, stderr }, { ...emitOptionsFor(config, options.json, command), repeatable }));
2683
+ return exit(emitPresentationFailure(shown, failure, { stdout, stderr }, emit));
2547
2684
  }
2548
2685
  if (viewed.kind === "text") {
2549
2686
  stdout(viewed.text);
2550
- return exit(downloadsOk ? 0 : 1);
2687
+ return exit(mediaExitCode);
2551
2688
  }
2552
2689
  if (viewed.order) {
2553
2690
  stdout(`${stringifyGroups(viewed.data, viewed.order, options.json === true)}
2554
2691
  `);
2555
- return exit(downloadsOk ? 0 : 1);
2692
+ return exit(mediaExitCode);
2556
2693
  }
2557
- result = { ...result, data: viewed.data };
2694
+ shown = { ...shown, data: viewed.data };
2558
2695
  }
2559
2696
  const policy = options.view === undefined && !options.wait ? cliResultPolicy(config, command) : undefined;
2560
- const exitCode = emitCliCommandResult(policy, result, options, { stdout, stderr }, { ...emitOptionsFor(config, options.json, command), repeatable });
2561
- return exit(downloadsOk ? exitCode : 1);
2697
+ const exitCode = emitCliCommandResult(policy, result, options, { stdout, stderr }, emit, shown);
2698
+ return exit(mediaExitCode || exitCode);
2562
2699
  }
2563
2700
 
2564
2701
  // src/tools/cli/run-native.ts
@@ -32,9 +32,8 @@ import {
32
32
  isModuleNotFound
33
33
  } from "./index-srs8hj9c.js";
34
34
  import {
35
- bindContract,
36
- mediaTypeEssence
37
- } from "./index-eabx6qjh.js";
35
+ bindContract
36
+ } from "./index-tnnmekgb.js";
38
37
  import {
39
38
  assertCorsConfig,
40
39
  isOriginAllowed,
@@ -42,6 +41,9 @@ import {
42
41
  requestCorsHeaders,
43
42
  applyCors
44
43
  } from "./index-pq7rkwkk.js";
44
+ import {
45
+ mediaTypeEssence
46
+ } from "./index-zs8cze4j.js";
45
47
  import {
46
48
  runWithRequestContext2,
47
49
  getRequestContext2,
@@ -0,0 +1,18 @@
1
+ // src/tools/operations/async-operation-contract.ts
2
+ import { z } from "zod";
3
+ var AsyncOperationCancelResultSchema2 = z.discriminatedUnion("outcome", [
4
+ z.object({ outcome: z.literal("accepted") }),
5
+ z.object({ outcome: z.literal("already_terminal") }),
6
+ z.object({ outcome: z.literal("rejected"), reason: z.string().min(1) })
7
+ ]);
8
+ function createAsyncOperationSnapshotSchema2(config) {
9
+ const progress = config.progress ? { progress: config.progress.optional() } : {};
10
+ return z.discriminatedUnion("phase", [
11
+ z.object({ phase: z.literal("pending"), ...progress }),
12
+ z.object({ phase: z.literal("running"), ...progress }),
13
+ z.object({ phase: z.literal("succeeded"), ...progress }),
14
+ z.object({ phase: z.literal("failed"), failure: config.failure, ...progress }),
15
+ z.object({ phase: z.literal("cancelled"), ...progress })
16
+ ]);
17
+ }
18
+ export { AsyncOperationCancelResultSchema2, createAsyncOperationSnapshotSchema2 };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  withExclusiveLock2
3
- } from "./index-73dappvg.js";
3
+ } from "./index-ezwvsqx9.js";
4
4
  import {
5
5
  readBoundedFile
6
6
  } from "./index-m616f0yz.js";
@@ -1,3 +1,6 @@
1
+ import {
2
+ mediaTypeEssence
3
+ } from "./index-zs8cze4j.js";
1
4
  import {
2
5
  sleep
3
6
  } from "./index-eemvahkc.js";
@@ -74,4 +77,21 @@ function runWaitOperation(params) {
74
77
  });
75
78
  }
76
79
 
77
- export { WaitTimeoutError, pollUntil, runWaitOperation };
80
+ // src/internal/media-extension.ts
81
+ var MIME_EXT = new Map([
82
+ ["image/png", ".png"],
83
+ ["image/jpeg", ".jpg"],
84
+ ["image/webp", ".webp"],
85
+ ["image/gif", ".gif"],
86
+ ["video/mp4", ".mp4"],
87
+ ["video/webm", ".webm"],
88
+ ["audio/mpeg", ".mp3"],
89
+ ["audio/wav", ".wav"],
90
+ ["audio/ogg", ".ogg"],
91
+ ["audio/mp4", ".m4a"]
92
+ ]);
93
+ function mediaExtension(contentType) {
94
+ return MIME_EXT.get(mediaTypeEssence(contentType));
95
+ }
96
+
97
+ export { WaitTimeoutError, pollUntil, runWaitOperation, mediaExtension };
@@ -0,0 +1,93 @@
1
+ // src/telegram/widget.ts
2
+ import { deflateSync } from "node:zlib";
3
+ import { z } from "zod";
4
+ var TELEGRAM_WIDGET_LIMITS2 = Object.freeze({
5
+ htmlBytes: 32768,
6
+ compressedHtmlBytes: 4096,
7
+ dataBytes: 1024,
8
+ queryDataBytes: 64,
9
+ answerWindowMs: 15000
10
+ });
11
+ var encoder = new TextEncoder;
12
+ var decoder = new TextDecoder("utf-8", { ignoreBOM: true });
13
+ function textProblem(value, max, min = 0) {
14
+ if (value.includes("\x00"))
15
+ return "contains NUL";
16
+ const encoded = encoder.encode(value);
17
+ if (decoder.decode(encoded) !== value)
18
+ return "contains an unpaired surrogate";
19
+ const bytes = encoded.length;
20
+ if (bytes < min)
21
+ return `is ${bytes} UTF-8 bytes, at least ${min} required`;
22
+ if (bytes > max)
23
+ return `is ${bytes} UTF-8 bytes, at most ${max} allowed`;
24
+ return;
25
+ }
26
+ function htmlProblem(html) {
27
+ const problem = textProblem(html, TELEGRAM_WIDGET_LIMITS2.htmlBytes, 1);
28
+ if (problem !== undefined)
29
+ return problem;
30
+ const compressed = deflateSync(html, { level: 9 }).byteLength;
31
+ return compressed > TELEGRAM_WIDGET_LIMITS2.compressedHtmlBytes ? `compresses to ${compressed} bytes, at most ${TELEGRAM_WIDGET_LIMITS2.compressedHtmlBytes} allowed` : undefined;
32
+ }
33
+ function widgetText(problemOf) {
34
+ return z.string().superRefine((value, context) => {
35
+ const problem = problemOf(value);
36
+ if (problem !== undefined)
37
+ context.addIssue({ code: "custom", message: `Text ${problem}` });
38
+ });
39
+ }
40
+ var TelegramWidgetHtmlSchema2 = widgetText(htmlProblem);
41
+ var TelegramWidgetDataSchema2 = widgetText((value) => textProblem(value, TELEGRAM_WIDGET_LIMITS2.dataBytes));
42
+ var QueryDataSchema = widgetText((value) => textProblem(value, TELEGRAM_WIDGET_LIMITS2.queryDataBytes, 1));
43
+ var WalletSchema = z.looseObject({
44
+ address: z.string(),
45
+ amount: z.string(),
46
+ public_key: z.string().optional(),
47
+ state_init: z.string().optional()
48
+ });
49
+ var TelegramWidgetMessageSchema2 = z.looseObject({
50
+ message_id: z.int().nonnegative(),
51
+ chat: z.looseObject({ id: z.int(), type: z.string() }),
52
+ widget: z.looseObject({
53
+ html: z.string(),
54
+ id: z.string().optional(),
55
+ width: z.int().optional(),
56
+ height: z.int().optional(),
57
+ public_data: z.string().optional(),
58
+ chat_data: z.string().optional()
59
+ })
60
+ });
61
+ var TelegramWidgetQuerySchema2 = z.looseObject({
62
+ id: z.string().min(1),
63
+ from: z.looseObject({ id: z.int() }),
64
+ chat: z.looseObject({ id: z.int(), type: z.string() }).optional(),
65
+ message_id: z.int().optional(),
66
+ inline_message_id: z.string().optional(),
67
+ chat_instance: z.string(),
68
+ chat_type: z.string().optional(),
69
+ type: z.discriminatedUnion("type", [
70
+ z.looseObject({ type: z.literal("data"), wallet_card: z.looseObject({}).optional() }),
71
+ z.looseObject({
72
+ type: z.literal("sign_data"),
73
+ wallet: WalletSchema,
74
+ sign_data: z.string()
75
+ }),
76
+ z.looseObject({
77
+ type: z.literal("sent_transaction"),
78
+ wallet: WalletSchema,
79
+ msg_hash: z.string()
80
+ })
81
+ ]),
82
+ data: QueryDataSchema,
83
+ widget_id: z.string().optional()
84
+ });
85
+ function parseTelegramWidgetQuery2(value) {
86
+ const parsed = TelegramWidgetQuerySchema2.safeParse(value);
87
+ if (parsed.success)
88
+ return { query: parsed.data };
89
+ const id = typeof value === "object" && value !== null ? Reflect.get(value, "id") : undefined;
90
+ return typeof id === "string" && id.length > 0 ? { id, error: parsed.error } : undefined;
91
+ }
92
+
93
+ export { TELEGRAM_WIDGET_LIMITS2, TelegramWidgetHtmlSchema2, TelegramWidgetDataSchema2, TelegramWidgetMessageSchema2, TelegramWidgetQuerySchema2, parseTelegramWidgetQuery2 };
@@ -0,0 +1,39 @@
1
+ // src/tools/transfer/view-file-contract.ts
2
+ import { z } from "zod";
3
+ var MAX_VIEW_FILES = 20;
4
+ var McpAnnotationsSchema2 = z.object({
5
+ audience: z.array(z.enum(["user", "assistant"])).optional(),
6
+ priority: z.number().optional()
7
+ });
8
+ var inlineMediaShape = {
9
+ data: z.string(),
10
+ mimeType: z.string(),
11
+ name: z.string().optional(),
12
+ annotations: McpAnnotationsSchema2.optional()
13
+ };
14
+ var McpImageContentSchema = z.object({
15
+ type: z.literal("image"),
16
+ ...inlineMediaShape
17
+ });
18
+ var McpAudioContentSchema = z.object({
19
+ type: z.literal("audio"),
20
+ ...inlineMediaShape
21
+ });
22
+ var McpMediaContentSchema2 = z.discriminatedUnion("type", [
23
+ z.object({ type: z.literal("text"), text: z.string() }),
24
+ McpImageContentSchema,
25
+ McpAudioContentSchema
26
+ ]);
27
+ var ViewFileErrorSchema2 = z.object({
28
+ path: z.string(),
29
+ message: z.string()
30
+ });
31
+ var ViewFileOutputSchema2 = z.object({
32
+ content: z.array(McpMediaContentSchema2),
33
+ errors: z.array(ViewFileErrorSchema2)
34
+ });
35
+ var ViewFileInputSchema2 = z.object({
36
+ paths: z.union([z.string(), z.array(z.string()).max(MAX_VIEW_FILES)]).describe("One media URL or file path, or an array of them. Pass the array itself, not JSON written as text.")
37
+ });
38
+
39
+ export { McpAnnotationsSchema2, McpImageContentSchema, McpAudioContentSchema, McpMediaContentSchema2, ViewFileErrorSchema2, ViewFileOutputSchema2, ViewFileInputSchema2 };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  attemptExclusiveLock
3
- } from "./index-chz7c830.js";
3
+ } from "./index-mqttte96.js";
4
4
  import {
5
5
  sleep
6
6
  } from "./index-eemvahkc.js";
@@ -1,10 +1,31 @@
1
- import {
2
- isTelegramNotDispatched
3
- } from "./index-6j725ez5.js";
4
1
  import {
5
2
  isRecord
6
3
  } from "./index-hkxgennw.js";
7
4
 
5
+ // src/telegram/not-dispatched.ts
6
+ class TelegramNotDispatchedError2 extends Error {
7
+ stage;
8
+ name = "TelegramNotDispatchedError";
9
+ code = "TELEGRAM_NOT_DISPATCHED";
10
+ constructor(stage, message, options) {
11
+ super(message, options);
12
+ this.stage = stage;
13
+ }
14
+ }
15
+ function isTelegramNotDispatchedError(error) {
16
+ return error instanceof TelegramNotDispatchedError2 || error instanceof Error && error.name === "TelegramNotDispatchedError" && Reflect.get(error, "code") === "TELEGRAM_NOT_DISPATCHED";
17
+ }
18
+ function isTelegramNotDispatched(error, depth = 0) {
19
+ if (error instanceof TelegramNotDispatchedError2)
20
+ return true;
21
+ if (typeof error !== "object" || error === null || depth > 4)
22
+ return false;
23
+ if (Reflect.get(error, "code") === "TELEGRAM_NOT_DISPATCHED")
24
+ return true;
25
+ const nested = Reflect.get(error, "cause") ?? Reflect.get(error, "error");
26
+ return nested !== error && isTelegramNotDispatched(nested, depth + 1);
27
+ }
28
+
8
29
  // src/telegram/send-failure.ts
9
30
  var BY_DESCRIPTION = [
10
31
  [/bot was blocked by the user|bot was kicked/i, "blocked-by-user"],
@@ -147,6 +168,8 @@ var EDIT_REFUSALS = [
147
168
  [/query is too old|query id is invalid/i, "query-expired"]
148
169
  ];
149
170
  function classifyTelegramEditRefusal(error) {
171
+ if (isTelegramNotDispatched(error))
172
+ return "other";
150
173
  const description = descriptionOf(error);
151
174
  for (const [pattern, refusal] of EDIT_REFUSALS) {
152
175
  if (pattern.test(description))
@@ -155,4 +178,4 @@ function classifyTelegramEditRefusal(error) {
155
178
  return "other";
156
179
  }
157
180
 
158
- export { TELEGRAM_SEND_FAILURE_REASONS2, classifyTelegramSendFailure2, classifyTelegramEditRefusal };
181
+ export { TelegramNotDispatchedError2, isTelegramNotDispatchedError, TELEGRAM_SEND_FAILURE_REASONS2, classifyTelegramSendFailure2, classifyTelegramEditRefusal };