@zhin.js/adapter-line 1.1.18 → 1.1.19

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/CHANGELOG.md CHANGED
@@ -1,5 +1,43 @@
1
1
  # @zhin.js/adapter-line
2
2
 
3
+ ## 1.1.19
4
+
5
+ ### Patch Changes
6
+
7
+ - 2c3610a: Move account lifecycle ownership into the generic Adapter base and let native Endpoints retain their SDK Client inheritance. Infer platform-specific operation Sessions from a single adapter registry while preserving command parameter, option, configuration and factory inference.
8
+
9
+ Bind message replies, management ports, login challenges and Agent cancellation to the captured account incarnation. Persist runtime account intent with encrypted, revision-checked Host storage; keep account management independent of Root process restarts. Require explicit operator confirmation before importing existing accounts, and give replacement accounts a new identity without inheriting previous Sessions.
10
+
11
+ Expose account save, start, stop, update and replacement through the existing adapter Console, with exact account ownership, truthful pending/unknown outcomes and no startup configuration or environment-file rewrites.
12
+
13
+ Complete the target migration across every adapter, the public authoring API, generators, examples and Console. This intentionally removes the old create factory, inheritable Endpoint/ClientEndpoint classes, Client descriptors and file-rewrite account management; plugin authors must use createAdapter, native Client inheritance and the single AdapterRegistry. Satori and OneBot12 require explicit platform/userId selection, and WeCom requires a separate agentId.
14
+
15
+ Verify opaque credential changes before the same configuration snapshot is committed. Drain admitted native callbacks across close/rollback, cancel target work on stop, and keep raw transport parsing, platform ACK timing and SDK native methods under their existing owners. Account metadata conceals credentials carried in URLs.
16
+
17
+ - a9f4e48: PATCH COMPATIBILITY CUTOVER: this batch intentionally changes plugin APIs. The maintainer explicitly chose patch releases with declared version boundaries. Upgrade the complete tested dependency set; patch numbering does not promise compatibility with the removed interfaces.
18
+
19
+ The first planned floors are zhin.js 1.1.19, Core 1.1.54, Adapter 1.1.26, FeatureKit 1.1.10, Plugin Runtime 1.1.18, Runtime/Isolate 1.1.16 and Agent 1.1.45. Keep old-interface plugins with the earlier locked stack until they are migrated. Adapter's independent Feature API changes from 1.0.0 to 2.0.0; official consumers declare ^2.0.0. Existing Feature API admission rejects explicitly incompatible ranges; omitted API metadata keeps its existing behavior and does not certify compatibility. Runtime engine and patch-only release gates remain unchanged.
20
+
21
+ Use the native-Client Adapter target contract, canonical FeatureKit AdapterRegistry augmentation and named Endpoint control/management requests. Route message controls from canonical message/conversation refs; retain exact source authority and propagate caller/account/explicit-Root-stop cancellation. Replace removed Agent activity feedback exports with source-bound feedback. HMR pause/resume belongs to concrete plugin instances; plugins choose accepted-work policy without changing Controller commit/rollback authority. Cooperative worker/process control cancellation does not kill an isolate or reopen retired business admission.
22
+
23
+ Provide authenticated historical-data preview, exact selected binding, transactional application, authoritative inspection and explicit resumption, including active games. Preserve before-images and journals; never replay an unconfirmed effect, infer an account from an alias, or reuse historical permission grants. Owner V2 approvals remain inactive legacy data, while new writes use V3. Rollback requires matching software, lockfile and verified data; installing old code alone cannot read a new V3 approval file. Conflicting after-images are never overwritten.
24
+
25
+ See docs/plans/adapter-operation-version-boundaries.md and the Chinese/English upgrade guide for the complete version inventory, custom-plugin changes, acceptance and recovery sequence. These code and metadata changes do not authorize merging, publication, deployment, login, production migration or removal of installed workspace patches.
26
+
27
+ - Updated dependencies [2c3610a]
28
+ - Updated dependencies [a9f4e48]
29
+ - Updated dependencies [f8505b0]
30
+ - Updated dependencies [2c3610a]
31
+ - @zhin.js/adapter@1.1.26
32
+ - @zhin.js/feature-kit@1.1.10
33
+ - @zhin.js/core@1.1.54
34
+ - @zhin.js/host-http@1.1.12
35
+ - @zhin.js/client@1.1.22
36
+ - @zhin.js/page@1.1.11
37
+ - @zhin.js/agent-feature@1.1.11
38
+ - @zhin.js/skill@1.1.11
39
+ - @zhin.js/tool@1.1.13
40
+
3
41
  ## 1.1.18
