@zhin.js/adapter-line 0.1.0 → 1.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +596 -0
  2. package/README.md +54 -22
  3. package/adapters/line.js +31 -0
  4. package/adapters/line.ts +36 -0
  5. package/agent/tools/get_group_members.ts +16 -0
  6. package/agent/tools/get_profile.ts +16 -0
  7. package/commands/endpoint/add/[id].js +3 -0
  8. package/commands/endpoint/add/[id].ts +3 -0
  9. package/commands/endpoint/list.js +3 -0
  10. package/commands/endpoint/list.ts +3 -0
  11. package/commands/endpoint/remove/[id].js +3 -0
  12. package/commands/endpoint/remove/[id].ts +3 -0
  13. package/lib/client.d.ts +33 -0
  14. package/lib/client.js +54 -0
  15. package/lib/endpoint.d.ts +41 -37
  16. package/lib/endpoint.js +149 -500
  17. package/lib/index.d.ts +4 -15
  18. package/lib/index.js +4 -83
  19. package/lib/line-endpoint-commands.d.ts +1 -0
  20. package/lib/line-endpoint-commands.js +17 -0
  21. package/lib/line-runtime-state.d.ts +1 -0
  22. package/lib/line-runtime-state.js +6 -0
  23. package/lib/protocol.d.ts +158 -0
  24. package/lib/protocol.js +265 -0
  25. package/lib/side-event-dispatch.d.ts +4 -0
  26. package/lib/side-event-dispatch.js +42 -0
  27. package/lib/webhook.d.ts +13 -0
  28. package/lib/webhook.js +50 -0
  29. package/package.json +61 -21
  30. package/plugin.js +14 -0
  31. package/schema.json +86 -0
  32. package/src/client.ts +87 -0
  33. package/src/endpoint.ts +197 -551
  34. package/src/index.ts +51 -100
  35. package/src/line-endpoint-commands.ts +18 -0
  36. package/src/line-runtime-state.ts +7 -0
  37. package/src/protocol.ts +442 -0
  38. package/src/side-event-dispatch.ts +54 -0
  39. package/src/webhook.ts +79 -0
  40. package/lib/adapter.d.ts +0 -15
  41. package/lib/adapter.d.ts.map +0 -1
  42. package/lib/adapter.js +0 -20
  43. package/lib/adapter.js.map +0 -1
  44. package/lib/endpoint.d.ts.map +0 -1
  45. package/lib/endpoint.js.map +0 -1
  46. package/lib/index.d.ts.map +0 -1
  47. package/lib/index.js.map +0 -1
  48. package/lib/types.d.ts +0 -112
  49. package/lib/types.d.ts.map +0 -1
  50. package/lib/types.js +0 -5
  51. package/lib/types.js.map +0 -1
  52. package/plugin.yml +0 -3
  53. package/src/adapter.ts +0 -29
  54. package/src/types.ts +0 -130
  55. /package/{skills/line → agent}/PERMITS.md +0 -0
  56. /package/{skills/line/SKILL.md → agent/skills/line.md} +0 -0
package/README.md CHANGED
@@ -1,13 +1,31 @@
1
1
  # @zhin.js/adapter-line
2
2
 
3
- Zhin.js 适配器 — LINE Messaging API (Webhook 模式)
3
+ Zhin.js LINE Messaging API 适配器(Plugin Runtime),通过 Runtime Host HTTP Webhook 收发消息。
4
4
 
5
5
  ## 功能
6
6
 
7
- - 接收并解析 LINE Webhook 事件(text、image、video、audio、file、location、sticker)
8
- - 支持私聊、群组、多人聊天(room)三种场景
9
- - Reply API / Push API 发送消息
10
- - HMAC-SHA256 签名验证
7
+ - Webhook 事件接收(`httpHostToken` POST + HMAC-SHA256 签名验证)
8
+ - 解析 text / image / video / audio / file / location / sticker
9
+ - 支持私聊、群组、多人聊天(room)
10
+ - Reply API(有 replyToken 时)/ Push API 发送
11
+ - 约定式 `defineAdapter` / `definePlugin`(无需 `usePlugin`)
12
+
13
+ ## 安装
14
+
15
+ ```bash
16
+ pnpm add @zhin.js/adapter-line
17
+ ```
18
+
19
+ ## Plugin Runtime
20
+
21
+ - `@zhin.js/adapter` — 约定式 `adapters/line.ts`(`defineAdapter`)
22
+ - `@zhin.js/core` — `Endpoint.emit(...)` 入站、`outboundMessageToken` 出站
23
+ - `@zhin.js/host-http` — `httpHostToken` 注册 Webhook 路由(**非** legacy host-router/Koa)
24
+ - `zhin.js` — `plugin.ts`(`definePlugin`)
25
+ - 配置经插件 `schema.json` 落到 `plugins.<instanceKey>`
26
+
27
+ 入站:`gateway.receive({ conversation, message: { conversation, id }, content: text, sender, metadata })`
28
+ 出站:`send({ conversation, payload })` → Reply API(缓存 replyToken)或 Push API
11
29
 
