@kkcode-app/agent 1.1.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @kkcode-app/agent
2
2
 
3
- > 高级用户兼容入口。普通用户应安装 KKCode Desktop,由 Desktop 托管 OpenCode、自启、升级、隧道和通知;CLI 继续服务 Linux/headless、已有自动化和调试场景,不再作为新手 onboarding 主路径。
3
+ > 高级用户兼容入口。普通用户应安装 KKCode Desktop,由 Desktop 托管 OpenCode、自启、升级、隧道和通知;CLI 继续服务 Linux/headless、已有自动化和调试场景。
4
4
 
5
- KKCode 的桌面配套工具:它可将电脑上的 OpenCode HTTP server 通过中继连接到手机,并作为 OpenCode 插件向 iPhone 发送提醒。
5
+ KKCode 的桌面配套工具(v2.0.0):通过 Tunnel v4(二进制帧 + AES-256-GCM 端到端加密)将本地 OpenCode 2 服务安全连接到手机,并作为 OpenCode 2 插件向 Notify 2.0 上报推送提醒(支持不开隧道独立推送)。
6
6
 
7
7
  ## Install
8
8
 
@@ -13,7 +13,7 @@ npm install
13
13
 
14
14
  ## Usage
15
15
 
16
- ### Default: spawn opencode serve for you
16
+ ### Default: spawn password-protected opencode serve + Tunnel v4
17
17
 
18
18
  ```bash
19
19
  npx -y @kkcode-app/agent@latest
@@ -21,120 +21,61 @@ npx -y @kkcode-app/agent@latest
21
21
 
22
22
  This will:
23
23
 
24
- 1. Spawn `opencode serve` on `127.0.0.1:<random-port>`.
25
- 2. Open a WebSocket tunnel to the relay.
26
- 3. Print a QR code. In KKCode, open **Servers** →
27
- **Scan tunnel QR code**, then scan the terminal QR code.
24
+ 1. Create or load the unified Host secret in `~/.config/kkcode/host.json` (`0o600`).
25
+ 2. Register `@kkcode-app/agent` in OpenCode 2 `plugins` config (`~/.config/opencode/opencode.json(c)`).
26
+ 3. Spawn `opencode serve` on `127.0.0.1:<random-port>` with a random 24-byte hex `OPENCODE_SERVER_PASSWORD`.
27
+ 4. Open an encrypted Tunnel v4 WebSocket to `wss://relay.kkcode.app/v4/host`.
28
+ 5. Print a permanent QR v8 code. Scan it in KKCode to pair both remote access and push notifications.
28
29
 
29
- Keep the terminal open while using the connection. The CLI reconnects after a
30
- temporary network loss. Use KKCode's manual server-address entry only for a
31
- normal LAN/Tailscale/OpenCode URL: a tunnel QR code contains a temporary access
32
- token and must be scanned.
33
-
34
- ### Background service (macOS & Linux)
35
-
36
- First run the tunnel in the foreground and scan its QR code in KKCode. Then
37
- install the tunnel as a **background service** so it auto-starts on login and
38
- auto-restarts on crash. On macOS it uses launchd (LaunchAgent), on Linux it
39
- uses a systemd user service. The CLI refuses a first-time `--install`, because
40
- the QR code would only be written to the service log instead of your terminal.
30
+ ### Push-only setup (without running a tunnel)
41
31
 
42
32
  ```bash
43
- npx -y @kkcode-app/agent@latest --install
33
+ npx -y @kkcode-app/agent@latest push-setup
34
+ # alias:
35
+ npx -y @kkcode-app/agent@latest link
44
36
  ```
45
37
 
46
- The first time you run `--install` it captures the current `PATH` and the
47
- absolute paths of `node` and `opencode`, so the background service can find
48
- them even though the service manager does not source your shell profile.
38
+ Creates `~/.config/kkcode/host.json`, registers the OpenCode 2 notification plugin, and prints a QR v8 code for mobile push pairing without starting a tunnel.
39
+
40
+ ### Background service (macOS & Linux)
49
41
 
50
- Other commands:
42
+ First run once in the foreground and scan its QR code in KKCode, then install as a background service:
51
43
 
