@wirecat/tg-cli 0.99.0 → 0.101.0

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 (117) hide show
  1. package/README.md +6 -5
  2. package/dist/bin/tg.js +23 -28
  3. package/dist/bundle/adapter-A3VD4Y6Z.js +2790 -0
  4. package/dist/bundle/all-profiles-UPVNHXB2.js +264 -0
  5. package/dist/bundle/anthropic-IRKNWPIB.js +71 -0
  6. package/dist/bundle/bot-api-UNTQG2M5.js +39793 -0
  7. package/dist/bundle/bot-history-V4RTY5K7.js +167 -0
  8. package/dist/bundle/bun-2JZPG2NL.js +169 -0
  9. package/dist/bundle/bun-sqlite-TZHKM225.js +70 -0
  10. package/dist/bundle/chunk-22PQUX72.js +190 -0
  11. package/dist/bundle/chunk-2DGOFLDA.js +58 -0
  12. package/dist/bundle/chunk-2SJOUK6J.js +2 -0
  13. package/dist/bundle/chunk-2XBSVRT2.js +98 -0
  14. package/dist/bundle/chunk-3KHKYYCR.js +24782 -0
  15. package/dist/bundle/chunk-4ZS73HTJ.js +6848 -0
  16. package/dist/bundle/chunk-54R2GDQ3.js +119 -0
  17. package/dist/bundle/chunk-5GKXETRP.js +1345 -0
  18. package/dist/bundle/chunk-5KU4UQBM.js +570 -0
  19. package/dist/bundle/chunk-5TPT2S2Z.js +41 -0
  20. package/dist/bundle/chunk-64DK7S4F.js +76 -0
  21. package/dist/bundle/chunk-6IPY2QRG.js +82 -0
  22. package/dist/bundle/chunk-7BFO3DY6.js +21 -0
  23. package/dist/bundle/chunk-7CBUCTB6.js +1142 -0
  24. package/dist/bundle/chunk-A5JSTZZZ.js +122 -0
  25. package/dist/bundle/chunk-ACGTFLEB.js +1275 -0
  26. package/dist/bundle/chunk-AFV74GK3.js +50 -0
  27. package/dist/bundle/chunk-AVWK4NCW.js +24600 -0
  28. package/dist/bundle/chunk-BJG6JA5U.js +35 -0
  29. package/dist/bundle/chunk-BX6HH4F6.js +215 -0
  30. package/dist/bundle/chunk-BXQS5RCE.js +8170 -0
  31. package/dist/bundle/chunk-CJ6IYCYP.js +583 -0
  32. package/dist/bundle/chunk-DG62L57H.js +2795 -0
  33. package/dist/bundle/chunk-DYNSP6FW.js +33720 -0
  34. package/dist/bundle/chunk-F7TDFWXY.js +82 -0
  35. package/dist/bundle/chunk-G2US6LJB.js +35 -0
  36. package/dist/bundle/chunk-G3ZRY436.js +3077 -0
  37. package/dist/bundle/chunk-G77QOTXE.js +18 -0
  38. package/dist/bundle/chunk-H6OXALTJ.js +45 -0
  39. package/dist/bundle/chunk-LPB2MDUW.js +452 -0
  40. package/dist/bundle/chunk-MLLJ74LM.js +24 -0
  41. package/dist/bundle/chunk-N5UFBWDM.js +166 -0
  42. package/dist/bundle/chunk-NC5WS7OP.js +31 -0
  43. package/dist/bundle/chunk-NKJJJAIJ.js +237 -0
  44. package/dist/bundle/chunk-NMGO6LW6.js +1950 -0
  45. package/dist/bundle/chunk-ODSVNH3H.js +18588 -0
  46. package/dist/bundle/chunk-OEJ5DMCX.js +2374 -0
  47. package/dist/bundle/chunk-OILBDLWL.js +724 -0
  48. package/dist/bundle/chunk-OPBTNQ35.js +1007 -0
  49. package/dist/bundle/chunk-PUBS2F5J.js +35803 -0
  50. package/dist/bundle/chunk-PYTOIDSM.js +153 -0
  51. package/dist/bundle/chunk-QOWSVDPZ.js +3526 -0
  52. package/dist/bundle/chunk-QYVVRQTN.js +73 -0
  53. package/dist/bundle/chunk-RF54YDBB.js +46 -0
  54. package/dist/bundle/chunk-RVCS7Q3A.js +6672 -0
  55. package/dist/bundle/chunk-S2JSZWEC.js +277 -0
  56. package/dist/bundle/chunk-S7ZNLLY5.js +54 -0
  57. package/dist/bundle/chunk-TGREFJVA.js +2315 -0
  58. package/dist/bundle/chunk-U46UNBMT.js +524 -0
  59. package/dist/bundle/chunk-UN6CKIBN.js +285 -0
  60. package/dist/bundle/chunk-VA5YEJS3.js +161 -0
  61. package/dist/bundle/chunk-VCGL2ETF.js +78 -0
  62. package/dist/bundle/chunk-VRSN7VLO.js +63 -0
  63. package/dist/bundle/chunk-VYDTI254.js +3332 -0
  64. package/dist/bundle/chunk-W2336E7Y.js +886 -0
  65. package/dist/bundle/chunk-X4Y2ROJI.js +541 -0
  66. package/dist/bundle/chunk-XCKD54TN.js +100 -0
  67. package/dist/bundle/chunk-ZEOCU24Z.js +738 -0
  68. package/dist/bundle/chunk-ZJVZXJOG.js +71 -0
  69. package/dist/bundle/chunk-ZV24I2UJ.js +25 -0
  70. package/dist/bundle/chunk-ZZLKX62Z.js +928 -0
  71. package/dist/bundle/command-contract-TKDI7E56.js +31 -0
  72. package/dist/bundle/dist-RJMT44PL.js +7577 -0
  73. package/dist/bundle/echarts-QZ6PR3VC.js +42501 -0
  74. package/dist/bundle/embed-UBXCXSRD.js +35 -0
  75. package/dist/bundle/embedder-B4ZTKC23.js +108 -0
  76. package/dist/bundle/entry-BTUTHO5M.js +14 -0
  77. package/dist/bundle/first-run-UC4HRIFV.js +24 -0
  78. package/dist/bundle/first-screen-SMCX6YKY.js +29 -0
  79. package/dist/bundle/identity-QSDEGDH7.js +11 -0
  80. package/dist/bundle/instructions-BBGLZKO3.js +9 -0
  81. package/dist/bundle/mcp-4Y37G2UY.js +165 -0
  82. package/dist/bundle/node-IUL5HSYI.js +2340 -0
  83. package/dist/bundle/node-LZZX22VR.js +176 -0
  84. package/dist/bundle/node-UPPL626U.js +21 -0
  85. package/dist/bundle/node-sqlite-BPGT6T5U.js +46 -0
  86. package/dist/bundle/oauth-XNE2KPKJ.js +18 -0
  87. package/dist/bundle/open-SXGYZLB5.js +20 -0
  88. package/dist/bundle/process-GPUXC4PG.js +91 -0
  89. package/dist/bundle/program-NEXEAL7T.js +1060 -0
  90. package/dist/bundle/prompt-SORGLEYI.js +13 -0
  91. package/dist/bundle/proxy-transport-G4MA6BGU.js +17 -0
  92. package/dist/bundle/recognize-UJBXORVD.js +191 -0
  93. package/dist/bundle/remote-W72AR7KH.js +26 -0
  94. package/dist/bundle/rerank-3Y2VZM3J.js +49 -0
  95. package/dist/bundle/serve-VDZIVOPR.js +196 -0
  96. package/dist/bundle/server-BERXP4GW.js +785 -0
  97. package/dist/bundle/server-ZFHN4GUF.js +178 -0
  98. package/dist/bundle/state-DGR4EE3E.js +34 -0
  99. package/dist/bundle/store-MRCFSCZD.js +121 -0
  100. package/dist/bundle/store-maintenance-command-DCMZDMYS.js +46 -0
  101. package/dist/bundle/tg.js +40 -0
  102. package/dist/commands/context.d.ts.map +1 -1
  103. package/dist/commands/context.js +3 -1
  104. package/dist/commands/context.js.map +1 -1
  105. package/dist/install/postinstall.js +1 -1
  106. package/dist/install/postinstall.js.map +1 -1
  107. package/dist/program.js +1 -1
  108. package/dist/program.js.map +1 -1
  109. package/dist/telegram/errors.js +1 -1
  110. package/dist/telegram/errors.js.map +1 -1
  111. package/dist/version.d.ts +1 -1
  112. package/dist/version.d.ts.map +1 -1
  113. package/dist/version.js +1 -1
  114. package/dist/version.js.map +1 -1
  115. package/install/windows.ps1 +1 -1
  116. package/package.json +6 -4
  117. package/skills/{wirecat-tg → tg-cli}/SKILL.md +4 -4