4
42
 
5
43
  ### Patch Changes
package/README.md CHANGED
@@ -18,13 +18,16 @@ pnpm add @zhin.js/adapter-line
18
18
 
19
19
  ## Plugin Runtime
20
20
 
21
+ `LineEndpoint` 的 Client 实际拥有 Messaging API HTTP 与签名 Webhook;未安装 LINE SDK。原始事件保留,框架只经 `endpointSpec` 接入。所属 `Adapter` 是账号期望状态与运行实例的唯一管理者,目录按实际内部身份路由。
22
+
21
23
  - `@zhin.js/adapter` — 约定式 `adapters/line/index.ts`(`defineAdapter`)
22
- - `@zhin.js/core` — `Endpoint.emit(...)` 入站、`outboundMessageToken` 出站
24
+ - `@zhin.js/core` — `endpointSpec.events` 入站、`outboundMessageToken` 出站
23
25
  - `@zhin.js/host-http` — `httpHostToken` 注册 Webhook 路由(**非** legacy host-router/Koa)
24
26
  - `zhin.js` — `plugin.ts`(`definePlugin`)
25
27
  - 配置经插件 `schema.json` 落到顶层 `<instanceKey>`
26
28
 
27
- 入站:`gateway.receive({ conversation, message: { conversation, id }, content: text, sender, metadata })`
29
+ 入站:`endpoint[endpointSpec].events.emit('message.receive', { conversation, message: { conversation, id }, content: text, sender, metadata })`
30
+
28
31
  出站:`send({ conversation, payload })` → Reply API(缓存 replyToken)或 Push API
29
32
 
30
33
  ## 前置条件
@@ -101,13 +104,11 @@ LINE 要求 Webhook URL 以 HTTPS 开头。常见方案:
101
104
 
102
105
  ## Console 页面
103
106
 
104
- 启动后打开 Console 的「LINE」页(地址 `/line`),可以:
107
+ 在所属插件的 Console 页面管理账号:查看配置与运行状态,添加、编辑、启动、停止、替换或删除账号。首次修改启动账号前,管理员需确认迁移清单;保留原身份与历史。此后保存到 Host 运行时存储,不改启动配置或 `.env`,无需重启进程。
105
108
 
106
- - 查看运行中的连接、点「测试连接」做连通性诊断;
107
- - 增删 `plugins.line.endpoints`(凭据写入 `.env`,配置里只保留 `${ENV}` 引用);
108
- - 如果适配器要求登录,页面会显示 LoginAssist 的扫码 / 滑块 / 设备确认待办;
109
+ 新增仅保存,需手动启动;运行账号的普通配置更新只重连该账号。身份变化走明确替换,新账号不会继承旧 Session 或登录状态。账号凭据变化先按平台实际只读接口核验;平台无法核验时需明确替换。空白或遮蔽的密码不会覆盖既有密码。
109
110
 
110
- 读取需要 `line:read`,写操作需要 `line:write`;管理员 full token 不受限。页面里的「添加 endpoint」等价于原来的 `line endpoint add`。
111
+ 读取需要 `line:read`,写入需要 `line:write`;首次迁移还需管理员身份。无持久化存储时管理操作不可用,提交结果未知时先刷新核实,不重复提交。
111
112
 
112
113
  ## 故障排查
113
114
 
@@ -1,12 +1,10 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { LineAdapter } from "../../lib/adapter.js";
2
3
  /**
3
4
  * Convention entry: discover `adapters/line/index.ts` → defineAdapter.
4
5
  */
5
6
  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";
7
+ import {} from "../../lib/protocol.js";
10
8
  export { LineEndpoint } from "../../lib/endpoint.js";
11
9
  export default defineAdapter({
12
10
  capabilities: ['inbound', 'outbound'],
@@ -15,17 +13,5 @@ export default defineAdapter({
15
13
  outboundMedia: ['url'],
16
14
  interactive: 'text',
17
15
  },
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
- },
16
+ createAdapter: context => new LineAdapter(context),
31
17
  });
@@ -1,14 +1,11 @@
1
+ import { LineAdapter } from '../../src/adapter.js';
1
2
  /**
2
3
  * Convention entry: discover `adapters/line/index.ts` → defineAdapter.
3
4
  */
4
5
  import { defineAdapter } from 'zhin.js/adapter';