12
30
  ## 前置条件
13
31
 
@@ -15,20 +33,26 @@ Zhin.js 适配器 — LINE Messaging API (Webhook 模式)
15
33
  2. 获取 **Channel Secret** 和 **Channel Access Token**
16
34
  3. 设置 Webhook URL 为 `https://your-domain/line/webhook`
17
35
  4. 在 Console 中启用 **Use webhooks** 并关闭 **Auto-reply messages**
36
+ 5. Runtime Host(`http`)须已 listen,Webhook 才可达
37
+
38
+ 必填字段(`endpoints[i]`):`name`、`channelSecret`、`channelAccessToken`。
18
39
 
19
40
  ## 最小配置
20
41
 
21
42
  ```yaml
22
- # zhin.config.yml
23
- adapters:
24
- - context: line
25
- name: my-line-bot
26
- channelSecret: ${LINE_CHANNEL_SECRET}
27
- channelAccessToken: ${LINE_CHANNEL_ACCESS_TOKEN}
43
+ # zhin.config.yml(Plugin Runtime)
44
+ plugins:
45
+ line:
28
46
  webhookPath: /line/webhook # 可选,默认 /line/webhook
29
47
  apiBaseUrl: https://api.line.me # 可选,调试时可改为 LINE API 沙盒地址
48
+ endpoints:
49
+ - name: my-line-bot
50
+ channelSecret: ${LINE_CHANNEL_SECRET}
51
+ channelAccessToken: ${LINE_CHANNEL_ACCESS_TOKEN}
30
52
  ```
31
53
 
54
+ 根插件 `zhin.plugins`(或项目图)需引用 `@zhin.js/adapter-line`(`instanceKey: line`)。
55
+
32
56
  ## 环境变量
33
57
 
34
58
  | 变量 | 说明 |
@@ -40,7 +64,7 @@ adapters:
40
64
 
41
65
  LINE 要求 Webhook URL 以 HTTPS 开头。常见方案:
42
66
 
43
- - **反向代理**:Nginx/Caddy 将 `https://your-domain/line/webhook` 转发到本地 zhIn 端口
67
+ - **反向代理**:Nginx/Caddy 将 `https://your-domain/line/webhook` 转发到本地 zhin 端口
44
68
  - **Cloudflare Tunnel**:`cloudflared tunnel --url http://localhost:端口`
45
69
  - **ngrok**:调试用 `ngrok http 端口`
46
70
 
@@ -48,15 +72,23 @@ LINE 要求 Webhook URL 以 HTTPS 开头。常见方案:
48
72
 
49
73
  ## 消息类型映射
50
74
 
51
- | LINE 类型 | Zhin.js Segment | 说明 |
52
- |-----------|----------------|------|
53
- | text | text | 纯文本 |
54
- | image | image | 图片(暂不支持二次获取) |
55
- | video | video | 视频 |
56
- | audio | audio | 音频 |
57
- | file | file | 文件 |
58
- | location | location | 位置信息 |
59
- | sticker | sticker | 贴纸 |
75
+ | LINE 类型 | 入站 content(文本摘要) | 出站 wire |
76
+ |-----------|--------------------------|-----------|
77
+ | text | 原文 | text |
78
+ | image | `[image]` | image(需 `url`) |
79
+ | video | `[video]` | video(需 `url`) |
80
+ | audio | `[audio]` | audio(需 `url`) |
81
+ | file | `[file: name]` | |
82
+ | location | address 或坐标 | location |
83
+ | sticker | `[sticker: pkg/id]` | sticker |
84
+
85
+ ## AI 工具
86
+
87
+ | 类别 | 路径 |
88
+ |------|------|
89
+ | Permit 词汇 | `agent/PERMITS.md` |
90
+ | 平台工具(2 个) | `agent/tools/`(`line_get_profile`、`line_get_group_members`) |
91
+ | 技能说明 | `agent/skills/line.md` |
60
92
 
61
93
  ## 已知限制
62
94
 