@@ -0,0 +1,13 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ readSecret
5
+ } from "./chunk-F7TDFWXY.js";
6
+ import "./chunk-6IPY2QRG.js";
7
+ import "./chunk-DG62L57H.js";
8
+ import "./chunk-OEJ5DMCX.js";
9
+ import "./chunk-BJG6JA5U.js";
10
+ import "./chunk-AFV74GK3.js";
11
+ export {
12
+ readSecret
13
+ };
@@ -0,0 +1,17 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ checkProxy,
5
+ proxiedTransport,
6
+ proxyFailure
7
+ } from "./chunk-ZJVZXJOG.js";
8
+ import "./chunk-2XBSVRT2.js";
9
+ import "./chunk-DG62L57H.js";
10
+ import "./chunk-OEJ5DMCX.js";
11
+ import "./chunk-BJG6JA5U.js";
12
+ import "./chunk-AFV74GK3.js";
13
+ export {
14
+ checkProxy,
15
+ proxiedTransport,
16
+ proxyFailure
17
+ };
@@ -0,0 +1,191 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import "./chunk-DG62L57H.js";
4
+ import {
5
+ CliError
6
+ } from "./chunk-OEJ5DMCX.js";
7
+ import {
8
+ importFrom
9
+ } from "./chunk-BJG6JA5U.js";
10
+ import {
11
+ __name
12
+ } from "./chunk-AFV74GK3.js";
13
+
14
+ // node_modules/.pnpm/@wirecat+cli-core@0.466.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.64.0_commander@15._f7e4048410ccbe1e801fd184c043d197/node_modules/@wirecat/cli-core/dist/speech/recognize.js
15
+ import { createRequire } from "node:module";
16
+
17
+ // node_modules/.pnpm/@wirecat+cli-core@0.466.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.64.0_commander@15._f7e4048410ccbe1e801fd184c043d197/node_modules/@wirecat/cli-core/dist/speech/ogg-limit.js
18
+ var invalid = /* @__PURE__ */ __name(() => new CliError("validation_error", "local transcription needs a complete mono or stereo Ogg Opus recording"), "invalid");
19
+ var checkOggDuration = /* @__PURE__ */ __name((bytes) => {
20
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
21
+ let offset = 0;
22
+ let serial;
23
+ let packet = 0;
24
+ let length = 0;
25
+ const prefix = [];
26
+ while (offset < bytes.length) {
27
+ if (offset + 27 > bytes.length || view.getUint32(offset, false) !== 1332176723 || bytes[offset + 4] !== 0)
28
+ throw invalid();
29
+ const stream = view.getUint32(offset + 14, true);
30
+ if (serial !== void 0 && serial !== stream)
31
+ throw invalid();
32
+ serial = stream;
33
+ const segments = bytes[offset + 26] ?? 0;
34
+ let data = offset + 27 + segments;
35
+ if (data > bytes.length || Boolean((bytes[offset + 5] ?? 0) & 1) !== length > 0)
36
+ throw invalid();
37
+ for (let index = 0; index < segments; index++) {
38
+ const size = bytes[offset + 27 + index] ?? 0;
39
+ if (data + size > bytes.length)
40
+ throw invalid();
41
+ const take = Math.min(size, 19 - prefix.length);
42
+ for (let i = 0; i < take; i++)
43
+ prefix.push(bytes[data + i] ?? 0);
44
+ length += size;
45
+ data += size;
46
+ if (size === 255)
47
+ continue;
48
+ if (packet === 0) {
49
+ if (length < 19 || String.fromCharCode(...prefix.slice(0, 8)) !== "OpusHead" || ![1, 2].includes(prefix[9] ?? 0) || prefix[18] !== 0)
50
+ throw invalid();
51
+ } else if (packet === 1) {
52
+ if (length < 8 || String.fromCharCode(...prefix.slice(0, 8)) !== "OpusTags")
53
+ throw invalid();
54
+ } else {
55
+ if (length < 1)
56
+ throw invalid();
57
+ const toc = prefix[0] ?? 0;
58
+ const config = toc >> 3;
59
+ const frame = config >= 16 ? 120 << (config & 3) : config >= 12 ? 480 << (config & 1) : (config & 3) === 3 ? 2880 : 480 << (config & 3);
60
+ const count = (toc & 3) === 0 ? 1 : (toc & 3) === 3 ? length >= 2 ? (prefix[1] ?? 0) & 63 : 0 : 2;
61
+ if (count < 1 || frame * count > 5760)
62
+ throw invalid();
63
+ }
64
+ packet++;
65
+ length = 0;
66
+ prefix.length = 0;
67
+ }
68
+ offset = data;
69
+ }
70
+ if (length !== 0 || packet < 3)
71
+ throw invalid();
72
+ }, "checkOggDuration");
73
+
74
+ // node_modules/.pnpm/@wirecat+cli-core@0.466.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.64.0_commander@15._f7e4048410ccbe1e801fd184c043d197/node_modules/@wirecat/cli-core/dist/speech/recognize.js
75
+ var SAMPLE_RATE = 16e3;
76
+ var LEAD = SAMPLE_RATE / 2;
77
+ var toModelRate = /* @__PURE__ */ __name((samples, rate) => {
78
+ const step = rate / SAMPLE_RATE;
79
+ const length = Math.floor(samples.length / step);
80
+ const pcm = new Float32Array(LEAD + length);
81
+ for (let i = 0; i < length; i++) {
82
+ const from = Math.floor(i * step);
83
+ const to = Math.max(from + 1, Math.floor((i + 1) * step));
84
+ let sum = 0;
85
+ for (let j = from; j < to; j++)
86
+ sum += samples[j] ?? 0;
87
+ pcm[LEAD + i] = sum / (to - from);
88
+ }
89
+ return pcm;
90
+ }, "toModelRate");
91
+ var decodeOgg = /* @__PURE__ */ __name(async (bytes) => {
92
+ checkOggDuration(bytes);
93
+ const { OggOpusDecoder } = await importFrom(new URL("speech/recognize.js", import.meta.resolve("@wirecat/cli-core")).href, "ogg-opus-decoder");
94
+ const decoder = new OggOpusDecoder();
95
+ await decoder.ready;
96
+ try {
97
+ const { channelData, sampleRate, samplesDecoded } = await decoder.decodeFile(bytes);
98
+ const samples = channelData[0];
99
+ if (!samples || samplesDecoded === 0)
100
+ throw new Error("no Ogg Opus audio in it");
101
+ return { samples, rate: sampleRate };
102
+ } finally {
103
+ decoder.free();
104
+ }
105
+ }, "decodeOgg");
106
+ var WINDOW = 512;
107
+ var detector = /* @__PURE__ */ __name((vadModel) => ({
108
+ sileroVad: {
109
+ model: vadModel,
110
+ // At the default 0.5 a quietly spoken stretch in the middle of a voice message never counted as
111
+ // speech and was lost; 0.3 keeps it for both models and changes nothing on clear speech (126508, 2026-09-30).
112
+ threshold: 0.3,
113
+ minSilenceDuration: 0.5,
114
+ minSpeechDuration: 0.25,
115
+ maxSpeechDuration: 20,
116
+ windowSize: WINDOW
117
+ },
118
+ sampleRate: SAMPLE_RATE,
119
+ numThreads: 1,
120
+ provider: "cpu",
121
+ debug: 0,
122
+ bufferSizeInSeconds: 30
123
+ }), "detector");
124
+ var loaded;
125
+ var loadSherpa = /* @__PURE__ */ __name(() => {
126
+ if (loaded)
127
+ return loaded;
128
+ const load = createRequire(new URL("speech/recognize.js", import.meta.resolve("@wirecat/cli-core")).href);
129
+ const wasm = {};
130
+ load("sherpa-onnx/sherpa-onnx-wasm-nodejs.js")(wasm);
131
+ const stdout = wasm.FS?.getStream(1);
132
+ if (stdout)
133
+ stdout.nfd = 2;
134
+ const asr = load("sherpa-onnx/sherpa-onnx-asr.js");
135
+ const vad = load("sherpa-onnx/sherpa-onnx-vad.js");
136
+ loaded = {
137
+ createOfflineRecognizer: /* @__PURE__ */ __name((config) => new asr.OfflineRecognizer(config, wasm), "createOfflineRecognizer"),
138
+ createVad: /* @__PURE__ */ __name((config) => vad.createVad(wasm, config), "createVad")
139
+ };
140
+ return loaded;
141
+ }, "loadSherpa");
142
+ var openRecognizer = /* @__PURE__ */ __name((model, path, vadModel) => {
143
+ const sherpa = loadSherpa();
144
+ const engine = sherpa.createOfflineRecognizer({
145
+ featConfig: { sampleRate: SAMPLE_RATE, featureDim: model.featureDim },
146
+ modelConfig: { ...model.config(path), numThreads: 1, provider: "cpu", debug: 0 },
147
+ decodingMethod: "greedy_search"
148
+ });
149
+ const vad = sherpa.createVad(detector(vadModel));
150
+ const piece = /* @__PURE__ */ __name((samples) => {
151
+ const stream = engine.createStream();
152
+ try {
153
+ stream.acceptWaveform(SAMPLE_RATE, samples);
154
+ engine.decode(stream);
155
+ return engine.getResult(stream).text.trim();
156
+ } finally {
157
+ stream.free();
158
+ }
159
+ }, "piece");
160
+ return {
161
+ recognize: /* @__PURE__ */ __name((pcm) => {
162
+ vad.reset();
163
+ const parts = [];
164
+ const drain = /* @__PURE__ */ __name(() => {
165
+ while (!vad.isEmpty()) {
166
+ parts.push(piece(vad.front().samples));
167
+ vad.pop();
168
+ }
169
+ }, "drain");
170
+ for (let i = 0; i + WINDOW <= pcm.length; i += WINDOW) {
171
+ vad.acceptWaveform(pcm.subarray(i, i + WINDOW));
172
+ drain();
173
+ }
174
+ vad.flush();
175
+ drain();
176
+ return parts.filter(Boolean).join(" ");
177
+ }, "recognize"),
178
+ free: /* @__PURE__ */ __name(() => {
179
+ vad.free();
180
+ engine.free();
181
+ }, "free")
182
+ };
183
+ }, "openRecognizer");
184
+ export {
185
+ SAMPLE_RATE,
186
+ decodeOgg,
187
+ detector,
188
+ loadSherpa,
189
+ openRecognizer,
190
+ toModelRate
191
+ };
@@ -0,0 +1,26 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ DEFAULT_OPENAI_MODEL,
5
+ OPENAI_MODELS,
6
+ OPENAI_URL,
7
+ isLocal,
8
+ openRemote,
9
+ remoteKey,
10
+ remoteModel
11
+ } from "./chunk-A5JSTZZZ.js";
12
+ import "./chunk-ACGTFLEB.js";
13
+ import "./chunk-G77QOTXE.js";
14
+ import "./chunk-DG62L57H.js";
15
+ import "./chunk-OEJ5DMCX.js";
16
+ import "./chunk-BJG6JA5U.js";
17
+ import "./chunk-AFV74GK3.js";
18
+ export {
19
+ DEFAULT_OPENAI_MODEL,
20
+ OPENAI_MODELS,
21
+ OPENAI_URL,
22
+ isLocal,
23
+ openRemote,
24
+ remoteKey,
25
+ remoteModel
26
+ };
@@ -0,0 +1,49 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ defaultThreads,
5
+ loadModel,
6
+ truncated
7
+ } from "./chunk-ACGTFLEB.js";
8
+ import "./chunk-G77QOTXE.js";
9
+ import "./chunk-DG62L57H.js";
10
+ import "./chunk-OEJ5DMCX.js";
11
+ import "./chunk-BJG6JA5U.js";
12
+ import {
13
+ __name
14
+ } from "./chunk-AFV74GK3.js";
15
+
16
+ // node_modules/.pnpm/@wirecat+cli-core@0.466.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.64.0_commander@15._f7e4048410ccbe1e801fd184c043d197/node_modules/@wirecat/cli-core/dist/embeddings/rerank.js
17
+ var openReranker = /* @__PURE__ */ __name(async (model, directory, { threads = defaultThreads() } = {}) => {
18
+ const { ort, tokenizer, session } = await loadModel(model, directory, threads);
19
+ const typeIds = session.inputNames.includes("token_type_ids");
20
+ const output = session.outputNames[0];
21
+ const one = /* @__PURE__ */ __name(async (question, passage) => {
22
+ const encoded = tokenizer.encode(question, { text_pair: passage, return_token_type_ids: true });
23
+ const ids = truncated(encoded.ids, model.maxTokens);
24
+ const shape = [1, ids.length];
25
+ const feeds = {
26
+ input_ids: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), shape),
27
+ attention_mask: new ort.Tensor("int64", new BigInt64Array(ids.length).fill(1n), shape)
28
+ };
29
+ if (typeIds)
30
+ feeds.token_type_ids = new ort.Tensor("int64", BigInt64Array.from(truncated(encoded.token_type_ids, model.maxTokens), BigInt), shape);
31
+ const logit = (await session.run(feeds))[output]?.data[0];
32
+ if (typeof logit !== "number" || !Number.isFinite(logit))
33
+ throw new Error(`${model.id} gave no score`);
34
+ return logit;
35
+ }, "one");
36
+ return {
37
+ model,
38
+ score: /* @__PURE__ */ __name(async (question, passages) => {
39
+ const scores = [];
40
+ for (const passage of passages)
41
+ scores.push(await one(question, passage));
42
+ return scores;
43
+ }, "score"),
44
+ close: /* @__PURE__ */ __name(() => session.release(), "close")
45
+ };
46
+ }, "openReranker");
47
+ export {
48
+ openReranker
49
+ };
@@ -0,0 +1,196 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ listen
5
+ } from "./chunk-VCGL2ETF.js";
6
+ import {
7
+ ownerLogin
8
+ } from "./chunk-UN6CKIBN.js";
9
+ import {
10
+ WebStandardStreamableHTTPServerTransport,
11
+ createMcpHandler,
12
+ getOAuthProtectedResourceMetadataUrl,
13
+ hostHeaderValidationResponse,
14
+ isLegacyRequest,
15
+ oauthMetadataResponse,
16
+ requireBearerAuth
17
+ } from "./chunk-3KHKYYCR.js";
18
+ import {
19
+ activityRecorder,
20
+ calledTools,
21
+ httpActivityFile,
22
+ httpLock
23
+ } from "./chunk-VA5YEJS3.js";
24
+ import "./chunk-QYVVRQTN.js";
25
+ import "./chunk-VRSN7VLO.js";
26
+ import "./chunk-DG62L57H.js";
27
+ import {
28
+ CliError
29
+ } from "./chunk-OEJ5DMCX.js";
30
+ import "./chunk-BJG6JA5U.js";
31
+ import {
32
+ __name
33
+ } from "./chunk-AFV74GK3.js";
34
+
35
+ // node_modules/.pnpm/@wirecat+cli-core@0.466.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.64.0_commander@15._f7e4048410ccbe1e801fd184c043d197/node_modules/@wirecat/cli-core/dist/mcp/http/serve.js
36
+ import { randomUUID } from "node:crypto";
37
+ var MCP_PATH = "/mcp";
38
+ var AS_METADATA = "/.well-known/oauth-authorization-server";
39
+ var LOCAL = ["localhost", "127.0.0.1"];
40
+ var MAX_SESSIONS = 20;
41
+ var MAX_LOGIN_BODY = 64 * 1024;
42
+ var SESSION_IDLE_MS = 60 * 60 * 1e3;
43
+ var sessionMissing = /* @__PURE__ */ __name(() => new Response(JSON.stringify({ jsonrpc: "2.0", error: { code: -32001, message: "Session not found" }, id: null }), {
44
+ status: 404,
45
+ headers: { "content-type": "application/json" }
46
+ }), "sessionMissing");
47
+ var legacySessions = /* @__PURE__ */ __name((build, now) => {
48
+ const sessions = /* @__PURE__ */ new Map();
49
+ const drop = /* @__PURE__ */ __name(async (id) => {
50
+ const one = sessions.get(id);
51
+ sessions.delete(id);
52
+ await one?.close();
53
+ }, "drop");
54
+ const handle = /* @__PURE__ */ __name(async (request, auth) => {
55
+ for (const [id2, one] of sessions)
56
+ if (now() - one.seen > SESSION_IDLE_MS)
57
+ await drop(id2);
58
+ const id = request.headers.get("mcp-session-id");
59
+ if (id) {
60
+ const known = sessions.get(id);
61
+ if (!known || known.clientId !== auth.clientId)
62
+ return sessionMissing();
63
+ known.seen = now();
64
+ return known.transport.handleRequest(request, { authInfo: auth });
65
+ }
66
+ const server = build();
67
+ const transport = new WebStandardStreamableHTTPServerTransport({
68
+ sessionIdGenerator: /* @__PURE__ */ __name(() => randomUUID(), "sessionIdGenerator"),
69
+ onsessionclosed: /* @__PURE__ */ __name((closed) => void sessions.delete(closed), "onsessionclosed")
70
+ });
71
+ await server.connect(transport);
72
+ const response = await transport.handleRequest(request, { authInfo: auth });
73
+ if (!transport.sessionId) {
74
+ await server.close();
75
+ return response;
76
+ }
77
+ sessions.set(transport.sessionId, { transport, close: /* @__PURE__ */ __name(() => server.close(), "close"), clientId: auth.clientId, seen: now() });
78
+ while (sessions.size > MAX_SESSIONS)
79
+ await drop(sessions.keys().next().value);
80
+ return response;
81
+ }, "handle");
82
+ return {
83
+ handle,
84
+ close: /* @__PURE__ */ __name(async () => {
85
+ for (const id of [...sessions.keys()])
86
+ await drop(id);
87
+ }, "close")
88
+ };
89
+ }, "legacySessions");
90
+ var metadataRequest = /* @__PURE__ */ __name((request, path, base) => {
91
+ const url = new URL(request.url);
92
+ const inserted = base && path === `${AS_METADATA}${base}`;
93
+ if (!inserted && url.pathname === path)
94
+ return request;
95
+ url.pathname = inserted ? AS_METADATA : path;
96
+ return new Request(url, { method: request.method, headers: request.headers });
97
+ }, "metadataRequest");
98
+ var toolsIn = /* @__PURE__ */ __name(async (request) => {
99
+ if (request.method !== "POST")
100
+ return [];
101
+ try {
102
+ return calledTools(await request.clone().json());
103
+ } catch {
104
+ return [];
105
+ }
106
+ }, "toolsIn");
107
+ var serveOverHttp = /* @__PURE__ */ __name(async (build, options) => {
108
+ const { publicUrl, port, tokenFile, appName, onCode, onError, now, lockFile, version } = options;
109
+ const lock = lockFile ? httpLock(lockFile, {
110
+ pid: process.pid,
111
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
112
+ port,
113
+ publicUrl: publicUrl.href,
114
+ ...version ? { version } : {}
115
+ }) : void 0;
116
+ if (lock?.held)
117
+ throw new CliError("validation_error", `${appName} already serves MCP over HTTP for this profile on port ${lock.held.port} (PID ${lock.held.pid}, since ${lock.held.startedAt})`);
118
+ const base = publicUrl.pathname === "/" ? "" : publicUrl.pathname.replace(/\/+$/, "");
119
+ const issuer = new URL(`${publicUrl.origin}${base}`);
120
+ const resource = new URL(`${base}${MCP_PATH}`, publicUrl.origin);
121
+ const mcpPath = resource.pathname;
122
+ const publicPath = /* @__PURE__ */ __name((path) => base && path !== base && !path.startsWith(`${base}/`) && !path.startsWith("/.well-known/") ? `${base}${path}` : path, "publicPath");
123
+ const login = ownerLogin({
124
+ issuer,
125
+ resource,
126
+ file: tokenFile,
127
+ appName,
128
+ onCode: /* @__PURE__ */ __name((code, expires) => {
129
+ lock?.update({ loginCode: code, loginCodeExpiresAt: expires.toISOString() });
130
+ onCode(code, expires);
131
+ }, "onCode"),
132
+ ...now ? { now } : {}
133
+ });
134
+ const insecure = issuer.protocol === "http:" && LOCAL.includes(issuer.hostname);
135
+ const mcp = createMcpHandler(build, { legacy: "reject", ...onError ? { onerror: onError } : {} });
136
+ const legacy = legacySessions(build, now ?? Date.now);
137
+ const bearer = requireBearerAuth({
138
+ verifier: login.verifier,
139
+ resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(resource)
140
+ });
141
+ const activity = activityRecorder(httpActivityFile(tokenFile), now);
142
+ const allowedHosts = [.../* @__PURE__ */ new Set([publicUrl.hostname, ...LOCAL])];
143
+ const allowedOrigins = [publicUrl.origin];
144
+ const listening = await listen(async (request) => {
145
+ const refused = hostHeaderValidationResponse(request, allowedHosts);
146
+ if (refused)
147
+ return refused;
148
+ const path = publicPath(new URL(request.url).pathname);
149
+ const discovery = oauthMetadataResponse(metadataRequest(request, path, base), {
150
+ oauthMetadata: login.metadata,
151
+ resourceServerUrl: resource,
152
+ resourceName: appName,
153
+ ...insecure ? { dangerouslyAllowInsecureIssuerUrl: true } : {}
154
+ });
155
+ if (discovery)
156
+ return discovery;
157
+ if (Number(request.headers.get("content-length") ?? 0) > MAX_LOGIN_BODY && path !== mcpPath)
158
+ return new Response("Request too large", { status: 413 });
159
+ const origin = request.headers.get("origin");
160
+ if (origin && !allowedOrigins.includes(origin))
161
+ return new Response("Origin not allowed", { status: 403 });
162
+ const answered = await login.handle(request, path);
163
+ if (answered)
164
+ return answered;
165
+ if (path !== mcpPath)
166
+ return new Response("Not found", { status: 404 });
167
+ const auth = await bearer(request);
168
+ if (auth instanceof Response)
169
+ return auth;
170
+ activity.record(auth.clientId, await toolsIn(request));
171
+ return await isLegacyRequest(request) ? legacy.handle(request, auth) : mcp.fetch(request, { authInfo: auth });
172
+ }, { host: "127.0.0.1", port }).catch((error) => {
173
+ login.close();
174
+ lock?.release();
175
+ throw error;
176
+ });
177
+ lock?.update({ listeningAt: (/* @__PURE__ */ new Date()).toISOString() });
178
+ return {
179
+ url: listening.url,
180
+ close: /* @__PURE__ */ __name(async () => {
181
+ login.close();
182
+ activity.flush();
183
+ try {
184
+ await listening.close();
185
+ await legacy.close();
186
+ await mcp.close();
187
+ } finally {
188
+ lock?.release();
189
+ }
190
+ }, "close")
191
+ };
192
+ }, "serveOverHttp");
193
+ export {
194
+ MCP_PATH,
195
+ serveOverHttp
196
+ };