@yoonion/mimi-seed-mcp 0.27.0 → 0.29.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.
- package/README.md +3 -2
- package/assets/agent-guide.md +7 -0
- package/dist/i18n/manifest-en.js +3 -0
- package/dist/i18n/tools-en/index.js +2 -0
- package/dist/i18n/tools-en/market.d.ts +15 -0
- package/dist/i18n/tools-en/market.js +14 -0
- package/dist/lib/human-approval.d.ts +7 -1
- package/dist/lib/human-approval.js +17 -5
- package/dist/lib/telegram-approval.d.ts +56 -0
- package/dist/lib/telegram-approval.js +382 -0
- package/dist/lib/tool-menu.js +2 -1
- package/dist/lib/tool-registrar.d.ts +1 -0
- package/dist/lib/tool-registrar.js +10 -2
- package/dist/market/tools.d.ts +137 -0
- package/dist/market/tools.js +377 -0
- package/dist/registers/market.d.ts +2 -0
- package/dist/registers/market.js +46 -0
- package/dist/server.js +3 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/tool-manifest.json +24 -2
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { catalog } from '#core/lang.js';
|
|
3
|
+
import { fetchWithTimeout } from './http.js';
|
|
4
|
+
import { callKey, DECLINE_COOLDOWN_MS, oneLine } from './human-approval.js';
|
|
5
|
+
/**
|
|
6
|
+
* 텔레그램 승인 채널 — `MIMI_SEED_APPROVAL=telegram`.
|
|
7
|
+
*
|
|
8
|
+
* 왜: 사람이 옆에 없는 봇(헤드리스 에이전트)의 MCP 클라이언트는 승인 대화상자(elicitation)를 띄우지 못한다. 그래서
|
|
9
|
+
* 예전에는 `auto`(에이전트의 confirm 만으로 실행)·`required`(전부 거부)·`off`(게이트 없음) 중 하나를 골라야 했다.
|
|
10
|
+
* 이 모드는 승인을 **에이전트가 닿지 않는 채널**로 보낸다: 승인 전용 텔레그램 봇이 지정한 채팅에 [승인]/[거절] 버튼을
|
|
11
|
+
* 보내고, mimi-seed 가 `getUpdates` 로 직접 답을 받는다. 버튼을 누른 사람이 허용 목록의 사용자 ID 여야만 인정한다 —
|
|
12
|
+
* 에이전트는 사용자의 텔레그램 계정으로 버튼을 누를 수 없으므로 스스로 승인하지 못한다.
|
|
13
|
+
*
|
|
14
|
+
* 흐름 (도구 호출 타임아웃이 짧은 클라이언트를 위해 비동기):
|
|
15
|
+
* 1. 첫 확정 호출 → 승인 요청 메시지를 보내고 최대 `MIMI_SEED_APPROVAL_WAIT_SECONDS` 동안 답을 기다린다.
|
|
16
|
+
* 2. 그 안에 답이 없으면 실행하지 않고 "⏳ 대기 중" 을 돌려준다. 에이전트가 **같은 인자 그대로** 다시 호출하면 같은
|
|
17
|
+
* 요청의 답을 확인한다 (인자가 바뀌면 다른 요청이다 — 승인은 도구 + 인자 해시에 묶인다).
|
|
18
|
+
* 3. 승인은 한 번만 쓰인다. 거절은 같은 호출을 쿨다운 동안 묻지 않고 거부한다 (elicitation 경로와 같은 피로 공격 방지).
|
|
19
|
+
*
|
|
20
|
+
* 지키지 못하는 것: 같은 호스트에서 셸을 가진 에이전트는 이 프로세스의 환경을 바꾸거나 자격증명 파일을 직접 쓸 수 있다.
|
|
21
|
+
* 이 게이트는 MCP 도구로만 움직이는 에이전트(프롬프트 인젝션)를 막는다.
|
|
22
|
+
*
|
|
23
|
+
* 제약: 텔레그램은 한 봇 토큰의 `getUpdates` 를 동시에 하나만 허용한다 (409). mimi-seed 프로세스(=봇 하나)마다
|
|
24
|
+
* 승인 봇 토큰을 따로 쓰고, 그 봇에 웹훅을 걸지 않는다.
|
|
25
|
+
*/
|
|
26
|
+
export const TELEGRAM_TOKEN_ENV = 'MIMI_SEED_APPROVAL_TELEGRAM_TOKEN';
|
|
27
|
+
export const TELEGRAM_CHAT_ENV = 'MIMI_SEED_APPROVAL_TELEGRAM_CHAT_ID';
|
|
28
|
+
export const TELEGRAM_USERS_ENV = 'MIMI_SEED_APPROVAL_TELEGRAM_USER_IDS';
|
|
29
|
+
export const APPROVAL_WAIT_ENV = 'MIMI_SEED_APPROVAL_WAIT_SECONDS';
|
|
30
|
+
/** 한 번의 도구 호출이 답을 기다리는 기본 시간. 많은 MCP 클라이언트의 도구 호출 타임아웃(60초)보다 짧게. */
|
|
31
|
+
export const DEFAULT_WAIT_SECONDS = 40;
|
|
32
|
+
export const MAX_WAIT_SECONDS = 600;
|
|
33
|
+
/** 승인 요청(과 받은 승인)의 수명. 지나면 메시지 버튼을 내리고 다음 호출이 새로 묻는다. */
|
|
34
|
+
export const TELEGRAM_REQUEST_TTL_MS = 30 * 60 * 1000;
|
|
35
|
+
/** 동시에 열어 둘 수 있는 요청 수 — 요청을 쏟아 내 하나쯤 승인되길 노리는 호출을 막는다. */
|
|
36
|
+
export const TELEGRAM_MAX_PENDING = 3;
|
|
37
|
+
const LONG_POLL_SECONDS = 10;
|
|
38
|
+
/** 텔레그램 메시지 상한은 4096자 — 결과 줄을 덧붙일 여유를 남긴다. */
|
|
39
|
+
const MESSAGE_MAX = 3600;
|
|
40
|
+
const API_TIMEOUT_MS = 15_000;
|
|
41
|
+
const T = catalog({
|
|
42
|
+
missing: (env) => `${env} 가 설정되지 않았다`,
|
|
43
|
+
badToken: (env) => `${env} 가 텔레그램 봇 토큰 형식이 아니다`,
|
|
44
|
+
badChat: (env) => `${env} 는 숫자 채팅 ID 여야 한다`,
|
|
45
|
+
badUsers: (env) => `${env} 는 쉼표로 구분한 숫자 사용자 ID 여야 한다`,
|
|
46
|
+
groupNeedsUsers: (chat, users) => `${chat} 가 그룹 채팅이면 승인할 사람을 ${users} 로 정해야 한다`,
|
|
47
|
+
misconfigured: (name, problem) => `⛔ \`${name}\` 은(는) 텔레그램 승인이 필요한데 승인 채널 설정이 올바르지 않아 실행하지 않았다 (${problem}). ` +
|
|
48
|
+
`아무것도 바꾸지 않았다. 사용자가 이 MCP 서버의 설정을 고쳐야 한다 — 에이전트가 바꾸지 말 것.`,
|
|
49
|
+
title: (title) => `⚠️ 실행 승인 요청 — ${title}`,
|
|
50
|
+
from: (client) => `요청한 에이전트: ${client}`,
|
|
51
|
+
intro: 'AI 에이전트가 되돌리기 어렵거나 외부에 공개되거나 자격증명을 다루는 작업을 실행하려 한다. 아래 인자가 의도한 것과 같을 때만 승인한다.',
|
|
52
|
+
truncated: '⚠️ 일부 값이 너무 길어 생략했다. 생략된 부분을 확인할 수 없다면 거절한다.',
|
|
53
|
+
args: '실행 인자:',
|
|
54
|
+
none: '(없음)',
|
|
55
|
+
footer: (id, minutes) => `요청 ${id} · ${minutes}분 뒤 만료`,
|
|
56
|
+
approveButton: '✅ 승인',
|
|
57
|
+
declineButton: '❌ 거절',
|
|
58
|
+
approvedLine: (who) => `✅ ${who} 님이 승인했다 — 에이전트가 같은 호출을 다시 하면 한 번 실행된다.`,
|
|
59
|
+
declinedLine: (who) => `❌ ${who} 님이 거절했다 — 실행하지 않는다.`,
|
|
60
|
+
expiredLine: '⌛ 만료된 요청 — 실행하지 않는다.',
|
|
61
|
+
toastApproved: '승인했습니다',
|
|
62
|
+
toastDeclined: '거절했습니다',
|
|
63
|
+
toastExpired: '만료된 요청입니다',
|
|
64
|
+
toastNotAllowed: '이 요청을 승인할 권한이 없습니다',
|
|
65
|
+
pending: (name, minutes) => `⏳ \`${name}\` 실행 승인을 텔레그램으로 사용자에게 요청했고 아직 답이 없다. 아무것도 바꾸지 않았다. ` +
|
|
66
|
+
`사용자가 승인한 뒤 **인자를 하나도 바꾸지 말고** 같은 호출을 다시 하면 그때 한 번 실행된다 (요청은 약 ${minutes}분 뒤 만료). ` +
|
|
67
|
+
`인자를 바꾸면 새 요청이 된다. 답을 재촉하려고 짧은 간격으로 반복 호출하지 말고, 사용자에게 텔레그램 승인을 기다린다고 알릴 것.`,
|
|
68
|
+
declined: (name) => `⛔ 사용자가 텔레그램에서 \`${name}\` 실행을 거절해 아무것도 바꾸지 않았다. 다시 시도하지 말고 사용자에게 어떻게 할지 물을 것.`,
|
|
69
|
+
cooldown: (name, minutes) => `⛔ 같은 \`${name}\` 요청을 사용자가 방금 거절해 다시 묻지 않고 거부했다 (${minutes}분 후 다시 물을 수 있다). 다시 시도하지 말 것.`,
|
|
70
|
+
alreadyUsed: (name) => `⛔ 이 승인은 동시에 들어온 같은 \`${name}\` 호출이 이미 한 번 썼다. 이 호출은 실행하지 않았다. 한 번 더 실행해야 한다면 다시 호출해 새 승인을 받을 것.`,
|
|
71
|
+
tooMany: (name, max) => `⛔ 답을 기다리는 승인 요청이 이미 ${max}개라 \`${name}\` 은(는) 새로 묻지 않았다. 아무것도 바꾸지 않았다. 앞의 요청이 끝난 뒤 다시 할 것.`,
|
|
72
|
+
failed: (name, reason) => `⛔ \`${name}\` 의 텔레그램 승인을 확인하지 못해 아무것도 바꾸지 않았다 (${reason}). 자동으로 반복하지 말고 사용자에게 알릴 것.`,
|
|
73
|
+
conflict: (env) => `다른 프로세스가 같은 승인 봇 토큰으로 업데이트를 받고 있거나 그 봇에 웹훅이 걸려 있다 — mimi-seed 프로세스마다 ${env} 를 따로 써야 한다`,
|
|
74
|
+
aborted: '호출이 중단됨',
|
|
75
|
+
}, {
|
|
76
|
+
missing: (env) => `${env} is not set`,
|
|
77
|
+
badToken: (env) => `${env} is not a Telegram bot token`,
|
|
78
|
+
badChat: (env) => `${env} must be a numeric chat id`,
|
|
79
|
+
badUsers: (env) => `${env} must be comma-separated numeric user ids`,
|
|
80
|
+
groupNeedsUsers: (chat, users) => `${chat} is a group chat, so ${users} must name who may approve`,
|
|
81
|
+
misconfigured: (name, problem) => `⛔ \`${name}\` needs Telegram approval, but the approval channel is misconfigured, so it did not run (${problem}). ` +
|
|
82
|
+
`Nothing was changed. The user must fix this MCP server's settings — do not change them yourself.`,
|
|
83
|
+
title: (title) => `⚠️ Approval needed — ${title}`,
|
|
84
|
+
from: (client) => `Requested by agent: ${client}`,
|
|
85
|
+
intro: 'An AI agent is about to run an action that is hard to undo, publishes externally, or handles credentials. Approve only if the arguments below are what you intended.',
|
|
86
|
+
truncated: '⚠️ Some values were too long and were shortened. Decline if you cannot check the omitted part.',
|
|
87
|
+
args: 'Arguments:',
|
|
88
|
+
none: '(none)',
|
|
89
|
+
footer: (id, minutes) => `Request ${id} · expires in ${minutes} min`,
|
|
90
|
+
approveButton: '✅ Approve',
|
|
91
|
+
declineButton: '❌ Decline',
|
|
92
|
+
approvedLine: (who) => `✅ Approved by ${who} — it runs once when the agent repeats the same call.`,
|
|
93
|
+
declinedLine: (who) => `❌ Declined by ${who} — it will not run.`,
|
|
94
|
+
expiredLine: '⌛ Expired request — it will not run.',
|
|
95
|
+
toastApproved: 'Approved',
|
|
96
|
+
toastDeclined: 'Declined',
|
|
97
|
+
toastExpired: 'This request has expired',
|
|
98
|
+
toastNotAllowed: 'You are not allowed to approve this request',
|
|
99
|
+
pending: (name, minutes) => `⏳ Approval for \`${name}\` was requested from the user on Telegram and has no answer yet. Nothing was changed. ` +
|
|
100
|
+
`Once the user approves, repeat the same call **with exactly the same arguments** and it runs once (the request expires in about ${minutes} min). ` +
|
|
101
|
+
`Changing any argument makes a new request. Do not call again in a tight loop to hurry the answer; tell the user you are waiting for their Telegram approval.`,
|
|
102
|
+
declined: (name) => `⛔ The user declined \`${name}\` on Telegram, so nothing was changed. Do not retry — ask the user how to proceed.`,
|
|
103
|
+
cooldown: (name, minutes) => `⛔ The user just declined this same \`${name}\` request, so it was refused without asking again (it can be asked again in ${minutes} min). Do not retry.`,
|
|
104
|
+
alreadyUsed: (name) => `⛔ This approval was already used once by an identical \`${name}\` call that was waiting at the same time. This call did not run. If it must run again, call again to get a new approval.`,
|
|
105
|
+
tooMany: (name, max) => `⛔ ${max} approval requests are already waiting for an answer, so \`${name}\` was not asked. Nothing was changed. Try again after those are answered.`,
|
|
106
|
+
failed: (name, reason) => `⛔ Could not check Telegram approval for \`${name}\`, so nothing was changed (${reason}). Do not retry automatically; tell the user.`,
|
|
107
|
+
conflict: (env) => `another process is receiving updates with the same approval bot token, or that bot has a webhook — each mimi-seed process needs its own ${env}`,
|
|
108
|
+
aborted: 'call aborted',
|
|
109
|
+
});
|
|
110
|
+
const TOKEN_SHAPE = /^\d+:[A-Za-z0-9_-]+$/;
|
|
111
|
+
const CHAT_SHAPE = /^-?\d+$/;
|
|
112
|
+
const USER_SHAPE = /^\d+$/;
|
|
113
|
+
/** 환경에서 텔레그램 승인 설정을 읽는다. 값이 틀리면 원인을 돌려준다 — 토큰 값은 절대 메시지에 넣지 않는다. */
|
|
114
|
+
export function telegramConfig(env) {
|
|
115
|
+
const m = T();
|
|
116
|
+
const token = env[TELEGRAM_TOKEN_ENV]?.trim();
|
|
117
|
+
if (!token)
|
|
118
|
+
return { problem: m.missing(TELEGRAM_TOKEN_ENV) };
|
|
119
|
+
if (!TOKEN_SHAPE.test(token))
|
|
120
|
+
return { problem: m.badToken(TELEGRAM_TOKEN_ENV) };
|
|
121
|
+
const chatId = env[TELEGRAM_CHAT_ENV]?.trim();
|
|
122
|
+
if (!chatId)
|
|
123
|
+
return { problem: m.missing(TELEGRAM_CHAT_ENV) };
|
|
124
|
+
if (!CHAT_SHAPE.test(chatId))
|
|
125
|
+
return { problem: m.badChat(TELEGRAM_CHAT_ENV) };
|
|
126
|
+
const users = (env[TELEGRAM_USERS_ENV] ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
127
|
+
if (users.some((u) => !USER_SHAPE.test(u)))
|
|
128
|
+
return { problem: m.badUsers(TELEGRAM_USERS_ENV) };
|
|
129
|
+
if (users.length === 0) {
|
|
130
|
+
// 1:1 채팅의 채팅 ID 는 상대 사용자 ID 와 같다. 그룹(음수 ID)은 누가 승인할지 따로 정해야 한다.
|
|
131
|
+
if (chatId.startsWith('-'))
|
|
132
|
+
return { problem: m.groupNeedsUsers(TELEGRAM_CHAT_ENV, TELEGRAM_USERS_ENV) };
|
|
133
|
+
users.push(chatId);
|
|
134
|
+
}
|
|
135
|
+
return { config: { token, chatId, userIds: new Set(users) } };
|
|
136
|
+
}
|
|
137
|
+
/** 한 호출이 답을 기다리는 시간(초). 잘못된 값은 기본값. */
|
|
138
|
+
export function approvalWaitSeconds(env) {
|
|
139
|
+
const raw = env[APPROVAL_WAIT_ENV]?.trim();
|
|
140
|
+
if (!raw || !/^\d+$/.test(raw))
|
|
141
|
+
return DEFAULT_WAIT_SECONDS;
|
|
142
|
+
return Math.min(Number(raw), MAX_WAIT_SECONDS);
|
|
143
|
+
}
|
|
144
|
+
// ── 텔레그램 Bot API ───────────────────────────────────────────────────────
|
|
145
|
+
class TelegramError extends Error {
|
|
146
|
+
code;
|
|
147
|
+
constructor(code, message) {
|
|
148
|
+
super(message);
|
|
149
|
+
this.code = code;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/** 토큰은 URL 경로에 들어간다 — 타임아웃·네트워크 오류 문구(엔드포인트 라벨)에 섞여 나오지 않게 지운다. */
|
|
153
|
+
const redact = (text, token) => oneLine(text.split(token).join('<token>'));
|
|
154
|
+
async function telegram(cfg, method, body, timeoutMs = API_TIMEOUT_MS) {
|
|
155
|
+
const url = new URL(method, `https://api.telegram.org/bot${cfg.token}/`);
|
|
156
|
+
let res;
|
|
157
|
+
try {
|
|
158
|
+
res = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }, { timeoutMs, maxAttempts: 1 });
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
throw new TelegramError(undefined, redact(e instanceof Error ? e.message : String(e), cfg.token));
|
|
162
|
+
}
|
|
163
|
+
const json = (await res.json().catch(() => null));
|
|
164
|
+
if (!json?.ok) {
|
|
165
|
+
const code = json?.error_code ?? res.status;
|
|
166
|
+
throw new TelegramError(code, redact(`Telegram ${method} ${code}: ${json?.description ?? res.statusText}`, cfg.token));
|
|
167
|
+
}
|
|
168
|
+
return json.result;
|
|
169
|
+
}
|
|
170
|
+
const states = new WeakMap();
|
|
171
|
+
const stateOf = (server) => {
|
|
172
|
+
let s = states.get(server);
|
|
173
|
+
if (!s)
|
|
174
|
+
states.set(server, (s = { byKey: new Map(), byId: new Map(), refusedUntil: new Map(), offset: 0 }));
|
|
175
|
+
return s;
|
|
176
|
+
};
|
|
177
|
+
function forget(st, req) {
|
|
178
|
+
if (st.byKey.get(req.key) === req)
|
|
179
|
+
st.byKey.delete(req.key);
|
|
180
|
+
st.byId.delete(req.id);
|
|
181
|
+
}
|
|
182
|
+
/** 수명이 다한 요청을 버리고 그 메시지의 버튼을 내린다 (실패해도 무시 — 버튼을 눌러도 만료로 답한다). */
|
|
183
|
+
function prune(cfg, st, t) {
|
|
184
|
+
for (const [k, until] of st.refusedUntil)
|
|
185
|
+
if (until <= t)
|
|
186
|
+
st.refusedUntil.delete(k);
|
|
187
|
+
for (const req of [...st.byKey.values()]) {
|
|
188
|
+
if (req.expiresAt > t)
|
|
189
|
+
continue;
|
|
190
|
+
forget(st, req);
|
|
191
|
+
void closeMessage(cfg, req.messageId, undefined, T().expiredLine);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** 메시지 끝에 결과 한 줄을 붙이고 버튼을 없앤다. 원문을 모르면 버튼만 없앤다. */
|
|
195
|
+
async function closeMessage(cfg, messageId, text, line) {
|
|
196
|
+
try {
|
|
197
|
+
if (text === undefined) {
|
|
198
|
+
await telegram(cfg, 'editMessageReplyMarkup', { chat_id: cfg.chatId, message_id: messageId, reply_markup: { inline_keyboard: [] } });
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
await telegram(cfg, 'editMessageText', {
|
|
202
|
+
chat_id: cfg.chatId,
|
|
203
|
+
message_id: messageId,
|
|
204
|
+
text: `${text}\n\n${line}`.slice(0, 4096),
|
|
205
|
+
reply_markup: { inline_keyboard: [] },
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
process.stderr.write(`[mimi-seed] telegram approval: could not update message (${e instanceof Error ? e.message : String(e)})\n`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
async function answerCallback(cfg, id, text) {
|
|
214
|
+
try {
|
|
215
|
+
await telegram(cfg, 'answerCallbackQuery', { callback_query_id: id, text });
|
|
216
|
+
}
|
|
217
|
+
catch (e) {
|
|
218
|
+
process.stderr.write(`[mimi-seed] telegram approval: could not answer button (${e instanceof Error ? e.message : String(e)})\n`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const CALLBACK_DATA = /^([ad]):([0-9a-f]{16})$/;
|
|
222
|
+
const displayName = (u) => oneLine(u.username ? `@${u.username}` : u.first_name || String(u.id)).slice(0, 64);
|
|
223
|
+
async function handleCallback(cfg, st, cq, t) {
|
|
224
|
+
const m = T();
|
|
225
|
+
const match = CALLBACK_DATA.exec(cq.data ?? '');
|
|
226
|
+
if (!match)
|
|
227
|
+
return;
|
|
228
|
+
const [, verb, id] = match;
|
|
229
|
+
// 채팅과 누른 사람을 둘 다 본다 — 승인 봇을 다른 채팅에 끌어들이거나, 그룹의 다른 사람이 누른 버튼은 인정하지 않는다.
|
|
230
|
+
const inChat = cq.message !== undefined && String(cq.message.chat.id) === cfg.chatId;
|
|
231
|
+
if (!inChat || !cfg.userIds.has(String(cq.from.id))) {
|
|
232
|
+
process.stderr.write(`[mimi-seed] telegram approval: ignored a button from user ${cq.from.id} (not allowed)\n`);
|
|
233
|
+
await answerCallback(cfg, cq.id, m.toastNotAllowed);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const req = st.byId.get(id);
|
|
237
|
+
if (!req || req.status !== 'pending' || req.expiresAt <= t || req.messageId !== cq.message?.message_id) {
|
|
238
|
+
// 다른(이전) 프로세스의 요청이거나 이미 끝난 요청 — 버튼만 내린다.
|
|
239
|
+
await answerCallback(cfg, cq.id, m.toastExpired);
|
|
240
|
+
if (cq.message && !req)
|
|
241
|
+
await closeMessage(cfg, cq.message.message_id, cq.message.text, m.expiredLine);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const who = displayName(cq.from);
|
|
245
|
+
req.status = verb === 'a' ? 'approved' : 'declined';
|
|
246
|
+
if (req.status === 'declined') {
|
|
247
|
+
// 거절은 여기서 끝낸다 — 에이전트는 거절된 호출을 다시 부르지 않으므로, 그 호출을 기다리면 요청이 자리를 차지한다.
|
|
248
|
+
forget(st, req);
|
|
249
|
+
st.refusedUntil.set(req.key, t + DECLINE_COOLDOWN_MS);
|
|
250
|
+
}
|
|
251
|
+
process.stderr.write(`[mimi-seed] telegram approval ${req.id}: ${req.status} by user ${cq.from.id}\n`);
|
|
252
|
+
await answerCallback(cfg, cq.id, req.status === 'approved' ? m.toastApproved : m.toastDeclined);
|
|
253
|
+
await closeMessage(cfg, req.messageId, cq.message?.text, req.status === 'approved' ? m.approvedLine(who) : m.declinedLine(who));
|
|
254
|
+
}
|
|
255
|
+
function pollOnce(cfg, st, timeoutSeconds, now) {
|
|
256
|
+
if (st.poll)
|
|
257
|
+
return st.poll;
|
|
258
|
+
st.poll = (async () => {
|
|
259
|
+
const updates = await telegram(cfg, 'getUpdates', { offset: st.offset, timeout: timeoutSeconds, allowed_updates: ['callback_query'] }, timeoutSeconds * 1000 + API_TIMEOUT_MS);
|
|
260
|
+
for (const u of updates) {
|
|
261
|
+
st.offset = Math.max(st.offset, u.update_id + 1);
|
|
262
|
+
if (u.callback_query)
|
|
263
|
+
await handleCallback(cfg, st, u.callback_query, now());
|
|
264
|
+
}
|
|
265
|
+
})().finally(() => {
|
|
266
|
+
st.poll = undefined;
|
|
267
|
+
});
|
|
268
|
+
return st.poll;
|
|
269
|
+
}
|
|
270
|
+
function buildMessage(server, call, id) {
|
|
271
|
+
const m = T();
|
|
272
|
+
const client = server.server.getClientVersion()?.name;
|
|
273
|
+
const head = [
|
|
274
|
+
m.title(call.title),
|
|
275
|
+
...(client ? [m.from(oneLine(client).slice(0, 80))] : []),
|
|
276
|
+
'',
|
|
277
|
+
m.intro,
|
|
278
|
+
];
|
|
279
|
+
const footer = ['', m.footer(id.slice(0, 6), Math.round(TELEGRAM_REQUEST_TTL_MS / 60_000))];
|
|
280
|
+
let args = call.argLines.length ? call.argLines.join('\n') : ` ${m.none}`;
|
|
281
|
+
let truncated = call.truncated;
|
|
282
|
+
const budget = MESSAGE_MAX - [...head, m.truncated, m.args, ...footer].join('\n').length - 8;
|
|
283
|
+
if (args.length > budget) {
|
|
284
|
+
args = `${args.slice(0, Math.max(0, budget - 2))} …`;
|
|
285
|
+
truncated = true;
|
|
286
|
+
}
|
|
287
|
+
return [...head, ...(truncated ? ['', m.truncated] : []), '', m.args, args, ...footer].join('\n');
|
|
288
|
+
}
|
|
289
|
+
const failReason = (e) => e instanceof TelegramError && e.code === 409 ? T().conflict(TELEGRAM_TOKEN_ENV) : e instanceof Error ? e.message : String(e);
|
|
290
|
+
const refuse = (text) => ({ isError: true, content: [{ type: 'text', text }] });
|
|
291
|
+
/** 승인되면 `null`, 아니면 실행 대신 돌려줄 결과. */
|
|
292
|
+
export async function requestTelegramApproval(server, call, options = {}) {
|
|
293
|
+
const m = T();
|
|
294
|
+
const env = options.env ?? process.env;
|
|
295
|
+
const now = options.now ?? Date.now;
|
|
296
|
+
const { config, problem } = telegramConfig(env);
|
|
297
|
+
if (!config)
|
|
298
|
+
return refuse(m.misconfigured(call.name, problem));
|
|
299
|
+
const st = stateOf(server);
|
|
300
|
+
const key = callKey(call.name, call.args);
|
|
301
|
+
prune(config, st, now());
|
|
302
|
+
const until = st.refusedUntil.get(key);
|
|
303
|
+
if (until !== undefined && until > now())
|
|
304
|
+
return refuse(m.cooldown(call.name, Math.ceil((until - now()) / 60_000)));
|
|
305
|
+
let req = st.byKey.get(key);
|
|
306
|
+
if (!req) {
|
|
307
|
+
// 자리가 찼다면 먼저 쌓인 답을 읽는다 — 다른 요청에 눌린 거절·승인이 자리를 비울 수 있다.
|
|
308
|
+
const open = () => [...st.byKey.values()].filter((r) => r.status === 'pending').length;
|
|
309
|
+
if (open() >= TELEGRAM_MAX_PENDING) {
|
|
310
|
+
try {
|
|
311
|
+
await pollOnce(config, st, 0, now);
|
|
312
|
+
}
|
|
313
|
+
catch (e) {
|
|
314
|
+
return refuse(m.failed(call.name, failReason(e)));
|
|
315
|
+
}
|
|
316
|
+
const t = now();
|
|
317
|
+
const until2 = st.refusedUntil.get(key);
|
|
318
|
+
if (until2 !== undefined && until2 > t)
|
|
319
|
+
return refuse(m.cooldown(call.name, Math.ceil((until2 - t) / 60_000)));
|
|
320
|
+
// 기다리는 사이 같은 호출이 자리를 잡았을 수 있다 — 그러면 그 요청을 함께 기다린다.
|
|
321
|
+
req = st.byKey.get(key);
|
|
322
|
+
if (!req && open() >= TELEGRAM_MAX_PENDING)
|
|
323
|
+
return refuse(m.tooMany(call.name, TELEGRAM_MAX_PENDING));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (!req) {
|
|
327
|
+
const id = randomBytes(8).toString('hex');
|
|
328
|
+
// 보내기 전에 자리를 잡는다 — 동시에 들어온 같은 호출이 메시지를 두 번 보내지 않게. 메시지 ID 는 보낸 뒤 채운다
|
|
329
|
+
// (버튼은 메시지가 있어야 눌리므로 그 전에 콜백이 올 수 없다).
|
|
330
|
+
const pending = { id, key, messageId: -1, expiresAt: now() + TELEGRAM_REQUEST_TTL_MS, status: 'pending' };
|
|
331
|
+
req = pending;
|
|
332
|
+
st.byKey.set(key, pending);
|
|
333
|
+
st.byId.set(id, pending);
|
|
334
|
+
try {
|
|
335
|
+
const sent = await telegram(config, 'sendMessage', {
|
|
336
|
+
chat_id: config.chatId,
|
|
337
|
+
// parse_mode 없이 평문으로 보낸다 — 인자 값이 서식·링크로 해석되지 않게.
|
|
338
|
+
text: buildMessage(server, call, id),
|
|
339
|
+
link_preview_options: { is_disabled: true },
|
|
340
|
+
reply_markup: {
|
|
341
|
+
inline_keyboard: [[
|
|
342
|
+
{ text: m.approveButton, callback_data: `a:${id}` },
|
|
343
|
+
{ text: m.declineButton, callback_data: `d:${id}` },
|
|
344
|
+
]],
|
|
345
|
+
},
|
|
346
|
+
});
|
|
347
|
+
pending.messageId = sent.message_id;
|
|
348
|
+
}
|
|
349
|
+
catch (e) {
|
|
350
|
+
forget(st, pending);
|
|
351
|
+
return refuse(m.failed(call.name, e instanceof Error ? e.message : String(e)));
|
|
352
|
+
}
|
|
353
|
+
process.stderr.write(`[mimi-seed] telegram approval ${req.id}: asked for ${call.name}\n`);
|
|
354
|
+
}
|
|
355
|
+
const deadline = now() + approvalWaitSeconds(env) * 1000;
|
|
356
|
+
try {
|
|
357
|
+
do {
|
|
358
|
+
if (req.status !== 'pending')
|
|
359
|
+
break;
|
|
360
|
+
if (options.signal?.aborted)
|
|
361
|
+
return refuse(m.failed(call.name, m.aborted));
|
|
362
|
+
const left = Math.max(0, Math.ceil((deadline - now()) / 1000));
|
|
363
|
+
await pollOnce(config, st, Math.min(LONG_POLL_SECONDS, left), now);
|
|
364
|
+
} while (req.status === 'pending' && now() < deadline);
|
|
365
|
+
}
|
|
366
|
+
catch (e) {
|
|
367
|
+
return refuse(m.failed(call.name, failReason(e)));
|
|
368
|
+
}
|
|
369
|
+
if (req.status === 'approved') {
|
|
370
|
+
if (req.used)
|
|
371
|
+
return refuse(m.alreadyUsed(call.name));
|
|
372
|
+
req.used = true; // 한 번만 쓴다
|
|
373
|
+
forget(st, req);
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
if (req.status === 'declined') {
|
|
377
|
+
forget(st, req);
|
|
378
|
+
st.refusedUntil.set(key, now() + DECLINE_COOLDOWN_MS);
|
|
379
|
+
return refuse(m.declined(call.name));
|
|
380
|
+
}
|
|
381
|
+
return refuse(m.pending(call.name, Math.max(1, Math.ceil((req.expiresAt - now()) / 60_000))));
|
|
382
|
+
}
|
package/dist/lib/tool-menu.js
CHANGED
|
@@ -2,7 +2,7 @@ export const TOOL_MENU_URI = 'mimi-seed://tools/menu';
|
|
|
2
2
|
export const TOOL_SELECTION_URI = `${TOOL_MENU_URI}/{areas*}`;
|
|
3
3
|
const menuOrder = [
|
|
4
4
|
'ga4', 'bigquery', 'playstore', 'appstore', 'onestore', 'video', 'youtube', 'firebase', 'googleads',
|
|
5
|
-
'admob', 'drive', 'gsc', 'naver', 'instagram', 'threads', 'facebook', 'tiktok', 'crosspost',
|
|
5
|
+
'admob', 'drive', 'gsc', 'naver', 'market', 'instagram', 'threads', 'facebook', 'tiktok', 'crosspost',
|
|
6
6
|
'ci', 'jenkins', 'checks', 'android', 'iam', 'billing', 'ai', 'auth',
|
|
7
7
|
];
|
|
8
8
|
const labels = {
|
|
@@ -13,6 +13,7 @@ const labels = {
|
|
|
13
13
|
video: { ko: 'YouTube · 영상 제작', en: 'YouTube · Video production' },
|
|
14
14
|
youtube: { ko: 'YouTube · 업로드·채널 운영', en: 'YouTube · Upload and channel management' },
|
|
15
15
|
naver: { ko: '네이버 서치어드바이저', en: 'Naver Search Advisor' },
|
|
16
|
+
market: { ko: 'Mobile Store · 경쟁 앱 관찰 (App Store 공개 데이터)', en: 'Mobile Store · Competitor apps (App Store public data)' },
|
|
16
17
|
crosspost: { ko: '소셜 통합 게시', en: 'Cross-post to several social platforms' },
|
|
17
18
|
checks: { ko: '출시 상태·제출 전 점검', en: 'Release status and submission checks' },
|
|
18
19
|
android: { ko: 'Android 서명', en: 'Android signing' },
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { catalog } from '#core/lang.js';
|
|
3
3
|
import { approvalMode, clientCanElicit, requestHumanApproval } from './human-approval.js';
|
|
4
|
+
import { telegramConfig } from './telegram-approval.js';
|
|
4
5
|
/** 자체 확인 파라미터 이름 — manifest `ownGate` 도구는 이 중 하나를 스키마에 가져야 한다. */
|
|
5
6
|
export const CONFIRM_KEYS = ['confirm', 'confirmPublish', 'confirmVisible'];
|
|
6
7
|
/** 레지스트라가 주입한 가드의 preview 첫 줄. 테스트와 에이전트가 이 문자열로 dry-run 을 식별한다. */
|
|
@@ -223,7 +224,14 @@ export function createToolRegistrar(server, options) {
|
|
|
223
224
|
return {
|
|
224
225
|
toolsets,
|
|
225
226
|
manifest,
|
|
226
|
-
approvalStatus: () =>
|
|
227
|
+
approvalStatus: () => {
|
|
228
|
+
const mode = approvalMode(env);
|
|
229
|
+
return {
|
|
230
|
+
mode,
|
|
231
|
+
clientCanElicit: clientCanElicit(server),
|
|
232
|
+
...(mode === 'telegram' ? { telegramProblem: telegramConfig(env).problem } : {}),
|
|
233
|
+
};
|
|
234
|
+
},
|
|
227
235
|
tool(name, description, shape, handler, outputSchema) {
|
|
228
236
|
const meta = metaOf(name);
|
|
229
237
|
if (meta.deprecatedFor) {
|
|
@@ -272,7 +280,7 @@ export function createToolRegistrar(server, options) {
|
|
|
272
280
|
return gated(args, extra);
|
|
273
281
|
const signal = extra?.signal;
|
|
274
282
|
const { lines, truncated } = approvalArgLines(args);
|
|
275
|
-
const refusal = await requestHumanApproval(server, { name, title, args, argLines: lines, truncated }, { signal, mode: approvalMode(env) });
|
|
283
|
+
const refusal = await requestHumanApproval(server, { name, title, args, argLines: lines, truncated }, { signal, mode: approvalMode(env), env });
|
|
276
284
|
return refusal ?? gated(args, extra);
|
|
277
285
|
};
|
|
278
286
|
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 경쟁 앱 관찰 — App Store **공개** 데이터만 읽는다 (iTunes Search/Lookup API, 고객 리뷰 RSS).
|
|
3
|
+
*
|
|
4
|
+
* 자격증명이 없다. 남의 앱이라 App Store Connect API 는 못 쓰고, 다운로드·매출 같은 비공개 수치는
|
|
5
|
+
* 어디에서도 얻을 수 없다. Google Play 는 공개 API 가 없어 다루지 않는다 — 스토어 웹페이지 스크래핑은
|
|
6
|
+
* 약관상 애매하고 마크업이 바뀌면 조용히 틀린 값을 낸다.
|
|
7
|
+
*
|
|
8
|
+
* 변화 감지(watchApp)는 `~/.mimi-seed/market-watch/<country>-<appId>.json` 의 기준점과 비교한다.
|
|
9
|
+
* 기준점은 market_save_baseline(save: true)일 때만 바뀐다 — 확인만 한 호출이 기준점을 덮으면, 아무도 읽지 않은 실행이
|
|
10
|
+
* 그 사이의 변화를 지워 버린다.
|
|
11
|
+
*/
|
|
12
|
+
export declare const ITUNES_BASE = "https://itunes.apple.com";
|
|
13
|
+
export declare const COUNTRY_RE: RegExp;
|
|
14
|
+
/** 도구 입력용 — 대소문자를 받고 register 가 소문자로 바꾼다. */
|
|
15
|
+
export declare const COUNTRY_INPUT_RE: RegExp;
|
|
16
|
+
export declare const APP_ID_RE: RegExp;
|
|
17
|
+
/** 리뷰 RSS 는 페이지당 50개, 최대 10페이지(최근 500개)까지만 준다. */
|
|
18
|
+
export declare const REVIEW_MAX_PAGE = 10;
|
|
19
|
+
export declare const REVIEW_PAGE_SIZE = 50;
|
|
20
|
+
export declare const SEARCH_MAX_LIMIT = 50;
|
|
21
|
+
export interface AppSnapshot {
|
|
22
|
+
appId: number;
|
|
23
|
+
bundleId: string;
|
|
24
|
+
name: string;
|
|
25
|
+
developer: string;
|
|
26
|
+
url: string;
|
|
27
|
+
version: string;
|
|
28
|
+
currentVersionReleaseDate: string | null;
|
|
29
|
+
releaseNotes: string;
|
|
30
|
+
firstReleaseDate: string | null;
|
|
31
|
+
price: number;
|
|
32
|
+
formattedPrice: string | null;
|
|
33
|
+
currency: string | null;
|
|
34
|
+
averageUserRating: number | null;
|
|
35
|
+
userRatingCount: number | null;
|
|
36
|
+
averageUserRatingForCurrentVersion: number | null;
|
|
37
|
+
userRatingCountForCurrentVersion: number | null;
|
|
38
|
+
primaryGenre: string | null;
|
|
39
|
+
contentRating: string | null;
|
|
40
|
+
fileSizeBytes: number | null;
|
|
41
|
+
minimumOsVersion: string | null;
|
|
42
|
+
screenshotCount: number;
|
|
43
|
+
description: string;
|
|
44
|
+
}
|
|
45
|
+
export interface MarketReview {
|
|
46
|
+
id: string;
|
|
47
|
+
author: string;
|
|
48
|
+
rating: number;
|
|
49
|
+
version: string | null;
|
|
50
|
+
title: string;
|
|
51
|
+
content: string;
|
|
52
|
+
updated: string | null;
|
|
53
|
+
voteSum: number;
|
|
54
|
+
voteCount: number;
|
|
55
|
+
}
|
|
56
|
+
type Raw = Record<string, unknown>;
|
|
57
|
+
export declare function toSnapshot(r: Raw): AppSnapshot;
|
|
58
|
+
export interface SearchHit {
|
|
59
|
+
appId: number;
|
|
60
|
+
bundleId: string;
|
|
61
|
+
name: string;
|
|
62
|
+
developer: string;
|
|
63
|
+
version: string;
|
|
64
|
+
averageUserRating: number | null;
|
|
65
|
+
userRatingCount: number | null;
|
|
66
|
+
price: number;
|
|
67
|
+
primaryGenre: string | null;
|
|
68
|
+
url: string;
|
|
69
|
+
}
|
|
70
|
+
export declare function searchApps(opts: {
|
|
71
|
+
term: string;
|
|
72
|
+
country: string;
|
|
73
|
+
limit: number;
|
|
74
|
+
}): Promise<SearchHit[]>;
|
|
75
|
+
export declare function lookupApp(opts: {
|
|
76
|
+
appId?: string;
|
|
77
|
+
bundleId?: string;
|
|
78
|
+
country: string;
|
|
79
|
+
}): Promise<AppSnapshot>;
|
|
80
|
+
export declare function parseReviewFeed(body: unknown): {
|
|
81
|
+
reviews: MarketReview[];
|
|
82
|
+
lastPage: number;
|
|
83
|
+
};
|
|
84
|
+
export declare function listReviews(opts: {
|
|
85
|
+
appId: string;
|
|
86
|
+
country: string;
|
|
87
|
+
page: number;
|
|
88
|
+
}): Promise<{
|
|
89
|
+
page: number;
|
|
90
|
+
lastPage: number;
|
|
91
|
+
reviews: MarketReview[];
|
|
92
|
+
}>;
|
|
93
|
+
export interface WatchBaseline {
|
|
94
|
+
savedAt: string;
|
|
95
|
+
country: string;
|
|
96
|
+
snapshot: Omit<AppSnapshot, 'description'> & {
|
|
97
|
+
descriptionSha256: string;
|
|
98
|
+
descriptionLength: number;
|
|
99
|
+
};
|
|
100
|
+
/** 기준점 저장 시점에 본 가장 최근 리뷰 id. 리뷰 id 는 시간순으로 커진다. */
|
|
101
|
+
latestReviewId: string | null;
|
|
102
|
+
}
|
|
103
|
+
export interface FieldChange {
|
|
104
|
+
field: string;
|
|
105
|
+
before: unknown;
|
|
106
|
+
after: unknown;
|
|
107
|
+
}
|
|
108
|
+
export declare function watchDir(home?: string): string;
|
|
109
|
+
export declare function baselinePath(country: string, appId: number, home?: string): string;
|
|
110
|
+
export declare function diffSnapshots(before: WatchBaseline['snapshot'], after: WatchBaseline['snapshot']): FieldChange[];
|
|
111
|
+
export interface WatchResult {
|
|
112
|
+
app: {
|
|
113
|
+
appId: number;
|
|
114
|
+
name: string;
|
|
115
|
+
country: string;
|
|
116
|
+
url: string;
|
|
117
|
+
};
|
|
118
|
+
baselineSavedAt: string | null;
|
|
119
|
+
changes: FieldChange[];
|
|
120
|
+
/** 기준점 이후 새로 달린 리뷰 — 이미 본 리뷰에 닿을 때까지 페이지를 넘겨 모은다. */
|
|
121
|
+
newReviews: MarketReview[];
|
|
122
|
+
/** 새 리뷰를 끝까지 모으지 못했다 — 피드가 주는 최근 500개가 전부 새 리뷰였거나, 2페이지 이후를 읽다 실패했다. */
|
|
123
|
+
newReviewsMayBeTruncated: boolean;
|
|
124
|
+
/** 2페이지 이후를 읽다 난 오류 (없으면 null). 이때 market_save_baseline 은 저장하지 않고 실패한다. */
|
|
125
|
+
reviewPageError: string | null;
|
|
126
|
+
current: AppSnapshot;
|
|
127
|
+
saved: boolean;
|
|
128
|
+
baselineFile: string;
|
|
129
|
+
}
|
|
130
|
+
export declare function watchApp(opts: {
|
|
131
|
+
appId?: string;
|
|
132
|
+
bundleId?: string;
|
|
133
|
+
country: string;
|
|
134
|
+
save: boolean;
|
|
135
|
+
home?: string;
|
|
136
|
+
}): Promise<WatchResult>;
|
|
137
|
+
export {};
|