52
44
  ```bash
53
- npx -y @kkcode-app/agent@latest --status # check if installed/loaded/running
54
- npx -y @kkcode-app/agent@latest --restart # restart the background service
55
- npx -y @kkcode-app/agent@latest --uninstall # stop and remove the service
56
- npx -y @kkcode-app/agent@latest --version # print the exact package version npx resolved
45
+ npx -y @kkcode-app/agent@latest --install
46
+ npx -y @kkcode-app/agent@latest --status
47
+ npx -y @kkcode-app/agent@latest --restart
48
+ npx -y @kkcode-app/agent@latest --stop
49
+ npx -y @kkcode-app/agent@latest --update
50
+ npx -y @kkcode-app/agent@latest --uninstall
57
51
  ```
58
52
 
59
- The QR payload includes a `cli` field with the package version, so you can tell
60
- which CLI build produced a pairing code. Note the legacy package name
61
- `@kkcode-app/opencode` still resolves to an old release that prints QR v4;
62
- always use `@kkcode-app/agent@latest`.
63
-
64
- Logs are written to `~/.config/kkcode/tunnel/tunnel.log`. The tunnel `code` and
65
- shared `secret` are persisted across restarts, so your phone stays connected without re-scanning
66
- as long as the relay session hasn't expired. If a legacy
67
- `~/.config/opencode-tunnel/config.json` exists, it is migrated automatically
68
- on first run.
69
-
70
- ### Windows
71
-
72
- The foreground flow (`npx -y @kkcode-app/agent@latest`) works on Windows out of
73
- the box — the CLI uses `where` and `shell:true` to resolve `opencode.cmd`
74
- installed via `npm install -g opencode-ai`. If `opencode -v` works in your
75
- shell but the CLI still can't find it, run `npm config get prefix` and make
76
- sure that directory is on your `PATH`, or pass `--command` with the absolute
77
- path to `opencode.cmd`.
78
-
79
- Background service flags (`--install` / `--uninstall` / `--stop` / `--restart`
80
- / `--status`) are **not** supported on Windows yet. Run the CLI inside WSL for
81
- the full background-service experience, or keep the foreground process open
82
- on Windows.
83
-
84
53
  ### Attach to an already running opencode serve
85
54
 
86
55
  ```bash
87
56
  opencode serve --port 4096 &
88
- npx -y @kkcode-app/agent@latest --attach --port 4096
57
+ npx -y @kkcode-app/agent@latest --attach --port 4096 --password <pwd>
89
58
  ```
90
59
 
91
60
  ### Flags
92
61
 