@@ -69,7 +101,7 @@ LINE 要求 Webhook URL 以 HTTPS 开头。常见方案:
69
101
 
70
102
  | 问题 | 排查方法 |
71
103
  |------|---------|
72
- | Webhook Verify 失败 | 检查 HTTPS 证书、域名解析、端口是否可达 |
104
+ | Webhook Verify 失败 | 检查 HTTPS 证书、域名解析、端口是否可达;确认 host-http 已 listen |
73
105
  | 签名验证 403 | 确认 Channel Secret 与 Console 一致 |
74
106
  | 发送 401 | 确认 Channel Access Token 未过期 |
75
107
  | 发送 400 | 检查消息格式是否符合 LINE API 规范 |
@@ -0,0 +1,31 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ /**
3
+ * Convention entry: discover `adapters/line.ts` → defineAdapter.
4
+ */
5
+ import { defineAdapter } from 'zhin.js/adapter';
6
+ import { httpHostToken } from '@zhin.js/host-http';
7
+ import { LineEndpoint } from "../lib/endpoint.js";
8
+ import { resolveLineConfig, } from "../lib/protocol.js";
9
+ import { lineRuntimeStateToken } from "../lib/line-runtime-state.js";
10
+ export { LineEndpoint } from "../lib/endpoint.js";
11
+ export default defineAdapter({
12
+ capabilities: ['inbound', 'outbound'],
13
+ // LINE Messaging API 媒体消息仅消费远程 URL;无按钮交互面,交互段降级纯文本。
14
+ segments: {
15
+ outboundMedia: ['url'],
16
+ interactive: 'text',
17
+ },
18
+ create(context) {
19
+ const config = resolveLineConfig(context.config);
20
+ // 注册到插件运行时状态(line.endpoint list 的"运行中"数据源)
21
+ context.use(lineRuntimeStateToken).endpoints.set(config.id, {
22
+ id: config.id,
23
+ mode: 'webhook',
24
+ });
25
+ return new LineEndpoint({
26
+ id: context.id,
27
+ http: context.use(httpHostToken),
28
+ config,
29
+ });
30
+ },
31
+ });
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Convention entry: discover `adapters/line.ts` → defineAdapter.
3
+ */
4
+ import { defineAdapter } from 'zhin.js/adapter';
5
+ import { httpHostToken } from '@zhin.js/host-http';
6
+ import { LineEndpoint } from '../src/endpoint.js';
7
+ import {
8
+ resolveLineConfig,
9
+ type LineAdapterConfig,
10
+ } from '../src/protocol.js';
11
+ import { lineRuntimeStateToken } from '../src/line-runtime-state.js';
12
+
13
+ export { LineEndpoint } from '../src/endpoint.js';
14
+ export type { LineEndpointOptions, LineFetch } from '../src/endpoint.js';
15
+
16
+ export default defineAdapter<LineAdapterConfig>({
17
+ capabilities: ['inbound', 'outbound'],
18
+ // LINE Messaging API 媒体消息仅消费远程 URL;无按钮交互面,交互段降级纯文本。
19
+ segments: {
20
+ outboundMedia: ['url'],
21
+ interactive: 'text',
22
+ },
23
+ create(context) {
24
+ const config = resolveLineConfig(context.config);
25
+ // 注册到插件运行时状态(line.endpoint list 的"运行中"数据源)
26
+ context.use(lineRuntimeStateToken).endpoints.set(config.id, {
27
+ id: config.id,
28
+ mode: 'webhook',
29
+ });
30
+ return new LineEndpoint({
31
+ id: context.id,
32
+ http: context.use(httpHostToken),
33
+ config,
34
+ });
35
+ },
36
+ });
@@ -0,0 +1,16 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+
4
+ export default defineAgentTool<{ groupId: string }>({
5
+ description: 'Get LINE group member IDs',
6
+ adapter: 'line',
7
+ inputSchema: z.object({
8
+ groupId: z.string().min(1),
9
+ }),
10
+ async execute({ groupId }, context) {
11
+ if (!groupId.startsWith('G')) {
12
+ throw new Error(`Invalid groupId "${groupId}": must start with G`);
13
+ }
14
+ return context.$client.getGroupMemberIds(groupId);
15
+ },
16
+ });
@@ -0,0 +1,16 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+
4
+ export default defineAgentTool<{ userId: string }>({
5
+ description: 'Get LINE user profile by userId',
6
+ adapter: 'line',
7
+ inputSchema: z.object({
8
+ userId: z.string().min(1),
9
+ }),
10
+ async execute({ userId }, context) {
11
+ if (!userId.startsWith('U')) {
12
+ throw new Error(`Invalid userId "${userId}": must start with U`);
13
+ }
14
+ return context.$client.getProfile(userId);
15
+ },
16
+ });
@@ -0,0 +1,3 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { lineEndpointCommands } from "../../../lib/line-endpoint-commands.js";
3
+ export default lineEndpointCommands.add;
@@ -0,0 +1,3 @@
1
+ import { lineEndpointCommands } from '../../../src/line-endpoint-commands.js';
2
+
3
+ export default lineEndpointCommands.add;
@@ -0,0 +1,3 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { lineEndpointCommands } from "../../lib/line-endpoint-commands.js";
3
+ export default lineEndpointCommands.list;
@@ -0,0 +1,3 @@
1
+ import { lineEndpointCommands } from '../../src/line-endpoint-commands.js';
2
+
3
+ export default lineEndpointCommands.list;
@@ -0,0 +1,3 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { lineEndpointCommands } from "../../../lib/line-endpoint-commands.js";
3
+ export default lineEndpointCommands.remove;
@@ -0,0 +1,3 @@
1
+ import { lineEndpointCommands } from '../../../src/line-endpoint-commands.js';
2
+
3
+ export default lineEndpointCommands.remove;
@@ -0,0 +1,33 @@
1
+ import type { LineFetch } from './endpoint.js';
2
+ import type { LineEvent, ResolvedLineConfig } from './protocol.js';
3
+ export interface LineGroupMember {
4
+ readonly user_id: string;
5
+ readonly nickname: string;
6
+ }
7
+ /** Direct LINE Messaging API client; it has no Endpoint lifecycle methods. */
8
+ export declare class LineClient {
9
+ readonly config: ResolvedLineConfig;
10
+ readonly fetch: LineFetch;
11
+ constructor(config: ResolvedLineConfig, fetch: LineFetch);
12
+ request<T = unknown>(path: string, init?: {
13
+ readonly method?: string;
14
+ readonly body?: string;
15
+ readonly signal?: AbortSignal;
16
+ }): Promise<T>;
17
+ getProfile(userId: string): Promise<unknown>;
18
+ getGroupMemberIds(groupId: string, start?: string): Promise<{
19
+ readonly memberIds?: string[];
20
+ readonly next?: string;
21
+ }>;
22
+ getGroupMembers(groupId: string): Promise<LineGroupMember[]>;
23
+ }
24
+ export type LineClientEventMap = Record<string, LineEvent>;
25
+ declare module '@zhin.js/feature-kit' {
26
+ interface AdapterClientRegistry {
27
+ readonly line: {
28
+ readonly client: LineClient;
29
+ readonly events: LineClientEventMap;
30
+ };
31
+ }
32
+ }
33
+ export declare const lineClient: import("@zhin.js/adapter").EndpointClientToken<LineClient, LineClientEventMap>;
package/lib/client.js ADDED
@@ -0,0 +1,54 @@
1
+ import { defineEndpointClient } from 'zhin.js/adapter';
2
+ /** Direct LINE Messaging API client; it has no Endpoint lifecycle methods. */
3
+ export class LineClient {
4
+ config;
5
+ fetch;
6
+ constructor(config, fetch) {
7
+ this.config = config;
8
+ this.fetch = fetch;
9
+ }
10
+ async request(path, init = {}) {
11
+ const response = await this.fetch(`${this.config.apiBaseUrl}${path}`, {
12
+ method: init.method ?? 'GET',
13
+ headers: {
14
+ Authorization: `Bearer ${this.config.channelAccessToken}`,
15
+ ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }),
16
+ },
17
+ ...(init.body === undefined ? {} : { body: init.body }),
18
+ signal: init.signal ?? AbortSignal.timeout(30_000),
19
+ });
20
+ if (!response.ok) {
21
+ const text = await response.text();
22
+ throw new Error(`LINE API error ${response.status}: ${text}`);
23
+ }
24
+ return await response.json();
25
+ }
26
+ getProfile(userId) {
27
+ return this.request(`/v2/profile/${encodeURIComponent(userId)}`);
28
+ }
29
+ getGroupMemberIds(groupId, start) {
30
+ const kind = groupId.startsWith('R') ? 'room' : 'group';
31
+ const query = start ? `?start=${encodeURIComponent(start)}` : '';
32
+ return this.request(`/v2/bot/${kind}/${encodeURIComponent(groupId)}/members/ids${query}`);
33
+ }
34
+ async getGroupMembers(groupId) {
35
+ const kind = groupId.startsWith('R') ? 'room' : 'group';
36
+ const ids = [];
37
+ let next;
38
+ do {
39
+ const page = await this.getGroupMemberIds(groupId, next);
40
+ ids.push(...(page.memberIds ?? []).filter((id) => typeof id === 'string' && id.length > 0));
41
+ next = page.next || undefined;
42
+ } while (next);
43
+ return Promise.all(ids.map(async (userId) => {
44
+ try {
45
+ const profile = await this.request(`/v2/bot/${kind}/${encodeURIComponent(groupId)}/member/${encodeURIComponent(userId)}`);
46
+ return { user_id: userId, nickname: String(profile.displayName ?? userId) };
47
+ }
48
+ catch {
49
+ return { user_id: userId, nickname: userId };
50
+ }
51
+ }));
52
+ }
53
+ }
54
+ export const lineClient = defineEndpointClient('line');
package/lib/endpoint.d.ts CHANGED
@@ -1,38 +1,42 @@
1
- import { Endpoint, Message, SendOptions } from "zhin.js";
2
- import { type Router } from "@zhin.js/host-router/router";
3
- import type { LineEndpointConfig, LineEvent } from "./types.js";
4
- import type { LineAdapter } from "./adapter.js";
5
- export declare class LineEndpoint implements Endpoint<LineEndpointConfig, LineEvent> {
6
- adapter: LineAdapter;
7
- private router;
8
- $config: LineEndpointConfig;
9
- $connected: boolean;
10
- get pluginLogger(): import("zhin.js").Logger;
11
- get $id(): string;
12
- constructor(adapter: LineAdapter, router: Router, $config: LineEndpointConfig);
13
- $connect(): Promise<void>;
14
- $disconnect(): Promise<void>;
15
- private handleWebhook;
16
- private verifySignature;
17
- private handleEvent;
18
- private handleMessageEvent;
19
- private handleFollowEvent;
20
- private handleJoinEvent;
21
- $formatMessage(event: LineEvent): Message<LineEvent>;
22
- private generateMessageId;
23
- private resolveChannel;
24
- private extractRawText;
25
- private parseMessageContent;
26
- $sendMessage(options: SendOptions): Promise<string>;
27
- private replyTokenCache;
28
- /**
29
- * 缓存 replyToken,用于后续发送回复消息
30
- */
31
- cacheReplyToken(channelId: string, replyToken: string): void;
32
- private replyMessage;
33
- private pushMessage;
34
- private buildLineMessages;
35
- private buildTextMessage;
36
- $recallMessage(_id: string): Promise<void>;
1
+ import { Endpoint } from 'zhin.js/adapter';
2
+ /**
3
+ * LineEndpoint — lifecycle, outbound, admit, OpenAPI helpers for agent tools.
4
+ */
5
+ import { type EndpointManagement, EndpointSendRequest } from 'zhin.js/adapter';
6
+ import type { HttpHost } from '@zhin.js/host-http';
7
+ import type { CapabilityId } from 'zhin.js';
8
+ import { type LineEvent, type ResolvedLineConfig } from './protocol.js';
9
+ import { LineClient } from './client.js';
10
+ export type LineFetch = (url: string, init?: {
11
+ readonly method?: string;
12
+ readonly headers?: Record<string, string>;
13
+ readonly body?: string;
14
+ readonly signal?: AbortSignal;
15
+ }) => Promise<{
16
+ readonly ok: boolean;
17
+ readonly status: number;
18
+ text(): Promise<string>;
19
+ json(): Promise<unknown>;
20
+ }>;
21
+ export interface LineEndpointOptions {
22
+ readonly id: CapabilityId;
23
+ readonly http: HttpHost;
24
+ readonly config: ResolvedLineConfig;
25
+ readonly fetch?: LineFetch;
26
+ }
27
+ export declare class LineEndpoint extends Endpoint<LineClient> {
28
+ #private;
29
+ readonly client: LineClient;
30
+ readonly management: EndpointManagement;
31
+ constructor(options: LineEndpointOptions);
32
+ /** Used by webhook handler. */
33
+ get isOpen(): boolean;
34
+ get config(): ResolvedLineConfig;
35
+ start(): Promise<void>;
36
+ open(): void;
37
+ close(): void;
38
+ stop(): Promise<void>;
39
+ send({ conversation, payload }: EndpointSendRequest): Promise<string>;
40
+ /** Test / internal: admit a parsed event when open (non-webhook path). */
41
+ admit(event: LineEvent): void;
37
42
  }
38
- //# sourceMappingURL=endpoint.d.ts.map