heyyumi 0.0.0-stage → 0.1.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/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,87 @@
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
+ Your AI finds and books real Korean restaurants, no Korean needed.
4
+
5
+ `heyyumi` is the command-line client for [HeyYumi](https://heyyumi.ai): verified data on 540,000+ restaurants, cafes, bakeries and bars across Korea, plus table requests that the venue answers within 5 minutes. It is built for AI agents (Claude Code, Codex, Cursor, k-skill …) that run shell commands and read JSON.
6
+
7
+ ```bash
8
+ npx -y heyyumi login # once: Google sign-in in the browser, then done
9
+ npx -y heyyumi search 냉면 --region 을지로 --page-size 5
10
+ npx -y heyyumi place 2069798395
11
+ npx -y heyyumi reserve 2069798395 --time "2026-10-25 19:00" --party 2 --phone 010-1234-5678 --name "Kim"
12
+ npx -y heyyumi wait sbx_r_... # confirmed / cancelled / expired
13
+ ```
14
+
15
+ Requires Node.js 18+. No other dependencies.
16
+
17
+ ## Sign in once
18
+
19
+ `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.
20
+
21
+ - Each sign-in gets its own HeyYumi key on the user's account, so usage is metered per user.
22
+ - 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.
23
+ - `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>.
24
+ - `--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 k-skill`).
25
+ - Already have a dashboard key? Set `HEYYUMI_API_KEY=hmp_...` and skip `login`.
26
+
27
+ ## Commands
28
+
29
+ | Command | What it does |
30
+ |---|---|
31
+ | `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: `--subtype korean_bbq`, `--open_at dinner`, `--parking`, `--reservation_channel yumi`, `--dietary vegan_options` … (see `heyyumi tools search_places`). Returns 10 venues unless `--page-size` is given. |
32
+ | `nearby --lat --lng [--radius] [--sort distance\|discovery]` | Venues around a point. |
33
+ | `place ID [--fields all]` | Full details for one venue. |
34
+ | `photos ID` | The owner's photo URLs. |
35
+ | `regions NAME` · `categories` · `stats` | Region lookup, category list, coverage numbers. |
36
+ | `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. |
37
+ | `wait RESERVATION_ID [--timeout 110]` | Wait for the venue's answer (they have 5 minutes). Re-run if `cli.settled` is false. |
38
+ | `reservation RESERVATION_ID` | Check a request once. |
39
+ | `live ID --kind item\|wait\|seats --topic TEXT` · `live-wait QUERY_ID` | Ask the venue right now (stock, wait time, seats). |
40
+ | `tools [TOOL]` · `call TOOL --json '{...}'` | Raw access to every HeyYumi MCP tool. |
41
+
42
+ Flags may use dashes or underscores (`--page-size` = `--page_size`). Bare flags mean `true`.
43
+
44
+ ## Output contract
45
+
46
+ - 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.
47
+ - Errors: `{"ok": false, "error": {"code", "message", "next"?, "details"?}}`. Server codes are passed through (`reservation_time_past`, `reservation_requests_closed`, …).
48
+ - Exit codes: `0` ok · `1` server/tool error · `2` bad usage · `3` not signed in (run `npx -y heyyumi login`).
49
+ - 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).
50
+ - When a follow-up command is needed, the output carries `cli.next`, e.g. `npx -y heyyumi wait <id>`.
51
+
52
+ ## Rules for agents
53
+
54
+ - 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.
55
+ - 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.
56
+ - `open_at` means the venue is open at that time, not that a table is free. Only a reservation answer says that.
57
+ - There are no star ratings (`rating` is always null). Do not invent one, and do not attribute review counts to any map platform.
58
+ - Link venue names to their `placeUrl`.
59
+
60
+ ## For k-skill
61
+
62
+ A k-skill skill can call this CLI the same way `bunjang-search` calls `bunjang-cli`:
63
+
64
+ ```bash
65
+ npx -y heyyumi login --client-name k-skill # returns at once if already signed in
66
+ npx -y heyyumi search "<dish or venue>" --region "<area>" --page-size 5
67
+ ```
68
+
69
+ Suggested profile: `action:booking` (reservations are irreversible and need the user's approval first). A ready-to-copy skill is in [`integrations/k-skill/heyyumi-restaurant`](integrations/k-skill/heyyumi-restaurant).
70
+
71
+ ## Environment
72
+
73
+ | Variable | Default |
74
+ |---|---|
75
+ | `HEYYUMI_API_KEY` | unset (use `login`) |
76
+ | `HEYYUMI_CONFIG_DIR` | `~/.config/heyyumi` |
77
+ | `HEYYUMI_CLIENT_NAME` | `HeyYumi CLI` |
78
+ | `HEYYUMI_MCP_URL` | `https://mcp.heyyumi.ai/mcp` |
79
+ | `HEYYUMI_ISSUER` | `https://heyyumi.ai` |
80
+
81
+ ---
82
+
83
+ ## 한국어 요약
84
+
85
+ AI 에이전트가 터미널 명령 하나로 한국 맛집을 찾고 예약 요청까지 보낼 수 있게 해 주는 CLI입니다. `npx -y heyyumi login`을 한 번 실행하면 브라우저에 구글 로그인 창이 뜨고, 승인하면 그 사용자 전용 키가 만들어져 바로 쓸 수 있습니다. 이후 명령은 모두 JSON으로 답합니다. 예약은 매장이 5분 안에 수락·거절하며, `wait`로 결과를 기다립니다.
86
+
87
+ 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,44 @@
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.0",
4
+ "description": "Find and book real Korean restaurants from your AI agent — no Korean needed. CLI for HeyYumi (search, details, table requests).",
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
+ "restaurant",
31
+ "reservation",
32
+ "k-food",
33
+ "ai-agent",
34
+ "mcp",
35
+ "cli",
36
+ "k-skill"
37
+ ],
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/hmp-dev/heyyumi-cli/issues"
43
+ }
44
+ }
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 };