5
- import { httpHostToken } from '@zhin.js/host-http';
6
- import { LineEndpoint } from '../../src/endpoint.js';
7
6
  import {
8
- resolveLineConfig,
9
7
  type LineEndpointConfig,
10
8
  } from '../../src/protocol.js';
11
- import { lineRuntimeStateToken } from '../../src/line-runtime-state.js';
12
9
 
13
10
  export { LineEndpoint } from '../../src/endpoint.js';
14
11
  export type { LineEndpointOptions, LineFetch } from '../../src/endpoint.js';
@@ -20,17 +17,5 @@ export default defineAdapter<LineEndpointConfig>({
20
17
  outboundMedia: ['url'],
21
18
  interactive: 'text',
22
19
  },
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
- },
20
+ createAdapter: context => new LineAdapter(context),
36
21
  });
@@ -5,7 +5,6 @@
5
5
  */
6
6
  import { createEndpointCommands } from 'zhin.js/adapter';
7
7
  import { defineCommand } from 'zhin.js/command';
8
- import { lineRuntimeStateToken } from "../../../lib/line-runtime-state.js";
9
8
  export const lineEndpointCommands = createEndpointCommands({
10
9
  adapterKey: 'line',
11
10
  adapterDisplayName: 'LINE',
@@ -13,6 +12,5 @@ export const lineEndpointCommands = createEndpointCommands({
13
12
  { key: 'channelSecret', required: true, env: true, description: 'LINE channel secret' },
14
13
  { key: 'channelAccessToken', required: true, env: true, description: 'LINE channel access token' },
15
14
  ],
16
- running: (use) => use(lineRuntimeStateToken).endpoints.values(),
17
15
  describeEntry: (entry) => `channelAccessToken: ${String(entry.channelAccessToken)}`,
18
16
  }, defineCommand);
@@ -4,7 +4,6 @@
4
4
  */
5
5
  import { createEndpointCommands } from 'zhin.js/adapter';
6
6
  import { defineCommand } from 'zhin.js/command';
7
- import { lineRuntimeStateToken } from '../../../src/line-runtime-state.js';
8
7
 
9
8
  export const lineEndpointCommands = createEndpointCommands({
10
9
  adapterKey: 'line',
@@ -13,6 +12,5 @@ export const lineEndpointCommands = createEndpointCommands({
13
12
  { key: 'channelSecret', required: true, env: true, description: 'LINE channel secret' },
14
13
  { key: 'channelAccessToken', required: true, env: true, description: 'LINE channel access token' },
15
14
  ],
16
- running: (use) => use(lineRuntimeStateToken).endpoints.values(),
17
15
  describeEntry: (entry) => `channelAccessToken: ${String(entry.channelAccessToken)}`,
18
16
  }, defineCommand);
@@ -0,0 +1,19 @@
1
+ import { Adapter, type AdapterContext, type EndpointCreationContext } from 'zhin.js/adapter';
2
+ import { LineEndpoint } from './endpoint.js';
3
+ import { type LineEndpointConfig } from './protocol.js';
4
+ import type { LineClientEventMap } from './client.js';
5
+ export declare class LineAdapter extends Adapter<LineEndpoint, LineEndpointConfig, LineClientEventMap> {
6
+ #private;
7
+ constructor(context: AdapterContext<LineEndpointConfig>);
8
+ get configurationIdentityFields(): readonly string[];
9
+ get configurationUpdateFields(): readonly string[];
10
+ get configurationIdentityProbeFields(): readonly string[];
11
+ protected identifyConfiguration(input: LineEndpointConfig, signal: AbortSignal, _changed: readonly string[]): Promise<string | undefined>;
12
+ protected validateConfiguration(config: LineEndpointConfig): void;
13
+ protected createEndpoint(input: LineEndpointConfig, execution: EndpointCreationContext): LineEndpoint;
14
+ }
15
+ declare module '@zhin.js/feature-kit' {
16
+ interface AdapterRegistry {
17
+ readonly 'line': LineAdapter;
18
+ }
19
+ }
package/lib/adapter.js ADDED
@@ -0,0 +1,24 @@
1
+ import { LineApiClient } from './api-client.js';
2
+ import { Adapter } from 'zhin.js/adapter';
3
+ import { LineEndpoint } from './endpoint.js';
4
+ import { resolveLineConfig } from './protocol.js';
5
+ import { httpHostToken } from '@zhin.js/host-http';
6
+ export class LineAdapter extends Adapter {
7
+ #context;
8
+ constructor(context) { super(); this.#context = context; }
9
+ get configurationIdentityFields() { return ['id']; }
10
+ get configurationUpdateFields() { return ['channelSecret', 'channelAccessToken', 'webhookPath', 'apiBaseUrl']; }
11
+ get configurationIdentityProbeFields() { return ['channelAccessToken', 'apiBaseUrl']; }
12
+ async identifyConfiguration(input, signal, _changed) {
13
+ const config = resolveLineConfig(input);
14
+ const response = await new LineApiClient({ config, fetch: globalThis.fetch, signal }).request('/v2/bot/info');
15
+ if (typeof response.userId !== 'string' || !response.userId)
16
+ throw new Error('LINE identity verification returned no userId');
17
+ return JSON.stringify(['line', new URL(config.apiBaseUrl).origin, response.userId]);
18
+ }
19
+ validateConfiguration(config) { resolveLineConfig(config); }
20
+ createEndpoint(input, execution) {
21
+ const config = resolveLineConfig(input);
22
+ return new LineEndpoint({ id: execution.canonicalId, config, http: this.#context.use(httpHostToken) });
23
+ }
24
+ }
@@ -0,0 +1,34 @@
1
+ import { type EndpointManagementRequest } from 'zhin.js/adapter';
2
+ import { EventEmitter } from 'node:events';
3
+ import type { LineFetch } from './endpoint.js';
4
+ import type { ResolvedLineConfig } from './protocol.js';
5
+ export interface LineGroupMember {
6
+ readonly user_id: string;
7
+ readonly nickname: string;
8
+ }
9
+ interface LineGroupMemberIds {
10
+ readonly memberIds?: string[];
11
+ readonly next?: string;
12
+ }
13
+ export interface LineApiClientOptions {
14
+ readonly config: ResolvedLineConfig;
15
+ readonly fetch: LineFetch;
16
+ readonly signal?: AbortSignal;
17
+ }
18
+ /** Direct LINE Messaging API client; it has no Endpoint lifecycle methods. */
19
+ export declare class LineApiClient extends EventEmitter {
20
+ #private;
21
+ readonly apiConfig: ResolvedLineConfig;
22
+ constructor({ config, fetch, signal }: LineApiClientOptions);
23
+ readonly fetch: LineFetch;
24
+ protected transportSignal?: AbortSignal;
25
+ request<T = unknown>(path: string, init?: {
26
+ readonly method?: string;
27
+ readonly body?: string;
28
+ readonly signal?: AbortSignal;
29
+ }): Promise<T>;
30
+ getProfile(userId: string): Promise<unknown>;
31
+ getGroupMemberIds(groupId: string, start?: string): Promise<LineGroupMemberIds>;
32
+ getGroupMembers(groupId: string, request?: EndpointManagementRequest): Promise<LineGroupMember[]>;
33
+ }
34
+ export {};
@@ -0,0 +1,65 @@
1
+ import { EventEmitter } from 'node:events';
2
+ /** Direct LINE Messaging API client; it has no Endpoint lifecycle methods. */
3
+ export class LineApiClient extends EventEmitter {
4
+ apiConfig;
5
+ constructor({ config, fetch, signal }) {
6
+ super();
7
+ this.apiConfig = config;
8
+ this.transportSignal = signal;
9
+ this.fetch = (url, init) => {
10
+ this.transportSignal?.throwIfAborted();
11
+ return fetch(url, { ...init, ...(this.transportSignal ? { signal: init?.signal ? AbortSignal.any([this.transportSignal, init.signal]) : this.transportSignal } : {}) });
12
+ };
13
+ }
14
+ fetch;
15
+ transportSignal;
16
+ async request(path, init = {}) {
17
+ init.signal?.throwIfAborted();
18
+ const response = await this.fetch(`${this.apiConfig.apiBaseUrl}${path}`, {
19
+ method: init.method ?? 'GET',
20
+ headers: {
21
+ Authorization: `Bearer ${this.apiConfig.channelAccessToken}`,
22
+ ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }),
23
+ },
24
+ ...(init.body === undefined ? {} : { body: init.body }),
25
+ signal: init.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000),
26
+ });
27
+ if (!response.ok) {
28
+ const text = await response.text();
29
+ throw new Error(`LINE API error ${response.status}: ${text}`);
30
+ }
31
+ return await response.json();
32
+ }
33
+ getProfile(userId) {
34
+ return this.request(`/v2/profile/${encodeURIComponent(userId)}`);
35
+ }
36
+ getGroupMemberIds(groupId, start) {
37
+ return this.#groupMemberIds({ groupId, start });
38
+ }
39
+ #groupMemberIds({ groupId, start, signal }) {
40
+ const kind = groupId.startsWith('R') ? 'room' : 'group';
41
+ const query = start ? `?start=${encodeURIComponent(start)}` : '';
42
+ return this.request(`/v2/bot/${kind}/${encodeURIComponent(groupId)}/members/ids${query}`, { signal });
43
+ }
44
+ async getGroupMembers(groupId, request = {}) {
45
+ const kind = groupId.startsWith('R') ? 'room' : 'group';
46
+ const ids = [];
47
+ let next;
48
+ do {
49
+ const page = await this.#groupMemberIds({ groupId, start: next, signal: request.signal });
50
+ ids.push(...(page.memberIds ?? []).filter((id) => typeof id === 'string' && id.length > 0));
51
+ next = page.next || undefined;
52
+ } while (next);
53
+ return Promise.all(ids.map(async (userId) => {
54
+ try {
55
+ const profile = await this.request(`/v2/bot/${kind}/${encodeURIComponent(groupId)}/member/${encodeURIComponent(userId)}`, { signal: request.signal });
56
+ return { user_id: userId, nickname: String(profile.displayName ?? userId) };
57
+ }
58
+ catch (error) {
59
+ if (request.signal?.aborted)
60
+ throw error;
61
+ return { user_id: userId, nickname: userId };
62
+ }
63
+ }));
64
+ }
65
+ }
package/lib/client.d.ts CHANGED
@@ -1,33 +1,54 @@
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 {
1
+ import { LineApiClient } from './api-client.js';
2
+ /**
3
+ * LineClient — lifecycle, outbound, admit, OpenAPI helpers for agent tools.
4
+ */
5
+ import { type EndpointManagement, type 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
+ export type LineFetch = (url: string, init?: {
10
+ readonly method?: string;
11
+ readonly headers?: Record<string, string>;
12
+ readonly body?: string;
13
+ readonly signal?: AbortSignal;
14
+ }) => Promise<{
15
+ readonly ok: boolean;
16
+ readonly status: number;
17
+ text(): Promise<string>;
18
+ json(): Promise<unknown>;
19
+ }>;
20
+ export interface LineEndpointOptions {
21
+ readonly id: CapabilityId;
22
+ readonly http: HttpHost;
9
23
  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[]>;
24
+ readonly fetch?: LineFetch;
23
25
  }
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
- }
26
+ export declare class LineClient extends LineApiClient {
27
+ #private;
28
+ protected readonly endpointManagement: EndpointManagement;
29
+ protected configName(): string;
30
+ get transportState(): import('zhin.js/adapter').EndpointTransportState | undefined;
31
+ protected executionSignal?: AbortSignal;
32
+ protected setExecutionSignal(signal: AbortSignal): void;
33
+ /** Native protocol work runs here; Endpoint attaches the framework receipt without replacing SDK APIs. */
34
+ protected receiveInboundCallback<T>(receive: () => T | Promise<T>): Promise<T>;
35
+ protected publishEvent(name: string, payload: unknown): Promise<unknown>;
36
+ protected publishAccepted(name: string, payload: unknown): Promise<void>;
37
+ protected publishPlatform(name: string, event: unknown): Promise<unknown>;
38
+ constructor(options: LineEndpointOptions);
39
+ /** Used by webhook handler. */
40
+ get isOpen(): boolean;
41
+ get config(): ResolvedLineConfig;
42
+ protected connectTransport(signal?: AbortSignal): Promise<void>;
43
+ protected openInput(): void;
44
+ protected closeInput(): void;
45
+ protected disconnectTransport(): Promise<void>;
46
+ protected sendPayload({ conversation, payload, signal }: EndpointSendRequest): Promise<string>;
47
+ /** Test / internal: admit a parsed event when open (non-webhook path). */
48
+ admit(event: LineEvent): void;
49
+ /** Webhook acknowledgement follows actual runtime generation admission. */
50
+ admitAccepted(event: LineEvent): Promise<void>;
51
+ protected inboundReceiptCurrent(): boolean;
32
52
  }
33
- export declare const lineClient: import("@zhin.js/adapter").EndpointClientToken<LineClient, LineClientEventMap>;
53
+ export type LineClientEventMap = Record<string, LineEvent>;
54
+ export type { LineGroupMember } from './api-client.js';