heyyumi 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hide Me Please, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # heyyumi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/heyyumi)](https://www.npmjs.com/package/heyyumi)
4
+ [![node](https://img.shields.io/node/v/heyyumi)](https://www.npmjs.com/package/heyyumi)
5
+ [![license](https://img.shields.io/npm/l/heyyumi)](https://github.com/hmp-dev/heyyumi-cli/blob/main/LICENSE)
6
+
7
+ **Your AI finds and books real Korean restaurants, no Korean needed.**
8
+
9
+ Ask your agent for *"bibimbap near Myeongdong"*, *"a place BTS's Jin goes to for naengmyeon"* or *"somewhere open for dinner in Hongdae where nobody minds that I don't speak Korean"*. HeyYumi answers from verified data on **543,000+ restaurants, cafes and bars across Korea**, and sends the table request to the restaurant itself. Within 5 minutes you know whether the table is yours.
10
+
11
+ ```bash
12
+ npx -y heyyumi login # once: Google sign-in in the browser, a key is made for you
13
+ npx -y heyyumi search bibimbap --region Myeongdong
14
+ npx -y heyyumi reserve <placeId> --time "2026-10-25 19:00" --party 2 --phone +1-415-555-0100 --email you@example.com
15
+ ```
16
+
17
+ Works with any agent that runs shell commands and reads JSON: Claude Code, Codex, Gemini CLI, Cursor, or your own scripts. Node.js 18+, zero dependencies, free for personal use.
18
+
19
+ ## What your agent gets
20
+
21
+ **Real data, cross-checked.** 367,000+ restaurants, 138,000+ cafes and 36,000+ bars. More than 424,000 of them are confirmed by more than one independent source, and every record carries a confidence score and a last-seen date. Menus, prices, opening hours, last orders and break times are included wherever they are known. Nothing is invented: there are no star ratings, and a missing field means "unknown", never "no".
22
+
23
+ **Ask in your own language.** Dish names in English, romanized Korean, Japanese or Chinese are mapped to the Korean dish through an official government list of 800 Korean dishes and their foreign names. `bibimbap`, `ビビンバ` and `拌饭` all become 비빔밥. Places can be typed the same way: `Hongdae`, `Gangnam Station`, `Jeju Airport`.
24
+
25
+ **Book from the conversation.** `reserve` sends a real request to the restaurant, and `wait` returns `confirmed`, `cancelled` (with the venue's reason, if it gave one) or `expired`. The venue has 5 minutes to answer. Foreign phone numbers are welcome with an email address. Many venues can take a request, and the JSON says which ones (`yumiBooking.canRequest`).
26
+
27
+ **Ask the owner right now.** At Yumi partner venues, `live` asks the owner directly: is the dish still available, how long is the wait, are there seats for 10 right now? The question goes to the owner's phone, and they have 5 minutes to reply.
28
+
29
+ **Search the way travelers actually ask.** Over 60 filters, including:
30
+
31
+ | Ask for | Flag |
32
+ |---|---|
33
+ | Places where you don't need Korean (English menu or staff who speak your language) | `--foreigner-friendly` · `--english-menu` · `--foreign-languages ja` |
34
+ | Places a K-pop star or K-drama is known for (with the news source) | `--associated-with BTS` · `--associated-with 도깨비` |
35
+ | Shops on official long-running lists (30+ years) | `--legacy` |
36
+ | Vegan meals for a mixed group, vegetarian, gluten-free | `--dietary mixed_group_suitable` · `--dietary gluten_free` |
37
+ | Known to welcome Muslim guests (not a halal certification) | `--muslim-friendly` |
38
+ | Open at a time or a meal, last orders included | `--open-at "2026-10-25 19:00"` · `--open-at dinner` |
39
+ | Hanok, rooftop, ocean or river view, temple food, a city's signature food | `--hanok` · `--rooftop` · `--view ocean` · `--temple-food` · `--local-food Busan` |
40
+ | Alipay, WeChat Pay, Apple Pay, UnionPay | `--payment-methods alipay` |
41
+
42
+ Coverage today: Seoul, Gyeonggi, Busan, Jeju, Incheon, Daejeon, Sejong, Chungbuk and Chungnam, and growing.
43
+
44
+ ## What it looks like
45
+
46
+ ```bash
47
+ $ npx -y heyyumi search bibimbap --region Myeongdong --page-size 3 --fields core
48
+ ```
49
+
50
+ ```jsonc
51
+ {
52
+ "resolvedAs": "명동 상권",
53
+ "data": [
54
+ {
55
+ "id": "8392850",
56
+ "name": "본죽&비빔밥 명동점",
57
+ "address": { "road": "서울특별시 중구 명동8가길 6 2층" },
58
+ "confidence": 0.87,
59
+ "distanceM": 241,
60
+ "placeUrl": "https://heyyumi.ai/en/places/8392850",
61
+ "matchReason": "name",
62
+ "yumiBooking": { "canRequest": true, "requestHours": "11:00-21:00 KST" }
63
+ },
64
+ {
65
+ "name": "방이옥 종로점",
66
+ "matchReason": "representative_menu",
67
+ "matchedMenu": ["[점심특선] 한우육회 비빔밥 (1인)"]
68
+ // ...
69
+ }
70
+ ],
71
+ "meta": {
72
+ "total": 308,
73
+ "sort": "discovery",
74
+ "keywordTranslated": { "from": "bibimbap", "to": "비빔밥", "source": "official_dish_name" }
75
+ }
76
+ }
77
+ ```
78
+
79
+ Names and addresses come back in Korean, which is what taxi drivers and map apps expect. Your agent reads the JSON and answers in whatever language the user wrote in. `matchReason` tells it whether a place is a specialist or just also sells the dish.
80
+
81
+ ## Try these
82
+
83
+ ```bash
84
+ npx -y heyyumi search --region Seoul --associated-with BTS --page-size 5
85
+ npx -y heyyumi search 고기국수 --region "Jeju Airport" --open-at lunch
86
+ npx -y heyyumi search --region Gangnam --subtype korean_bbq --bbq-meat pork --private-room
87
+ npx -y heyyumi search --region Seongsu --dietary mixed_group_suitable --open-at dinner
88
+ npx -y heyyumi search --region Busan --local-food Busan --exclude 돼지국밥
89
+ npx -y heyyumi place <placeId> --fields all # menu, hours, attributes, reputation
90
+ ```
91
+
92
+ ## Sign in once
93
+
94
+ `heyyumi login` opens HeyYumi's Google sign-in and waits on a local callback (`http://127.0.0.1:<random port>/callback`). When the user approves, the CLI finishes by itself. Nobody has to press Enter, so an agent can run it directly.
95
+
96
+ - Each sign-in gets its own HeyYumi key on the user's account, so usage is metered per user.
97
+ - Credentials are saved to `~/.config/heyyumi/credentials.json` (mode 0600; `%APPDATA%\heyyumi` on Windows). Access tokens refresh on their own; refresh is locked across processes so parallel agent commands never sign the user out.
98
+ - `heyyumi status` shows whether you are signed in (never prints tokens). `heyyumi logout` removes local credentials. Keys can be revoked any time at <https://heyyumi.ai/dashboard>.
99
+ - `--no-browser` prints the URL instead of opening it. `--client-name NAME` labels the connection (it shows up as the source of reservation requests, e.g. `--client-name "My Agent"`).
100
+ - Already have a dashboard key? Set `HEYYUMI_API_KEY=hmp_...` and skip `login`.
101
+
102
+ ## Commands
103
+
104
+ | Command | What it does |
105
+ |---|---|
106
+ | `search [KEYWORD] --region NAME [filters]` | Shortlist venues. `--region` takes Korean or romanized names, stations and landmarks (`Hongdae`, `강남역`, `제주공항`). Every `search_places` filter works as a flag (see `heyyumi tools search_places`). Returns 10 venues unless `--page-size` is given. |
107
+ | `nearby --lat --lng [--radius] [--sort distance\|discovery]` | Venues around a point. |
108
+ | `place ID [--fields all]` | Full details for one venue. |
109
+ | `photos ID` | The owner's photo URLs. |
110
+ | `regions NAME` · `categories` · `stats` | Region lookup, category list, coverage numbers. |
111
+ | `reserve ID --time --party --phone [--name --email --note --lang]` | Send a table request. Times without an offset are Korea time. `--email` is required for non-Korean phone numbers. |
112
+ | `wait RESERVATION_ID [--timeout 110]` | Wait for the venue's answer (they have 5 minutes). Re-run if `cli.settled` is false. |
113
+ | `reservation RESERVATION_ID` | Check a request once. |
114
+ | `live ID --kind item\|wait\|seats --topic TEXT` · `live-wait QUERY_ID` | Ask the venue right now (stock, wait time, seats). |
115
+ | `tools [TOOL]` · `call TOOL --json '{...}'` | Raw access to every HeyYumi MCP tool. |
116
+
117
+ Flags may use dashes or underscores (`--page-size` = `--page_size`). Bare flags mean `true`.
118
+
119
+ ## Output contract
120
+
121
+ - stdout is always one JSON document: compact when piped, indented on a terminal or with `--pretty`. Progress and the sign-in URL go to stderr.
122
+ - Errors: `{"ok": false, "error": {"code", "message", "next"?, "details"?}}`. Server codes are passed through (`reservation_time_past`, `reservation_requests_closed`, …).
123
+ - Exit codes: `0` ok · `1` server/tool error · `2` bad usage · `3` not signed in (run `npx -y heyyumi login`).
124
+ - Unknown flags fail with `unknown_option` and a "did you mean" hint instead of being dropped, so a typo never turns into a silently wider search or a nameless booking. Search flags are checked against the live tool schema (cached for an hour), so new server filters work without a CLI update.
125
+ - When a follow-up command is needed, the output carries `cli.next`, e.g. `npx -y heyyumi wait <id>`.
126
+
127
+ ## Rules for agents
128
+
129
+ - Only send `reserve` for venues whose result shows `yumiBooking.canRequest: true`. Confirm time, party size, name and phone with the user before sending; it reaches a real venue. Venues with `requestHours` take requests only in those hours (Korea time).
130
+ - A request starts as `pending`. Say it is booked only after `wait` returns `status: "confirmed"`. `cancelled` means the venue declined (relay `declineReason` if present); `expired` means no answer in time.
131
+ - `open_at` means the venue is open at that time, not that a table is free. Only a reservation answer says that.
132
+ - There are no star ratings (`rating` is always null). Do not invent one, and do not attribute review counts to any map platform.
133
+ - `associated_with` results are reported visits with a news link, not endorsements. Say "reportedly visited by".
134
+ - Link venue names to their `placeUrl`.
135
+
136
+ ## Use it as an agent skill
137
+
138
+ Any agent or skill system that can run a shell command can wrap this CLI:
139
+
140
+ ```bash
141
+ npx -y heyyumi login --client-name "My Agent" # returns at once if already signed in
142
+ npx -y heyyumi search "<dish or venue>" --region "<area>" --page-size 5
143
+ ```
144
+
145
+ A ready-to-copy skill in the common `SKILL.md` format is in [`examples/agent-skill`](https://github.com/hmp-dev/heyyumi-cli/blob/main/examples/agent-skill/SKILL.md). For Claude Code, copy it to `~/.claude/skills/heyyumi-restaurant/SKILL.md`; for other agents, adapt the same instructions to their skill or tool format. Treat `reserve` and `live` as actions that need the user's approval first, because they reach a real venue.
146
+
147
+ Not in a terminal? The same tools are available as an MCP server for ChatGPT, Claude, Perplexity and Cursor: `https://mcp.heyyumi.ai/mcp` ([setup guide](https://heyyumi.ai/mcp)). Building a product? See the [REST API](https://heyyumi.ai/developers).
148
+
149
+ ## Environment
150
+
151
+ | Variable | Default |
152
+ |---|---|
153
+ | `HEYYUMI_API_KEY` | unset (use `login`) |
154
+ | `HEYYUMI_CONFIG_DIR` | `~/.config/heyyumi` |
155
+ | `HEYYUMI_CLIENT_NAME` | `HeyYumi CLI` |
156
+ | `HEYYUMI_MCP_URL` | `https://mcp.heyyumi.ai/mcp` |
157
+ | `HEYYUMI_ISSUER` | `https://heyyumi.ai` |
158
+
159
+ ---
160
+
161
+ **한국어** · AI 에이전트가 터미널 명령 하나로 한국의 검증된 맛집 54만여 곳을 찾고, 매장에 예약 요청까지 보낼 수 있는 CLI입니다. `npx -y heyyumi login`을 한 번 실행해 구글로 로그인하면 바로 쓸 수 있고, 모든 결과는 JSON으로 옵니다. 예약 요청을 보내면 5분 안에 수락 여부를 알 수 있어요.
162
+
163
+ **日本語** · 韓国語が分からなくても、AIエージェントが韓国の飲食店54万件以上から店を探し、予約リクエストまで送れるCLIです。「ビビンバ」のように日本語の料理名でもそのまま検索できます。予約できたかどうかは5分以内に分かります。
164
+
165
+ **中文** · 不会韩语也没关系。这个 CLI 让 AI 助手在韩国 54 万多家经过核实的餐厅、咖啡馆和酒吧中搜索,并直接发送订位请求。可以用中文菜名搜索(例如“拌饭”),5 分钟内就能知道是否订位成功。
166
+
167
+ **Español** · Tu IA encuentra y reserva restaurantes reales en Corea sin que sepas coreano: más de 543.000 locales verificados, búsqueda por nombre de plato en tu idioma y solicitudes de reserva con respuesta en 5 minutos.
168
+
169
+ MIT License · © 2026 Hide Me Please, Inc.
package/bin/heyyumi.js ADDED
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const { parseArgs } = require("../src/args");
5
+ const { commands, HELP, checkOwnFlags } = require("../src/commands");
6
+ const { CliError } = require("../src/errors");
7
+
8
+ function print(value, flags) {
9
+ const indent = flags.pretty || (process.stdout.isTTY && !flags.compact) ? 2 : 0;
10
+ process.stdout.write(`${JSON.stringify(value, null, indent)}\n`);
11
+ }
12
+
13
+ async function main() {
14
+ const [command, ...rest] = process.argv.slice(2);
15
+ const { positionals, flags } = parseArgs(rest);
16
+
17
+ if (!command || command === "help" || command === "--help" || command === "-h") {
18
+ process.stdout.write(HELP);
19
+ return 0;
20
+ }
21
+ if (command === "--version" || command === "-v" || command === "-V") {
22
+ process.stdout.write(`${require("../package.json").version}\n`);
23
+ return 0;
24
+ }
25
+ if (flags.help) {
26
+ process.stdout.write(HELP);
27
+ return 0;
28
+ }
29
+
30
+ const handler = Object.prototype.hasOwnProperty.call(commands, command) ? commands[command] : null;
31
+ if (!handler) {
32
+ print(new CliError("usage", `Unknown command "${command}"`, { exitCode: 2, next: "npx -y heyyumi help" }).toJSON(), flags);
33
+ return 2;
34
+ }
35
+
36
+ try {
37
+ checkOwnFlags(command, flags);
38
+ print(await handler({ positionals, flags }), flags);
39
+ return 0;
40
+ } catch (e) {
41
+ const err =
42
+ e instanceof CliError
43
+ ? e
44
+ : e instanceof TypeError && !e.cause
45
+ ? new CliError("usage", e.message, { exitCode: 2 })
46
+ : new CliError("unexpected", e?.message || String(e));
47
+ print(err.toJSON(), flags);
48
+ return err.exitCode;
49
+ }
50
+ }
51
+
52
+ main().then((code) => {
53
+ process.exitCode = code;
54
+ });
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "heyyumi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Your AI finds and books real Korean restaurants, no Korean needed. 543,000+ verified venues; search, details and table requests as JSON for any agent.",
5
+ "license": "MIT",
6
+ "bin": {
7
+ "heyyumi": "bin/heyyumi.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "scripts": {
19
+ "lint": "node --check bin/heyyumi.js && for f in src/*.js test/*.js; do node --check \"$f\" || exit 1; done",
20
+ "test": "node --test test/*.test.js"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/hmp-dev/heyyumi-cli.git"
25
+ },
26
+ "homepage": "https://heyyumi.ai",
27
+ "keywords": [
28
+ "heyyumi",
29
+ "korea",
30
+ "korean-food",
31
+ "k-food",
32
+ "seoul",
33
+ "restaurant",
34
+ "reservation",
35
+ "booking",
36
+ "travel",
37
+ "ai-agent",
38
+ "llm",
39
+ "mcp",
40
+ "cli",
41
+ "agent-skills",
42
+ "claude-code",
43
+ "codex",
44
+ "gemini-cli",
45
+ "cursor"
46
+ ],
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/hmp-dev/heyyumi-cli/issues"
52
+ }
53
+ }
package/src/args.js ADDED
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Minimal argv parser: positionals, `--key value`, `--key=value`, bare `--flag` (= true), `--` ends flags.
5
+ * A value starting with "--" is never consumed, so `--parking --region 성수` keeps parking=true.
6
+ */
7
+ function parseArgs(argv) {
8
+ const positionals = [];
9
+ const flags = {};
10
+ for (let i = 0; i < argv.length; i++) {
11
+ const arg = argv[i];
12
+ if (arg === "--") {
13
+ positionals.push(...argv.slice(i + 1));
14
+ break;
15
+ }
16
+ if (arg === "-h") {
17
+ flags.help = true;
18
+ continue;
19
+ }
20
+ if (arg.startsWith("--") && arg.length > 2) {
21
+ const eq = arg.indexOf("=");
22
+ if (eq !== -1) {
23
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
24
+ continue;
25
+ }
26
+ const key = arg.slice(2);
27
+ const next = argv[i + 1];
28
+ if (next !== undefined && !next.startsWith("--")) {
29
+ flags[key] = next;
30
+ i++;
31
+ } else {
32
+ flags[key] = true;
33
+ }
34
+ continue;
35
+ }
36
+ positionals.push(arg);
37
+ }
38
+ return { positionals, flags };
39
+ }
40
+
41
+ // Flags the CLI itself consumes; never forwarded to a tool.
42
+ const CLI_FLAGS = new Set([
43
+ "help",
44
+ "pretty",
45
+ "compact",
46
+ "json",
47
+ "timeout",
48
+ "no-browser",
49
+ "client-name",
50
+ "force",
51
+ ]);
52
+
53
+ // Tool arguments typed as numbers in the MCP schema.
54
+ const NUMERIC_KEYS = new Set([
55
+ "page",
56
+ "page_size",
57
+ "min_confidence",
58
+ "max_dish_price",
59
+ "radius_m",
60
+ "lat",
61
+ "lng",
62
+ "limit",
63
+ "guestCount",
64
+ ]);
65
+
66
+ function toSnake(key) {
67
+ return key.replace(/-/g, "_");
68
+ }
69
+
70
+ /**
71
+ * Turn CLI flags into tool arguments. Bare boolean flags become the string "true",
72
+ * which is what the search filters expect (`--parking` → parking: "true").
73
+ */
74
+ function flagsToToolArgs(flags, { rename = {}, skip = [] } = {}) {
75
+ const out = {};
76
+ for (const [rawKey, rawValue] of Object.entries(flags)) {
77
+ if (CLI_FLAGS.has(rawKey) || skip.includes(rawKey)) continue;
78
+ const key = rename[rawKey] || toSnake(rawKey);
79
+ let value = rawValue === true ? "true" : rawValue;
80
+ if (NUMERIC_KEYS.has(key)) {
81
+ const n = Number(value);
82
+ if (!Number.isFinite(n)) throw new TypeError(`--${rawKey} must be a number (got "${rawValue}")`);
83
+ value = n;
84
+ }
85
+ out[key] = value;
86
+ }
87
+ return out;
88
+ }
89
+
90
+ module.exports = { parseArgs, flagsToToolArgs, CLI_FLAGS, NUMERIC_KEYS };
@@ -0,0 +1,297 @@
1
+ "use strict";
2
+
3
+ const { flagsToToolArgs } = require("./args");
4
+ const { callTool, listTools } = require("./mcp");
5
+ const { login } = require("./oauth");
6
+ const { readCredentials, removeCredentials } = require("./credentials");
7
+ const { normalizeReservationTime } = require("./time");
8
+ const { credentialsPath, DEFAULT_CLIENT_NAME, MCP_URL, version } = require("./config");
9
+ const { CliError, usageError } = require("./errors");
10
+ const { validateArgs, suggest } = require("./schema");
11
+
12
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
13
+
14
+ // Each venue is ~1 KB of JSON; 10 keeps an agent's context small. --page-size overrides.
15
+ const DEFAULT_PAGE_SIZE = 10;
16
+
17
+ // Tool payloads come back as { success, data: {...} } from the REST API, or flat.
18
+ function pick(obj, key) {
19
+ if (!obj || typeof obj !== "object") return undefined;
20
+ if (obj[key] !== undefined) return obj[key];
21
+ if (obj.data && typeof obj.data === "object" && !Array.isArray(obj.data)) return obj.data[key];
22
+ return undefined;
23
+ }
24
+
25
+ function requirePositional(positionals, name, example) {
26
+ const v = positionals[0];
27
+ if (!v) throw usageError(`Missing ${name}. Example: ${example}`);
28
+ return v;
29
+ }
30
+
31
+ // Surface the server's own error code (e.g. reservation_time_past) so the agent can act on it.
32
+ function toolError(name, data) {
33
+ const code = typeof data?.code === "string" ? data.code : "tool_error";
34
+ const message = typeof data?.message === "string" ? data.message : typeof data === "string" ? data : `${name} failed`;
35
+ return new CliError(code, message, { details: data });
36
+ }
37
+
38
+ async function tool(name, args) {
39
+ const out = await callTool(name, await validateArgs(name, args));
40
+ if (!out.ok) throw toolError(name, out.data);
41
+ return out.data;
42
+ }
43
+
44
+ /** Re-call a ~25s long-poll tool until settled or the time budget runs out. */
45
+ async function pollUntilSettled(toolName, args, { timeoutSec, nextCommand }) {
46
+ const deadline = Date.now() + timeoutSec * 1000;
47
+ for (;;) {
48
+ const data = await tool(toolName, args);
49
+ if (pick(data, "settled") === true) return data;
50
+ if (Date.now() + 5000 > deadline) {
51
+ return { ...data, cli: { settled: false, next: nextCommand, note: "Still waiting for the venue. Run the next command to keep waiting." } };
52
+ }
53
+ await sleep(1000);
54
+ }
55
+ }
56
+
57
+ function timeoutFlag(flags, fallback) {
58
+ if (flags.timeout === undefined) return fallback;
59
+ const n = Number(flags.timeout);
60
+ if (!Number.isFinite(n) || n <= 0) throw usageError("--timeout must be seconds, e.g. --timeout 110");
61
+ return n;
62
+ }
63
+
64
+ // Commands that build tool arguments by hand. Anything else they get is a typo, and a dropped
65
+ // `--nme` would book under no name, so reject it. Commands not listed forward flags to the tool,
66
+ // where validateArgs checks them against the live schema.
67
+ const OWN_FLAGS = {
68
+ login: ["client-name", "no-browser", "timeout", "force"],
69
+ logout: [],
70
+ status: [],
71
+ photos: [],
72
+ categories: [],
73
+ stats: [],
74
+ reserve: ["time", "party", "phone", "name", "email", "note", "lang", "idempotency-key"],
75
+ reservation: [],
76
+ wait: ["timeout"],
77
+ live: ["kind", "topic", "question"],
78
+ "live-wait": ["timeout"],
79
+ tools: [],
80
+ version: [],
81
+ };
82
+ const OUTPUT_FLAGS = ["pretty", "compact", "help"];
83
+
84
+ function checkOwnFlags(command, flags) {
85
+ const allowed = OWN_FLAGS[command];
86
+ if (!allowed) return;
87
+ const unknown = Object.keys(flags).filter((k) => !allowed.includes(k) && !OUTPUT_FLAGS.includes(k));
88
+ if (!unknown.length) return;
89
+ const hints = unknown.map((k) => {
90
+ const s = suggest(k, allowed);
91
+ return s.length ? `--${k} (did you mean ${s.map((x) => `--${x}`).join(", ")}?)` : `--${k}`;
92
+ });
93
+ throw new CliError("unknown_option", `${command} does not take ${hints.join("; ")}`, { exitCode: 2, next: "npx -y heyyumi help" });
94
+ }
95
+
96
+ const commands = {
97
+ async login({ flags }) {
98
+ const existing = readCredentials();
99
+ if (existing?.refreshToken && !flags.force && !process.env.HEYYUMI_API_KEY) {
100
+ return { ok: true, alreadySignedIn: true, clientName: existing.clientName, note: "Already signed in. Use --force to sign in again." };
101
+ }
102
+ const clientName = typeof flags["client-name"] === "string" ? flags["client-name"] : process.env.HEYYUMI_CLIENT_NAME || DEFAULT_CLIENT_NAME;
103
+ const creds = await login({
104
+ clientName,
105
+ noBrowser: flags["no-browser"] === true,
106
+ timeoutMs: timeoutFlag(flags, 300) * 1000,
107
+ });
108
+ return { ok: true, signedIn: true, clientName: creds.clientName, credentials: credentialsPath() };
109
+ },
110
+
111
+ async logout() {
112
+ const removed = removeCredentials();
113
+ return {
114
+ ok: true,
115
+ signedOut: removed,
116
+ note: "Local sign-in removed. The connection's key can also be revoked at https://heyyumi.ai/dashboard.",
117
+ };
118
+ },
119
+
120
+ async status() {
121
+ if (process.env.HEYYUMI_API_KEY) return { ok: true, signedIn: true, mode: "api_key", mcpUrl: MCP_URL };
122
+ const c = readCredentials();
123
+ if (!c?.refreshToken) return { ok: true, signedIn: false, next: "npx -y heyyumi login" };
124
+ return {
125
+ ok: true,
126
+ signedIn: true,
127
+ mode: "oauth",
128
+ clientName: c.clientName,
129
+ accessTokenExpiresAt: new Date(c.expiresAt).toISOString(),
130
+ credentials: credentialsPath(),
131
+ mcpUrl: c.mcpUrl,
132
+ };
133
+ },
134
+
135
+ async search({ positionals, flags }) {
136
+ const args = flagsToToolArgs(flags, { rename: { region: "region_name" } });
137
+ if (positionals.length && args.keyword === undefined) args.keyword = positionals.join(" ");
138
+ args.page_size ??= DEFAULT_PAGE_SIZE;
139
+ return tool("search_places", args);
140
+ },
141
+
142
+ async nearby({ flags }) {
143
+ const args = flagsToToolArgs(flags, { rename: { radius: "radius_m" } });
144
+ if (args.lat === undefined || args.lng === undefined) throw usageError("nearby needs --lat and --lng. Example: heyyumi nearby --lat 37.5665 --lng 126.978 --radius 800");
145
+ args.page_size ??= DEFAULT_PAGE_SIZE;
146
+ return tool("nearby_places", args);
147
+ },
148
+
149
+ async place({ positionals, flags }) {
150
+ const id = requirePositional(positionals, "place id", "heyyumi place 21853004");
151
+ return tool("get_place", { id, ...flagsToToolArgs(flags) });
152
+ },
153
+
154
+ // Photo URLs via get_place; the photo tool returns base64 thumbnails, which do not belong in a terminal.
155
+ async photos({ positionals }) {
156
+ const id = requirePositional(positionals, "place id", "heyyumi photos 21853004");
157
+ return tool("get_place", { id, fields: "photos" });
158
+ },
159
+
160
+ async regions({ positionals, flags }) {
161
+ const args = flagsToToolArgs(flags);
162
+ if (positionals.length && !args.dong && !args.sigungu && !args.sido) args.dong = positionals.join(" ");
163
+ return tool("resolve_regions", args);
164
+ },
165
+
166
+ async categories() {
167
+ return tool("list_categories", {});
168
+ },
169
+
170
+ async stats() {
171
+ return tool("get_stats", {});
172
+ },
173
+
174
+ async reserve({ positionals, flags }) {
175
+ const placeId = requirePositional(positionals, "place id", 'heyyumi reserve 21853004 --time "2026-10-25 19:00" --party 2 --name "Kim" --phone 010-1234-5678');
176
+ let reservationTime;
177
+ try {
178
+ reservationTime = normalizeReservationTime(flags.time);
179
+ } catch (e) {
180
+ throw usageError(e.message);
181
+ }
182
+ const guestCount = Number(flags.party);
183
+ if (!Number.isInteger(guestCount) || guestCount < 1) throw usageError("--party must be a whole number of guests, e.g. --party 2");
184
+ if (typeof flags.phone !== "string") throw usageError("--phone is required (the guest's mobile, e.g. 010-1234-5678 or +1 415 555 0100)");
185
+
186
+ const args = { placeId, reservationTime, guestCount, guestPhone: flags.phone };
187
+ const optional = { name: "guestName", email: "guestEmail", note: "note", lang: "guestLanguage", "idempotency-key": "idempotencyKey" };
188
+ for (const [flag, key] of Object.entries(optional)) {
189
+ if (typeof flags[flag] === "string") args[key] = flags[flag];
190
+ }
191
+ const data = await tool("request_reservation", args);
192
+ const id = pick(data, "reservationId") ?? pick(data, "id");
193
+ if (id && data && typeof data === "object" && !Array.isArray(data) && pick(data, "settled") !== true) {
194
+ return { ...data, cli: { next: `npx -y heyyumi wait ${id}` } };
195
+ }
196
+ return data;
197
+ },
198
+
199
+ async reservation({ positionals }) {
200
+ const reservationId = requirePositional(positionals, "reservation id", "heyyumi reservation <reservationId>");
201
+ return tool("get_reservation", { reservationId });
202
+ },
203
+
204
+ async wait({ positionals, flags }) {
205
+ const reservationId = requirePositional(positionals, "reservation id", "heyyumi wait <reservationId>");
206
+ return pollUntilSettled("wait_for_reservation", { reservationId }, {
207
+ timeoutSec: timeoutFlag(flags, 110),
208
+ nextCommand: `npx -y heyyumi wait ${reservationId}`,
209
+ });
210
+ },
211
+
212
+ async live({ positionals, flags }) {
213
+ const placeId = requirePositional(positionals, "place id", 'heyyumi live 21853004 --kind wait --topic "웨이팅"');
214
+ if (!["item", "wait", "seats"].includes(flags.kind)) throw usageError("--kind must be item, wait, or seats");
215
+ if (typeof flags.topic !== "string") throw usageError('--topic is required, e.g. --topic "두바이 쫀득 쿠키"');
216
+ const args = { placeId, kind: flags.kind, topic: flags.topic };
217
+ if (typeof flags.question === "string") args.question = flags.question;
218
+ const data = await tool("request_live_status", args);
219
+ const queryId = pick(data, "queryId");
220
+ if (queryId && pick(data, "settled") !== true && !pick(data, "blocked")) {
221
+ return { ...data, cli: { next: `npx -y heyyumi live-wait ${queryId}` } };
222
+ }
223
+ return data;
224
+ },
225
+
226
+ async "live-wait"({ positionals, flags }) {
227
+ const queryId = requirePositional(positionals, "query id", "heyyumi live-wait <queryId>");
228
+ return pollUntilSettled("wait_for_live_status", { queryId }, {
229
+ timeoutSec: timeoutFlag(flags, 110),
230
+ nextCommand: `npx -y heyyumi live-wait ${queryId}`,
231
+ });
232
+ },
233
+
234
+ async tools({ positionals }) {
235
+ const all = await listTools();
236
+ if (positionals[0]) {
237
+ const t = all.find((x) => x.name === positionals[0]);
238
+ if (!t) throw usageError(`Unknown tool "${positionals[0]}". Run: heyyumi tools`);
239
+ return t;
240
+ }
241
+ return all.map((t) => ({ name: t.name, title: t.title || t.annotations?.title, required: t.inputSchema?.required || [] }));
242
+ },
243
+
244
+ async call({ positionals, flags }) {
245
+ const name = requirePositional(positionals, "tool name", "heyyumi call search_places --json '{\"region_name\":\"성수\"}'");
246
+ let args = {};
247
+ if (typeof flags.json === "string") {
248
+ try {
249
+ args = JSON.parse(flags.json);
250
+ } catch {
251
+ throw usageError("--json must be a JSON object");
252
+ }
253
+ }
254
+ Object.assign(args, flagsToToolArgs(flags));
255
+ return tool(name, args);
256
+ },
257
+
258
+ async version() {
259
+ return { ok: true, version };
260
+ },
261
+ };
262
+
263
+ const HELP = `heyyumi ${version} — Korean restaurant search & table requests for AI agents (HeyYumi)
264
+
265
+ Sign in (once per machine; opens Google sign-in, finishes on its own):
266
+ heyyumi login [--no-browser] [--client-name NAME] [--timeout 300] [--force]
267
+ heyyumi status | logout
268
+
269
+ Search & details:
270
+ heyyumi search [KEYWORD] --region 을지로 [--subtype korean_bbq] [--open_at "2026-10-25 19:00"] [--parking] ...
271
+ Any search_places filter works as a flag (see: heyyumi tools search_places). 10 results unless --page-size.
272
+ --region takes Korean or romanized names, stations and landmarks (Hongdae, 강남역, 제주공항).
273
+ heyyumi nearby --lat 37.5665 --lng 126.978 [--radius 800] [--sort discovery]
274
+ heyyumi place PLACE_ID [--fields all]
275
+ heyyumi photos PLACE_ID
276
+ heyyumi regions NAME | categories | stats
277
+
278
+ Table requests (only where a result shows yumiBooking.canRequest=true; ask the user before sending):
279
+ heyyumi reserve PLACE_ID --time "2026-10-25 19:00" --party 2 --phone 010-1234-5678 [--name NAME]
280
+ [--email EMAIL (required for non-Korean phones)] [--note TEXT] [--lang en]
281
+ heyyumi wait RESERVATION_ID [--timeout 110] waits until confirmed / cancelled / expired (venue has 5 min)
282
+ heyyumi reservation RESERVATION_ID one status check
283
+
284
+ Ask the venue right now (stock / wait time / seats):
285
+ heyyumi live PLACE_ID --kind item|wait|seats --topic "웨이팅" [--question TEXT]
286
+ heyyumi live-wait QUERY_ID [--timeout 110]
287
+
288
+ Raw MCP access:
289
+ heyyumi tools [TOOL] list tools / show one tool's full schema
290
+ heyyumi call TOOL [--json '{...}'] [--flag value]
291
+
292
+ Output is JSON on stdout (compact when piped, --pretty to indent); progress goes to stderr.
293
+ Exit codes: 0 ok · 1 server/tool error · 2 usage · 3 not signed in (run: npx -y heyyumi login)
294
+ HEYYUMI_API_KEY=hmp_... skips sign-in and uses a dashboard key instead.
295
+ `;
296
+
297
+ module.exports = { commands, HELP, pick, checkOwnFlags };
package/src/config.js ADDED
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ const os = require("node:os");
4
+ const path = require("node:path");
5
+ const { version } = require("../package.json");
6
+
7
+ const ISSUER = (process.env.HEYYUMI_ISSUER || "https://heyyumi.ai").replace(/\/+$/, "");
8
+ const MCP_URL = process.env.HEYYUMI_MCP_URL || "https://mcp.heyyumi.ai/mcp";
9
+ const DEFAULT_CLIENT_NAME = "HeyYumi CLI";
10
+ const USER_AGENT = `heyyumi-cli/${version} (+https://github.com/hmp-dev/heyyumi-cli)`;
11
+
12
+ // Protected-resource id advertised by mcp.heyyumi.ai (RFC 9728).
13
+ function mcpResource() {
14
+ return new URL(MCP_URL).origin;
15
+ }
16
+
17
+ function configDir() {
18
+ if (process.env.HEYYUMI_CONFIG_DIR) return process.env.HEYYUMI_CONFIG_DIR;
19
+ if (process.platform === "win32") {
20
+ return path.join(process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"), "heyyumi");
21
+ }
22
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "heyyumi");
23
+ }
24
+
25
+ function credentialsPath() {
26
+ return path.join(configDir(), "credentials.json");
27
+ }
28
+
29
+ module.exports = {
30
+ ISSUER,
31
+ MCP_URL,
32
+ DEFAULT_CLIENT_NAME,
33
+ USER_AGENT,
34
+ version,
35
+ mcpResource,
36
+ configDir,
37
+ credentialsPath,
38
+ };
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { credentialsPath } = require("./config");
6
+
7
+ function readCredentials(file = credentialsPath()) {
8
+ try {
9
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
10
+ return parsed && typeof parsed === "object" ? parsed : null;
11
+ } catch {
12
+ return null;
13
+ }
14
+ }
15
+
16
+ // Owner-only file; written to a temp file then renamed so a crash never leaves half a token.
17
+ function writeCredentials(creds, file = credentialsPath()) {
18
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
19
+ const tmp = `${file}.${process.pid}.tmp`;
20
+ fs.writeFileSync(tmp, `${JSON.stringify(creds, null, 2)}\n`, { mode: 0o600 });
21
+ fs.renameSync(tmp, file);
22
+ try {
23
+ fs.chmodSync(file, 0o600);
24
+ } catch {
25
+ // Windows ignores POSIX modes.
26
+ }
27
+ }
28
+
29
+ function removeCredentials(file = credentialsPath()) {
30
+ try {
31
+ fs.unlinkSync(file);
32
+ return true;
33
+ } catch (e) {
34
+ if (e.code === "ENOENT") return false;
35
+ throw e;
36
+ }
37
+ }
38
+
39
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
40
+
41
+ /**
42
+ * Cross-process lock around refresh. The server rotates refresh tokens (the old one is revoked),
43
+ * so two agent commands refreshing at once would sign the user out without this.
44
+ */
45
+ async function withCredentialsLock(fn, { file = credentialsPath(), timeoutMs = 15000, staleMs = 30000 } = {}) {
46
+ const lock = `${file}.lock`;
47
+ fs.mkdirSync(path.dirname(lock), { recursive: true, mode: 0o700 });
48
+ const deadline = Date.now() + timeoutMs;
49
+ let fd;
50
+ while (fd === undefined) {
51
+ try {
52
+ fd = fs.openSync(lock, "wx", 0o600);
53
+ } catch (e) {
54
+ if (e.code !== "EEXIST") throw e;
55
+ try {
56
+ if (Date.now() - fs.statSync(lock).mtimeMs > staleMs) fs.unlinkSync(lock);
57
+ } catch {
58
+ // Lock vanished between checks; retry.
59
+ }
60
+ if (Date.now() > deadline) throw new Error("Timed out waiting for the HeyYumi credentials lock");
61
+ await sleep(100);
62
+ }
63
+ }
64
+ try {
65
+ return await fn();
66
+ } finally {
67
+ fs.closeSync(fd);
68
+ try {
69
+ fs.unlinkSync(lock);
70
+ } catch {
71
+ // Already removed as stale by another process.
72
+ }
73
+ }
74
+ }
75
+
76
+ module.exports = { readCredentials, writeCredentials, removeCredentials, withCredentialsLock };
package/src/errors.js ADDED
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ // Exit codes: 1 = the server answered with an error, 2 = bad usage, 3 = not signed in.
4
+ class CliError extends Error {
5
+ constructor(code, message, { exitCode = 1, next, details } = {}) {
6
+ super(message);
7
+ this.code = code;
8
+ this.exitCode = exitCode;
9
+ this.next = next;
10
+ this.details = details;
11
+ }
12
+
13
+ toJSON() {
14
+ const error = { code: this.code, message: this.message };
15
+ if (this.next) error.next = this.next;
16
+ if (this.details !== undefined) error.details = this.details;
17
+ return { ok: false, error };
18
+ }
19
+ }
20
+
21
+ function usageError(message) {
22
+ return new CliError("usage", message, { exitCode: 2, next: "npx -y heyyumi help" });
23
+ }
24
+
25
+ function loginRequired(message = "Not signed in to HeyYumi.") {
26
+ return new CliError("login_required", message, { exitCode: 3, next: "npx -y heyyumi login" });
27
+ }
28
+
29
+ module.exports = { CliError, usageError, loginRequired };
package/src/mcp.js ADDED
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+
3
+ const { MCP_URL, USER_AGENT } = require("./config");
4
+ const { readCredentials } = require("./credentials");
5
+ const { getAccessToken } = require("./oauth");
6
+ const { CliError, loginRequired } = require("./errors");
7
+
8
+ let rpcId = 0;
9
+
10
+ /** Streamable HTTP answers either plain JSON or one SSE event per JSON-RPC message. */
11
+ function parseRpcBody(text, contentType, id) {
12
+ if (!/text\/event-stream/i.test(contentType || "")) return JSON.parse(text);
13
+ for (const block of text.split(/\r?\n\r?\n/)) {
14
+ const data = block
15
+ .split(/\r?\n/)
16
+ .filter((l) => l.startsWith("data:"))
17
+ .map((l) => l.slice(5).replace(/^ /, ""))
18
+ .join("\n");
19
+ if (!data) continue;
20
+ const msg = JSON.parse(data);
21
+ if (msg.id === id || msg.id === undefined) return msg;
22
+ }
23
+ throw new Error("Empty response from the HeyYumi MCP server");
24
+ }
25
+
26
+ function mcpUrl() {
27
+ return process.env.HEYYUMI_MCP_URL || readCredentials()?.mcpUrl || MCP_URL;
28
+ }
29
+
30
+ async function rpcOnce(method, params, token) {
31
+ const id = ++rpcId;
32
+ const res = await fetch(mcpUrl(), {
33
+ method: "POST",
34
+ headers: {
35
+ Authorization: `Bearer ${token}`,
36
+ "Content-Type": "application/json",
37
+ Accept: "application/json, text/event-stream",
38
+ "User-Agent": USER_AGENT,
39
+ },
40
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
41
+ // wait_for_* tools hold the request ~25s on the server.
42
+ signal: AbortSignal.timeout(90000),
43
+ });
44
+ if (res.status === 401) return { unauthorized: true };
45
+ const text = await res.text();
46
+ if (!res.ok) throw new CliError("http_error", `HeyYumi MCP server returned HTTP ${res.status}`, { details: text.slice(0, 500) });
47
+ const msg = parseRpcBody(text, res.headers.get("content-type"), id);
48
+ if (msg.error) throw new CliError("rpc_error", msg.error.message || "MCP error", { details: msg.error });
49
+ return { result: msg.result };
50
+ }
51
+
52
+ async function rpc(method, params) {
53
+ let auth = await getAccessToken();
54
+ let out = await rpcOnce(method, params, auth.token);
55
+ if (out.unauthorized && auth.mode === "oauth") {
56
+ auth = await getAccessToken({ staleToken: auth.token });
57
+ out = await rpcOnce(method, params, auth.token);
58
+ }
59
+ if (out.unauthorized) {
60
+ if (auth.mode === "api_key") {
61
+ throw new CliError("invalid_api_key", "HEYYUMI_API_KEY was rejected. Check the key or unset it to use `heyyumi login`.", {
62
+ exitCode: 3,
63
+ });
64
+ }
65
+ throw loginRequired("Your HeyYumi sign-in was rejected. Sign in again.");
66
+ }
67
+ return out.result;
68
+ }
69
+
70
+ /**
71
+ * Unwrap a tool result: JSON text blocks are parsed, image blocks are summarised (base64 would
72
+ * flood the agent's context). `isError` results become { ok:false } so callers can exit non-zero.
73
+ */
74
+ function unwrapToolResult(result) {
75
+ const parts = (result?.content || []).map((c) => {
76
+ if (c.type === "text") {
77
+ try {
78
+ return JSON.parse(c.text);
79
+ } catch {
80
+ return c.text;
81
+ }
82
+ }
83
+ if (c.type === "image") return { type: "image", mimeType: c.mimeType, omitted: "base64 image omitted in CLI output" };
84
+ return c;
85
+ });
86
+ const data = parts.length === 1 ? parts[0] : parts;
87
+ if (result?.isError) return { ok: false, data };
88
+ return { ok: true, data };
89
+ }
90
+
91
+ async function callTool(name, args) {
92
+ return unwrapToolResult(await rpc("tools/call", { name, arguments: args }));
93
+ }
94
+
95
+ async function listTools() {
96
+ const result = await rpc("tools/list", {});
97
+ return result.tools || [];
98
+ }
99
+
100
+ module.exports = { callTool, listTools, rpc, parseRpcBody, unwrapToolResult };
package/src/oauth.js ADDED
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const http = require("node:http");
5
+ const { spawn } = require("node:child_process");
6
+ const { ISSUER, MCP_URL, DEFAULT_CLIENT_NAME, USER_AGENT, mcpResource } = require("./config");
7
+ const { readCredentials, writeCredentials, withCredentialsLock } = require("./credentials");
8
+ const { CliError, loginRequired } = require("./errors");
9
+
10
+ const REFRESH_SKEW_MS = 60 * 1000;
11
+
12
+ const base64url = (buf) => Buffer.from(buf).toString("base64url");
13
+
14
+ function createPkce() {
15
+ const verifier = base64url(crypto.randomBytes(32));
16
+ const challenge = base64url(crypto.createHash("sha256").update(verifier).digest());
17
+ return { verifier, challenge };
18
+ }
19
+
20
+ async function postJson(url, body) {
21
+ const res = await fetch(url, {
22
+ method: "POST",
23
+ headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
24
+ body: JSON.stringify(body),
25
+ signal: AbortSignal.timeout(20000),
26
+ });
27
+ const json = await res.json().catch(() => ({}));
28
+ return { res, json };
29
+ }
30
+
31
+ async function postForm(url, params) {
32
+ const res = await fetch(url, {
33
+ method: "POST",
34
+ headers: { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": USER_AGENT },
35
+ body: new URLSearchParams(params).toString(),
36
+ signal: AbortSignal.timeout(20000),
37
+ });
38
+ const json = await res.json().catch(() => ({}));
39
+ return { res, json };
40
+ }
41
+
42
+ async function registerClient({ redirectUri, clientName, issuer = ISSUER }) {
43
+ const { res, json } = await postJson(`${issuer}/oauth/register`, {
44
+ client_name: clientName,
45
+ redirect_uris: [redirectUri],
46
+ grant_types: ["authorization_code", "refresh_token"],
47
+ response_types: ["code"],
48
+ token_endpoint_auth_method: "none",
49
+ });
50
+ if (!res.ok || !json.client_id) {
51
+ throw new CliError("oauth_register_failed", json.error_description || `Client registration failed (HTTP ${res.status})`);
52
+ }
53
+ return json.client_id;
54
+ }
55
+
56
+ function credsFromTokenResponse(json, { clientId, clientName, issuer = ISSUER, mcpUrl = MCP_URL }) {
57
+ return {
58
+ version: 1,
59
+ issuer,
60
+ mcpUrl,
61
+ clientId,
62
+ clientName,
63
+ accessToken: json.access_token,
64
+ refreshToken: json.refresh_token,
65
+ expiresAt: Date.now() + Number(json.expires_in || 3600) * 1000,
66
+ scope: json.scope || "read",
67
+ updatedAt: new Date().toISOString(),
68
+ };
69
+ }
70
+
71
+ function openBrowser(url) {
72
+ const [cmd, args] =
73
+ process.platform === "darwin"
74
+ ? ["open", [url]]
75
+ : process.platform === "win32"
76
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
77
+ : ["xdg-open", [url]];
78
+ try {
79
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
80
+ child.on("error", () => {});
81
+ child.unref();
82
+ } catch {
83
+ // The URL is printed too, so the user can open it by hand.
84
+ }
85
+ }
86
+
87
+ const PAGE = (title, body) =>
88
+ `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title></head>` +
89
+ `<body style="font-family:system-ui,sans-serif;max-width:420px;margin:15vh auto;padding:0 24px;line-height:1.6">` +
90
+ `<h1 style="font-size:22px">${title}</h1><p>${body}</p></body></html>`;
91
+
92
+ /**
93
+ * Loopback OAuth (RFC 8252) + PKCE against heyyumi.ai. The portal issues a key dedicated to this
94
+ * connection, so each user is metered on their own account. Finishes on its own when the browser
95
+ * returns, so an agent can run it without anyone pressing Enter.
96
+ */
97
+ async function login({
98
+ clientName = DEFAULT_CLIENT_NAME,
99
+ noBrowser = false,
100
+ timeoutMs = 5 * 60 * 1000,
101
+ log = (m) => process.stderr.write(`${m}\n`),
102
+ issuer = ISSUER,
103
+ browser = openBrowser,
104
+ } = {}) {
105
+ const state = base64url(crypto.randomBytes(16));
106
+ const { verifier, challenge } = createPkce();
107
+
108
+ let settle;
109
+ const callback = new Promise((resolve, reject) => {
110
+ settle = { resolve, reject };
111
+ });
112
+ callback.catch(() => {});
113
+
114
+ const server = http.createServer((req, res) => {
115
+ const url = new URL(req.url, "http://127.0.0.1");
116
+ if (url.pathname !== "/callback") {
117
+ res.writeHead(404).end();
118
+ return;
119
+ }
120
+ const send = (status, title, body) => {
121
+ res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" }).end(PAGE(title, body));
122
+ };
123
+ if (url.searchParams.get("state") !== state) {
124
+ send(400, "Sign-in failed", "This sign-in link is stale. Run <code>npx -y heyyumi login</code> again.");
125
+ return;
126
+ }
127
+ const error = url.searchParams.get("error");
128
+ if (error) {
129
+ send(400, "Sign-in cancelled", "You can close this tab. 이 탭을 닫으셔도 돼요.");
130
+ settle.reject(new CliError("oauth_denied", url.searchParams.get("error_description") || error, { exitCode: 3 }));
131
+ return;
132
+ }
133
+ const code = url.searchParams.get("code");
134
+ if (!code) {
135
+ send(400, "Sign-in failed", "No authorization code was returned.");
136
+ return;
137
+ }
138
+ send(200, "HeyYumi is connected", "You can close this tab and go back to your AI. 이 탭을 닫고 AI로 돌아가세요.");
139
+ settle.resolve(code);
140
+ });
141
+
142
+ await new Promise((resolve, reject) => {
143
+ server.once("error", reject);
144
+ server.listen(0, "127.0.0.1", resolve);
145
+ });
146
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
147
+
148
+ const timer = setTimeout(() => {
149
+ settle.reject(
150
+ new CliError("login_timeout", `No sign-in within ${Math.round(timeoutMs / 1000)}s.`, {
151
+ exitCode: 3,
152
+ next: "npx -y heyyumi login",
153
+ }),
154
+ );
155
+ }, timeoutMs);
156
+
157
+ try {
158
+ const clientId = await registerClient({ redirectUri, clientName, issuer });
159
+ const authUrl = new URL(`${issuer}/oauth/authorize`);
160
+ authUrl.search = new URLSearchParams({
161
+ response_type: "code",
162
+ client_id: clientId,
163
+ redirect_uri: redirectUri,
164
+ code_challenge: challenge,
165
+ code_challenge_method: "S256",
166
+ scope: "read",
167
+ state,
168
+ resource: mcpResource(),
169
+ }).toString();
170
+
171
+ log("Sign in to HeyYumi with Google in your browser. If it did not open, visit:");
172
+ log(authUrl.toString());
173
+ if (!noBrowser) browser(authUrl.toString());
174
+
175
+ const code = await callback;
176
+ const { res, json } = await postForm(`${issuer}/oauth/token`, {
177
+ grant_type: "authorization_code",
178
+ code,
179
+ redirect_uri: redirectUri,
180
+ client_id: clientId,
181
+ code_verifier: verifier,
182
+ });
183
+ if (!res.ok || !json.access_token) {
184
+ throw new CliError("oauth_token_failed", json.error_description || `Token exchange failed (HTTP ${res.status})`, {
185
+ exitCode: 3,
186
+ });
187
+ }
188
+ const creds = credsFromTokenResponse(json, { clientId, clientName, issuer });
189
+ writeCredentials(creds);
190
+ return creds;
191
+ } finally {
192
+ clearTimeout(timer);
193
+ server.close();
194
+ // Browsers keep the callback connection alive, which would hold the process open.
195
+ server.closeAllConnections?.();
196
+ }
197
+ }
198
+
199
+ async function refreshCredentials(creds) {
200
+ const { res, json } = await postForm(`${creds.issuer || ISSUER}/oauth/token`, {
201
+ grant_type: "refresh_token",
202
+ refresh_token: creds.refreshToken,
203
+ client_id: creds.clientId,
204
+ });
205
+ if (res.status === 400 || res.status === 401) return null;
206
+ if (!res.ok || !json.access_token) {
207
+ throw new CliError("oauth_refresh_failed", json.error_description || `Token refresh failed (HTTP ${res.status})`);
208
+ }
209
+ return credsFromTokenResponse(json, {
210
+ clientId: creds.clientId,
211
+ clientName: creds.clientName,
212
+ issuer: creds.issuer,
213
+ mcpUrl: creds.mcpUrl,
214
+ });
215
+ }
216
+
217
+ /**
218
+ * Bearer token for mcp.heyyumi.ai. HEYYUMI_API_KEY (an hmp_ key from the dashboard) wins when set.
219
+ * `staleToken` = the token the server just rejected; refresh unless another process already did.
220
+ */
221
+ async function getAccessToken({ staleToken } = {}) {
222
+ const envKey = process.env.HEYYUMI_API_KEY;
223
+ if (envKey) return { token: envKey.trim(), mode: "api_key" };
224
+
225
+ const current = readCredentials();
226
+ if (!current?.refreshToken) throw loginRequired();
227
+ const fresh = (c) => c.accessToken && c.expiresAt - REFRESH_SKEW_MS > Date.now();
228
+ if (!staleToken && fresh(current)) return { token: current.accessToken, mode: "oauth" };
229
+
230
+ return withCredentialsLock(async () => {
231
+ const latest = readCredentials();
232
+ if (!latest?.refreshToken) throw loginRequired();
233
+ if (latest.accessToken !== staleToken && fresh(latest)) return { token: latest.accessToken, mode: "oauth" };
234
+ const next = await refreshCredentials(latest);
235
+ if (!next) throw loginRequired("Your HeyYumi sign-in expired or was revoked. Sign in again.");
236
+ writeCredentials(next);
237
+ return { token: next.accessToken, mode: "oauth" };
238
+ });
239
+ }
240
+
241
+ module.exports = { login, getAccessToken, refreshCredentials, registerClient, createPkce, openBrowser };
package/src/schema.js ADDED
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { configDir, MCP_URL } = require("./config");
6
+ const { listTools } = require("./mcp");
7
+ const { CliError } = require("./errors");
8
+
9
+ const TTL_MS = 60 * 60 * 1000;
10
+
11
+ function cachePath() {
12
+ return path.join(configDir(), "tools-cache.json");
13
+ }
14
+
15
+ /** Tool schemas, cached for an hour. null when the server can't be asked (validation is then skipped). */
16
+ async function loadSchemas() {
17
+ try {
18
+ const cached = JSON.parse(fs.readFileSync(cachePath(), "utf8"));
19
+ if (cached.mcpUrl === MCP_URL && Date.now() - cached.savedAt < TTL_MS && cached.tools) return cached.tools;
20
+ } catch {
21
+ // No cache yet.
22
+ }
23
+ let tools;
24
+ try {
25
+ tools = await listTools();
26
+ } catch (e) {
27
+ if (e instanceof CliError && e.exitCode === 3) throw e;
28
+ return null;
29
+ }
30
+ const byName = {};
31
+ for (const t of tools) byName[t.name] = t.inputSchema || {};
32
+ try {
33
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
34
+ fs.writeFileSync(cachePath(), JSON.stringify({ mcpUrl: MCP_URL, savedAt: Date.now(), tools: byName }));
35
+ } catch {
36
+ // Read-only home: validate this run without caching.
37
+ }
38
+ return byName;
39
+ }
40
+
41
+ function editDistance(a, b) {
42
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
43
+ for (let j = 1; j <= b.length; j++) dp[0][j] = j;
44
+ for (let i = 1; i <= a.length; i++) {
45
+ for (let j = 1; j <= b.length; j++) {
46
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
47
+ }
48
+ }
49
+ return dp[a.length][b.length];
50
+ }
51
+
52
+ function suggest(key, known) {
53
+ return known
54
+ .map((k) => ({ k, d: k.startsWith(key) || key.startsWith(k) ? 0 : editDistance(key, k) }))
55
+ .filter((x) => x.d <= Math.max(2, Math.floor(key.length / 3)))
56
+ .sort((a, b) => a.d - b.d)
57
+ .slice(0, 3)
58
+ .map((x) => x.k);
59
+ }
60
+
61
+ /**
62
+ * The server drops arguments it doesn't know without saying so, which turns a typo into a silently
63
+ * wrong search. Reject unknown keys here and coerce booleans the schema types as boolean.
64
+ */
65
+ function checkArgs(toolName, args, schema) {
66
+ const props = schema?.properties;
67
+ if (!props) return args;
68
+ const known = Object.keys(props);
69
+ const unknown = Object.keys(args).filter((k) => !(k in props));
70
+ if (unknown.length) {
71
+ const hints = unknown.map((k) => {
72
+ const s = suggest(k, known);
73
+ return s.length ? `--${k} (did you mean ${s.map((x) => `--${x}`).join(", ")}?)` : `--${k}`;
74
+ });
75
+ throw new CliError("unknown_option", `${toolName} does not take ${hints.join("; ")}`, {
76
+ exitCode: 2,
77
+ next: `npx -y heyyumi tools ${toolName}`,
78
+ });
79
+ }
80
+ const out = { ...args };
81
+ for (const [k, v] of Object.entries(out)) {
82
+ if (props[k]?.type === "boolean" && typeof v === "string") out[k] = !["false", "0", "no", "off"].includes(v.toLowerCase());
83
+ }
84
+ return out;
85
+ }
86
+
87
+ async function validateArgs(toolName, args) {
88
+ const schemas = await loadSchemas();
89
+ if (!schemas || !schemas[toolName]) return args;
90
+ return checkArgs(toolName, args, schemas[toolName]);
91
+ }
92
+
93
+ module.exports = { validateArgs, checkArgs, suggest };
package/src/time.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+
3
+ const HAS_OFFSET = /(Z|[+-]\d{2}:?\d{2})$/i;
4
+ const LOCAL = /^(\d{4}-\d{2}-\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/;
5
+
6
+ /**
7
+ * Reservation times are Korea time. Accept "2026-10-25 19:00" / "2026-10-25T19:00" (read as KST)
8
+ * or a full ISO string with an offset. A bare "19:00" is rejected: guessing the date books the wrong day.
9
+ */
10
+ function normalizeReservationTime(input) {
11
+ const raw = String(input ?? "").trim();
12
+ if (!raw) throw new TypeError("--time is required, e.g. --time \"2026-10-25 19:00\" (Korea time)");
13
+
14
+ if (HAS_OFFSET.test(raw)) {
15
+ if (Number.isNaN(Date.parse(raw))) throw new TypeError(`--time "${raw}" is not a valid ISO 8601 time`);
16
+ return raw;
17
+ }
18
+
19
+ const m = LOCAL.exec(raw);
20
+ if (!m) {
21
+ throw new TypeError(
22
+ `--time "${raw}" needs a date and time, e.g. "2026-10-25 19:00" (Korea time) or "2026-10-25T19:00:00+09:00"`,
23
+ );
24
+ }
25
+ const [, date, hh, mm, ss = "00"] = m;
26
+ const iso = `${date}T${hh.padStart(2, "0")}:${mm}:${ss}+09:00`;
27
+ if (Number.isNaN(Date.parse(iso))) throw new TypeError(`--time "${raw}" is not a valid date/time`);
28
+ return iso;
29
+ }
30
+
31
+ module.exports = { normalizeReservationTime };