93
- | Flag | Description | Default |
94
- | ------------------ | --------------------------------------------------------------------- | ------------------------------------------------- |
95
- | `--backend <name>` | Local backend: `opencode` | `opencode` |
96
- | `--relay <url>` | Relay base URL (`ws://` or `wss://`) | `$OPENCODE_RELAY_URL` or `wss://relay.kkcode.app` |
97
- | `--port <n>` | Port for `opencode serve` (random free port if omitted) | random |
98
- | `--hostname <h>` | Local hostname for `opencode serve` | `127.0.0.1` |
99
- | `--attach` | Don't spawn — reuse an existing `opencode serve` | off |
100
- | `--command <bin>` | Binary to spawn | `$OPENCODE_CMD`/`opencode` |
101
- | `--reset-tunnel` | Forget the saved secret and create a new tunnel | off |
102
- | `--install` | Install as macOS LaunchAgent (background, auto-start on login) | off |
103
- | `--uninstall` | Remove the LaunchAgent and stop the background service | off |
104
- | `--restart` | Restart the background service (`kickstart -k` / `systemctl restart`) | off |
105
- | `--status` | Show whether the background service is installed/loaded/running | off |
106
- | `--update` | Upgrade the background service to the latest npm version | off |
107
- | `-v`, `--version` | Print the CLI package version and exit | off |
108
-
109
- ## iPhone notifications
110
-
111
- Pair the phone from KKCode's notification settings or scan the Agent QR code.
112
- The CLI stores the stable Agent/Service identity in
113
- `~/.config/kkcode/agent.json`, detects whether the installed runtime is
114
- OpenCode 1 or 2, and incrementally registers the matching plugin entry in the
115
- global `opencode.json(c)`. Existing JSONC comments and unrelated plugins are
116
- preserved. Restart OpenCode after first-time registration.
117
-
118
- The npm package exposes one shared entrypoint (`""`, `./plugin` and `./server`
119
- all resolve to the same file). Its default export carries both shapes:
120
- OpenCode 1 loads `server()`, OpenCode 2 loads `setup`. Both map runtime events
121
- to the same five KKCode notification types, so the phone and Go notification
122
- service do not need version-specific configuration.
123
-
124
- ## How it works
125
-
126
- - The CLI registers as a "host" on the relay over a single WebSocket.
127
- - The CLI generates a random shared secret and derives an opaque tunnel ID with SHA-256.
128
- - The phone hits `https://relay.example.com/t/<tunnel-id>/...` with the secret in a
129
- header. The relay forwards each request frame-by-frame over the WebSocket to
130
- the CLI, which then `fetch()`es the local `opencode serve` and streams the
131
- response back.
132
- - Streaming endpoints (SSE) pass through unchanged — chunks are forwarded as
133
- they arrive.
134
-
135
- The secret is persisted in `~/.config/kkcode/tunnel/config.json` so that
136
- restarting or reconnecting the CLI gets you the **same tunnel** without a
137
- second scan.
62
+ | Flag | Description | Default |
63
+ | -------------------- | ------------------------------------------------------------------ | ------------------------------------------------- |
64
+ | `--relay <url>` | Relay base URL (`ws://`, `wss://`, `http://`, `https://`) | `$OPENCODE_RELAY_URL` or `wss://relay.kkcode.app` |
65
+ | `--notify-api <url>` | Notify 2.0 API base URL | `$KKCODE_NOTIFY_API_URL` or `https://api.kkcode.app` |
66
+ | `--port <n>` | Port for `opencode serve` (random free port if omitted) | random |
67
+ | `--hostname <h>` | Local hostname for `opencode serve` | `127.0.0.1` |
68
+ | `--attach` | Reuse an existing `opencode serve` instead of spawning | off |
69
+ | `--password <pwd>` | Optional Basic Auth password for `opencode serve` | random 24-byte hex in spawn mode |
70
+ | `--command <bin>` | OpenCode binary | `$OPENCODE_CMD` or `opencode` |
71
+ | `--reset-tunnel` | Generate a new host secret and print a new QR v8 | off |
72
+ | `--install` | Install background service (macOS LaunchAgent / Linux systemd) | off |
73
+ | `--uninstall` | Remove and stop the background service | off |
74
+ | `--stop` | Stop the background service | off |
75
+ | `--restart` | Restart the background service | off |
76
+ | `--update` | Upgrade background service to latest npm version | off |
77
+ | `--status` | Show background service status | off |
78
+ | `-v`, `--version` | Print CLI package version and exit | off |
138
79
 
139
80
  ## License
140
81
 
@@ -1,37 +1,35 @@
1
1
  /**
2
- * [INPUT]: 依赖 node:fs/promises、node:child_process、jsonc-parser 与 ./config.ts
3
- * [OUTPUT]: 提供 notify API、配对 ticket、OpenCode 代际探测及 v1/v2 JSONC 增量插件配置
4
- * [POS]: cli/ 的 link/启动配置入口;写 agent.json,并按运行时代际迁移 plugin/plugins 中的 KKCode 项
5
- * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
2
+ * [INPUT]: 依赖 node:fs/promises、node:child_process、jsonc-parser、./config.ts、./notification-core.ts 与 ./qr.ts
3
+ * [OUTPUT]: 提供 OpenCode 2 版本探测、JSONC plugins 数组无损注册、ensureOpenCodePluginConfigured 与 push-setup/link 子命令
4
+ * [POS]: cli 的 OpenCode 2 通知插件注册与纯本地推送配对入口,不依赖隧道即可完成推送配置
5
+ * [PROTOCOL]: Update this header on change, then check CLAUDE.md
6
6
  */
7
7
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
8
  import { spawnSync } from "node:child_process";
9
- import { hostname, homedir } from "node:os";
9
+ import { homedir } from "node:os";
10
10
  import { dirname, join } from "node:path";
11
11
  import { applyEdits, modify, parse } from "jsonc-parser";
12
- import { getAgentIdentity } from "./config.js";
13
- const DEFAULT_API_URL = "https://api.kkcode.app";
14
- const apiUrl = (process.env.KKCODE_NOTIFY_API_URL ?? DEFAULT_API_URL).replace(/\/$/u, "");
15
- const configRoot = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
16
- const agentConfigPath = process.env.KKCODE_AGENT_CONFIG ?? join(configRoot, "kkcode", "agent.json");
12
+ import { ensureHostConfig } from "./config.js";
13
+ import { DEFAULT_NOTIFY_API_URL } from "./notification-core.js";
14
+ import { printConnectionInfo } from "./qr.js";
15
+ export const DEFAULT_RELAY_URL = "wss://relay.kkcode.app";
17
16
  const PLUGIN_PACKAGE = "@kkcode-app/agent";
18
- export function agentNotifyApiUrl() {
19
- return apiUrl;
17
+ const LEGACY_PLUGIN_PACKAGES = ["@kkcode-app/agent", "@kkcode-app/opencode"];
18
+ export function resolveNotifyApiUrl(override) {
19
+ const raw = override ?? process.env.KKCODE_NOTIFY_API_URL ?? DEFAULT_NOTIFY_API_URL;
20
+ return raw.trim().replace(/\/$/u, "");
21
+ }
22
+ function configRootDir() {
23
+ return process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
20
24
  }
21
25
  function flagValue(args, flag) {
22
26
  const index = args.indexOf(flag);
23
27
  return index >= 0 ? args[index + 1]?.trim() : undefined;
24
28
  }
25
- async function writeJSON(path, value) {
26
- await mkdir(dirname(path), { recursive: true });
27
- const temp = `${path}.${process.pid}.tmp`;
28
- await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
29
- await rename(temp, path);
30
- }
31
29
  async function opencodeConfigPath() {
32
30
  if (process.env.OPENCODE_CONFIG)
33
31
  return process.env.OPENCODE_CONFIG;
34
- const directory = join(configRoot, "opencode");
32
+ const directory = join(configRootDir(), "opencode");
35
33
  const jsonc = join(directory, "opencode.jsonc");
36
34
  try {
37
35
  await readFile(jsonc, "utf8");
@@ -49,7 +47,9 @@ function isKKCodePlugin(value) {
49
47
  : value && typeof value === "object" && !Array.isArray(value)
50
48
  ? value.package
51
49
  : undefined;
52
- return (typeof spec === "string" && (spec === PLUGIN_PACKAGE || spec.startsWith(`${PLUGIN_PACKAGE}@`)));
50
+ if (typeof spec !== "string")
51
+ return false;
52
+ return LEGACY_PLUGIN_PACKAGES.some((pkg) => spec === pkg || spec.startsWith(`${pkg}@`));
53
53
  }
54
54
  function patchJSONC(text, path, value) {
55
55
  return applyEdits(text, modify(text, path, value, {
@@ -67,9 +67,13 @@ export function detectOpenCodeGeneration(command = process.env.OPENCODE_CMD ?? "
67
67
  const match = `${result.stdout ?? ""}\n${result.stderr ?? ""}`.match(/\bv?(\d+)\./iu);
68
68
  if (!match)
69
69
  return null;
70
- return Number(match[1]) >= 2 ? "v2" : "v1";
70
+ return Number(match[1]) === 2 ? "v2" : null;
71
71
  }
72
- export async function ensureOpenCodePlugin(generation) {
72
+ /**
73
+ * 无损在 ~/.config/opencode/opencode.json(c) 的 `plugins` 数组里确保存在 "@kkcode-app/agent",
74
+ * 只清理旧版 kkcode 插件名,不触碰无关插件、注释或 OpenCode v1 的单数 `plugin` 字段。
75
+ */
76
+ export async function ensureOpenCodePlugin() {
73
77
  const path = await opencodeConfigPath();
74
78
  let text = "{}\n";
75
79
  try {
@@ -88,96 +92,54 @@ export async function ensureOpenCodePlugin(generation) {
88
92
  throw new Error("OpenCode config must be a valid JSON/JSONC object.");
89
93
  }
90
94
  const config = parsed;
91
- const targetKey = generation === "v2" ? "plugins" : "plugin";
92
- const legacyKey = generation === "v2" ? "plugin" : "plugins";
93
- const target = config[targetKey];
94
- const legacy = config[legacyKey];
95
+ const target = config.plugins;
95
96
  if (target !== undefined && !Array.isArray(target)) {
96
- throw new Error(`OpenCode config field "${targetKey}" must be an array.`);
97
- }
98
- if (legacy !== undefined && !Array.isArray(legacy)) {
99
- throw new Error(`OpenCode config field "${legacyKey}" must be an array.`);
97
+ throw new Error('OpenCode config field "plugins" must be an array.');
100
98
  }
101
99
  const nextTarget = (Array.isArray(target) ? target : []).filter((item) => !isKKCodePlugin(item));
102
100
  nextTarget.push(PLUGIN_PACKAGE);
103
- const nextLegacy = (Array.isArray(legacy) ? legacy : []).filter((item) => !isKKCodePlugin(item));
104
101
  const targetAlreadyCanonical = Array.isArray(target) &&
105
102
  target.length === nextTarget.length &&
106
103
  target.every((item, index) => item === nextTarget[index]);
107
- const legacyAlreadyClean = !Array.isArray(legacy) ||
108
- (legacy.length === nextLegacy.length &&
109
- legacy.every((item, index) => item === nextLegacy[index]));
110
- if (targetAlreadyCanonical && legacyAlreadyClean)
104
+ if (targetAlreadyCanonical)
111
105
  return path;
112
- text = patchJSONC(text, [targetKey], nextTarget);
113
- if (Array.isArray(legacy)) {
114
- text = patchJSONC(text, [legacyKey], nextLegacy);
115
- }
106
+ text = patchJSONC(text, ["plugins"], nextTarget);
116
107
  await mkdir(dirname(path), { recursive: true });
117
108
  const temp = `${path}.${process.pid}.tmp`;
118
109
  await writeFile(temp, text.endsWith("\n") ? text : `${text}\n`, { mode: 0o600 });
119
110
  await rename(temp, path);
120
111
  return path;
121
112
  }
122
- export async function configureAgentRuntime(identity, _backend, command = process.env.OPENCODE_CMD ?? "opencode") {
123
- await writeJSON(agentConfigPath, {
124
- node_id: identity.nodeId,
125
- node_secret: identity.nodeSecret,
126
- service_id: identity.serviceId,
127
- api_url: apiUrl,
128
- });
113
+ export async function ensureOpenCodePluginConfigured(command = process.env.OPENCODE_CMD ?? "opencode") {
129
114
  const detected = detectOpenCodeGeneration(command);
130
115
  if (!detected) {
131
- throw new Error(`Could not detect the OpenCode generation from '${command} --version'.`);
132
- }
133
- return { generation: detected, configPath: await ensureOpenCodePlugin(detected) };
134
- }
135
- export async function createAgentLinkTicket(identity, backend) {
136
- const response = await fetch(`${apiUrl}/v1/agent-link-tickets`, {
137
- method: "POST",
138
- headers: { "Content-Type": "application/json" },
139
- body: JSON.stringify({
140
- node_id: identity.nodeId,
141
- node_secret: identity.nodeSecret,
142
- service_id: identity.serviceId,
143
- backend,
144
- machine_label: (process.env.KKCODE_AGENT_MACHINE_LABEL ?? hostname()).slice(0, 80),
145
- }),
146
- });
147
- const body = (await response.json().catch(() => ({})));
148
- if (!response.ok || !body.ticket || !Number.isFinite(body.expiresAt)) {
149
- throw new Error(body.message ?? `Could not prepare notification linking (${response.status}).`);
116
+ throw new Error(`OpenCode 2 is required. Could not verify it from '${command} --version'.`);
150
117
  }
151
- return { ticket: body.ticket, expiresAt: body.expiresAt };
118
+ return { generation: detected, configPath: await ensureOpenCodePlugin() };
152
119
  }
153
- export async function runAgentLink(args) {
154
- const ticket = flagValue(args, "--ticket");
155
- const backend = (flagValue(args, "--backend") ?? "opencode");
120
+ /**
121
+ * 纯本地推送配置入口(`kkcode push-setup` / `kkcode link`):
122
+ * 生成/读取 host.json + 注册 OpenCode 2 插件 + 打印 QR v8 供手机扫码绑定推送。
123
+ */
124
+ export async function runPushSetup(args) {
125
+ const relay = flagValue(args, "--relay") ?? process.env.OPENCODE_RELAY_URL ?? DEFAULT_RELAY_URL;
126
+ const notifyApiOverride = flagValue(args, "--notify-api");
156
127
  const command = flagValue(args, "--command") ?? process.env.OPENCODE_CMD ?? "opencode";
157
- if (!ticket || !/^[A-Za-z0-9_-]{32,256}$/u.test(ticket)) {
158
- throw new Error("A valid one-time --ticket is required.");
159
- }
160
- if (backend !== "opencode") {
161
- throw new Error("--backend must be opencode.");
162
- }
163
- const identity = await getAgentIdentity(backend);
164
- const response = await fetch(`${apiUrl}/v1/agent-links/claim`, {
165
- method: "POST",
166
- headers: { "Content-Type": "application/json" },
167
- body: JSON.stringify({
168
- ticket,
169
- node_id: identity.nodeId,
170
- node_secret: identity.nodeSecret,
171
- service_id: identity.serviceId,
172
- backend,
173
- machine_label: (process.env.KKCODE_AGENT_MACHINE_LABEL ?? hostname()).slice(0, 80),
174
- }),
128
+ const label = flagValue(args, "--label");
129
+ const reset = args.includes("--reset-tunnel");
130
+ const notifyApiUrl = resolveNotifyApiUrl(notifyApiOverride);
131
+ const hostConfig = await ensureHostConfig({
132
+ reset,
133
+ notifyApiUrl: notifyApiOverride ? notifyApiUrl : undefined,
134
+ label,
175
135
  });
176
- const body = (await response.json().catch(() => ({})));
177
- if (!response.ok)
178
- throw new Error(body.message ?? `Link request failed (${response.status}).`);
179
- const configured = await configureAgentRuntime(identity, backend, command);
180
- console.log(`OpenCode ${configured.generation === "v2" ? "2" : "1"} plugin registered in ${configured.configPath}. Restart OpenCode to load it.`);
181
- console.log(`Linked Agent service ${identity.serviceId} to this phone.`);
136
+ const configured = await ensureOpenCodePluginConfigured(command);
137
+ console.log(`[agent] OpenCode 2 plugin registered in ${configured.configPath}.`);
138
+ printConnectionInfo({
139
+ relay,
140
+ api: hostConfig.notifyApiUrl ?? notifyApiUrl,
141
+ secret: hostConfig.secret,
142
+ label: hostConfig.label,
143
+ }, { mode: "push-only" });
182
144
  }
183
145
  //# sourceMappingURL=agent-link.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-link.js","sourceRoot":"","sources":["../src/agent-link.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAmB,MAAM,cAAc,CAAC;AAE1E,OAAO,EAAE,gBAAgB,EAAsB,MAAM,aAAa,CAAC;AAEnE,MAAM,eAAe,GAAG,wBAAwB,CAAC;AACjD,MAAM,MAAM,GAAG,CAAC,OAAO,CAAC,GAAG,CAA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,KAAK;QACL,GAAG,EAAE,UAAU,CAAC,YAAY,IAAI,YAAY;QAC5C,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,KAAK,EAAE,UAAU,CAAC,KAAK;KACxB,EACD,EAAE,IAAI,EAAE,WAAW,EAAE,CACtB,CAAC;AACJ,CAAC"}
package/dist/config.js CHANGED
@@ -1,89 +1,121 @@
1
1
  /**
2
- * [INPUT]: 依赖 node:fs/promises、node:os、node:path 的本地配置文件能力
3
- * [OUTPUT]: 对外提供 TunnelBackend/TunnelConfig、稳定 Agent/Service 身份及 tunnel secret
4
- * [POS]: cli 的 OpenCode 隧道与 Agent 身份持久化层,node_id 与 service_id 跨重连稳定
5
- * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
2
+ * [INPUT]: 依赖 node:fs/promises、node:os、node:path 与 ./crypto.ts 的 secret 生成与校验
3
+ * [OUTPUT]: 提供 HostConfig 类型、hostConfigPath、loadHostConfig、saveHostConfig 与 ensureHostConfig
4
+ * [POS]: cli 统一 Host 身份持久化层,管理 ~/.config/kkcode/host.json 的 0o600 原子写入与进程内串行写
5
+ * [PROTOCOL]: Update this header on change, then check CLAUDE.md
6
6
  */
7
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
7
+ import { mkdir, mkdtemp, open, readFile, rename, rm } from "node:fs/promises";
8
8
  import { homedir } from "node:os";
9
9
  import { dirname, join } from "node:path";
10
- function configDir() {
11
- return join(homedir(), ".config", "kkcode", "tunnel");
10
+ import { decodeSecret, generateSecret } from "./crypto.js";
11
+ export function hostConfigPath() {
12
+ if (process.env.KKCODE_HOST_CONFIG) {
13
+ return process.env.KKCODE_HOST_CONFIG;
14
+ }
15
+ const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
16
+ return join(base, "kkcode", "host.json");
12
17
  }
13
- function configFile() {
14
- return join(configDir(), "config.json");
18
+ function isRecord(value) {
19
+ return value !== null && typeof value === "object" && !Array.isArray(value);
15
20
  }
16
- function legacyFile() {
17
- return join(homedir(), ".config", "opencode-tunnel", "config.json");
21
+ function normalizeOptionalString(value, field) {
22
+ if (value === undefined)
23
+ return undefined;
24
+ if (typeof value !== "string") {
25
+ throw new Error(`Invalid host config: "${field}" must be a string`);
26
+ }
27
+ const trimmed = value.trim();
28
+ return trimmed.length > 0 ? trimmed : undefined;
18
29
  }
19
- async function migrateLegacyConfig() {
20
- try {
21
- await mkdir(dirname(configFile()), { recursive: true });
22
- await rename(legacyFile(), configFile());
30
+ function parseHostConfig(raw) {
31
+ const parsed = JSON.parse(raw);
32
+ if (!isRecord(parsed)) {
33
+ throw new Error("Invalid host config: expected a JSON object");
23
34
  }
24
- catch (err) {
25
- if (err.code !== "ENOENT")
26
- throw err;
35
+ if (typeof parsed.secret !== "string") {
36
+ throw new Error('Invalid host config: missing "secret"');
27
37
  }
38
+ decodeSecret(parsed.secret);
39
+ const notifyApiUrl = normalizeOptionalString(parsed.notifyApiUrl, "notifyApiUrl")?.replace(/\/$/u, "");
40
+ const label = normalizeOptionalString(parsed.label, "label");
41
+ return {
42
+ secret: parsed.secret,
43
+ ...(notifyApiUrl ? { notifyApiUrl } : {}),
44
+ ...(label ? { label } : {}),
45
+ };
28
46
  }
29
- const DEFAULT = { secrets: {} };
30
- export async function loadConfig() {
31
- await migrateLegacyConfig();
47
+ async function publishHostConfig(path, cfg) {
48
+ const normalized = parseHostConfig(JSON.stringify(cfg));
49
+ const raw = `${JSON.stringify(normalized, null, 2)}\n`;
50
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
51
+ const tempDir = await mkdtemp(join(dirname(path), ".host-config-"));
52
+ const tempFile = join(tempDir, "host.json");
32
53
  try {
33
- const raw = await readFile(configFile(), "utf8");
34
- const parsed = JSON.parse(raw);
35
- const identity = parsed.identity;
36
- return {
37
- secrets: parsed.secrets ??
38
- Object.fromEntries(Object.entries(parsed.tunnels ?? {}).flatMap(([relayUrl, identity]) => typeof identity?.secret === "string" ? [[relayUrl, identity.secret]] : [])),
39
- identity: identity &&
40
- typeof identity === "object" &&
41
- typeof identity.nodeId === "string" &&
42
- typeof identity.nodeSecret === "string" &&
43
- identity.serviceIds &&
44
- typeof identity.serviceIds === "object"
45
- ? identity
46
- : undefined,
47
- };
54
+ const file = await open(tempFile, "wx", 0o600);
55
+ try {
56
+ await file.writeFile(raw, "utf8");
57
+ await file.sync();
58
+ }
59
+ finally {
60
+ await file.close();
61
+ }
62
+ await rename(tempFile, path);
48
63
  }
49
- catch (err) {
50
- if (err.code === "ENOENT")
51
- return { ...DEFAULT };
52
- throw err;
64
+ finally {
65
+ await rm(tempDir, { recursive: true, force: true });
53
66
  }
54
67
  }
55
- export async function saveConfig(cfg) {
56
- await mkdir(dirname(configFile()), { recursive: true });
57
- await writeFile(configFile(), JSON.stringify(cfg, null, 2), { mode: 0o600 });
68
+ async function readHostConfigAt(path) {
69
+ try {
70
+ return parseHostConfig(await readFile(path, "utf8"));
71
+ }
72
+ catch (error) {
73
+ if (error.code === "ENOENT")
74
+ return null;
75
+ throw error;
76
+ }
58
77
  }
59
- function secretKey(relayUrl, backend) {
60
- return relayUrl;
78
+ const writes = new Map();
79
+ function withConfigWrite(operation) {
80
+ const path = hostConfigPath();
81
+ const previous = writes.get(path) ?? Promise.resolve();
82
+ const result = previous.catch(() => undefined).then(() => operation(path));
83
+ writes.set(path, result);
84
+ void result
85
+ .finally(() => {
86
+ if (writes.get(path) === result)
87
+ writes.delete(path);
88
+ })
89
+ .catch(() => undefined);
90
+ return result;
61
91
  }
62
- export async function getTunnelSecret(relayUrl, backend = "opencode") {
63
- const cfg = await loadConfig();
64
- return cfg.secrets[secretKey(relayUrl, backend)];
92
+ export async function loadHostConfig() {
93
+ return readHostConfigAt(hostConfigPath());
65
94
  }
66
- export async function setTunnelSecret(relayUrl, secret, backend = "opencode") {
67
- const cfg = await loadConfig();
68
- cfg.secrets[secretKey(relayUrl, backend)] = secret;
69
- await saveConfig(cfg);
95
+ export async function saveHostConfig(cfg) {
96
+ await withConfigWrite(async (path) => {
97
+ await publishHostConfig(path, cfg);
98
+ });
70
99
  }
71
- /**
72
- * A node identifies this computer's Agent installation. A service identifies
73
- * one backend hosted by it. Neither identity changes when a tunnel reconnects
74
- * or its capability secret is rotated.
75
- */
76
- export async function getAgentIdentity(backend) {
77
- const cfg = await loadConfig();
78
- const nodeId = cfg.identity?.nodeId ?? crypto.randomUUID();
79
- const nodeSecret = cfg.identity?.nodeSecret ?? crypto.randomUUID() + crypto.randomUUID();
80
- const serviceId = cfg.identity?.serviceIds?.[backend] ?? crypto.randomUUID();
81
- cfg.identity = {
82
- nodeId,
83
- nodeSecret,
84
- serviceIds: { ...cfg.identity?.serviceIds, [backend]: serviceId },
85
- };
86
- await saveConfig(cfg);
87
- return { nodeId, nodeSecret, serviceId };
100
+ export async function ensureHostConfig(opts) {
101
+ return withConfigWrite(async (path) => {
102
+ const existing = opts?.reset ? null : await readHostConfigAt(path);
103
+ const nextNotifyApiUrl = opts?.notifyApiUrl !== undefined
104
+ ? opts.notifyApiUrl.trim().replace(/\/$/u, "") || undefined
105
+ : existing?.notifyApiUrl;
106
+ const nextLabel = opts?.label !== undefined ? opts.label.trim() || undefined : existing?.label;
107
+ if (existing &&
108
+ existing.notifyApiUrl === nextNotifyApiUrl &&
109
+ existing.label === nextLabel) {
110
+ return existing;
111
+ }
112
+ const next = {
113
+ secret: existing?.secret ?? generateSecret(),
114
+ ...(nextNotifyApiUrl ? { notifyApiUrl: nextNotifyApiUrl } : {}),
115
+ ...(nextLabel ? { label: nextLabel } : {}),
116
+ };
117
+ await publishHostConfig(path, next);
118
+ return next;
119
+ });
88
120
  }
89
121
  //# sourceMappingURL=config.js.map