openclaw-openagent 1.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.
Files changed (113) hide show
  1. package/index.ts +114 -0
  2. package/openclaw.plugin.json +159 -0
  3. package/package.json +79 -0
  4. package/skills/clawlink/SKILL.md +145 -0
  5. package/skills/clawlink/SKILL.md.bak +165 -0
  6. package/src/app/channel-tools.ts +249 -0
  7. package/src/app/discovery-tools.ts +273 -0
  8. package/src/app/hooks.ts +60 -0
  9. package/src/app/index.ts +78 -0
  10. package/src/app/messaging-tools.ts +79 -0
  11. package/src/app/ops-tools.ts +155 -0
  12. package/src/app/remote-agent-tool.ts +476 -0
  13. package/src/app/types.ts +67 -0
  14. package/src/app/verbose-preflight.ts +190 -0
  15. package/src/auth/config.ts +197 -0
  16. package/src/auth/credential-manager.ts +146 -0
  17. package/src/auth/index.ts +24 -0
  18. package/src/auth/verify.ts +99 -0
  19. package/src/channel.ts +565 -0
  20. package/src/compat.ts +82 -0
  21. package/src/config/config-schema.ts +39 -0
  22. package/src/messaging/aggregator.ts +120 -0
  23. package/src/messaging/collector.ts +89 -0
  24. package/src/messaging/executor.ts +72 -0
  25. package/src/messaging/inbound.ts +150 -0
  26. package/src/messaging/index.ts +11 -0
  27. package/src/messaging/mention-protocol.ts +94 -0
  28. package/src/messaging/process-c2c-request.ts +564 -0
  29. package/src/messaging/process-message.ts +373 -0
  30. package/src/messaging/scheduler.ts +55 -0
  31. package/src/messaging/types.ts +38 -0
  32. package/src/plugin-ui/assets/agentbook-icon.svg +5 -0
  33. package/src/plugin-ui/assets/magic.svg +5 -0
  34. package/src/plugin-ui/assets/openagent-override.js +9329 -0
  35. package/src/plugin-ui/build.cjs +175 -0
  36. package/src/plugin-ui/index.ts +18 -0
  37. package/src/plugin-ui/modules/agent-book/panel/agent-book.js +458 -0
  38. package/src/plugin-ui/modules/agent-book/panel/agent-card.js +154 -0
  39. package/src/plugin-ui/modules/agent-book/panel/agent-data.js +644 -0
  40. package/src/plugin-ui/modules/agent-book/panel/inject-ui.js +456 -0
  41. package/src/plugin-ui/modules/agent-book/panel/mention-state.js +206 -0
  42. package/src/plugin-ui/modules/agent-book/panel/styles.js +670 -0
  43. package/src/plugin-ui/modules/agent-book/remote-agent-tool/components-core.js +293 -0
  44. package/src/plugin-ui/modules/agent-book/remote-agent-tool/thought-chain-card.js +208 -0
  45. package/src/plugin-ui/modules/agent-book/scanner.js +119 -0
  46. package/src/plugin-ui/modules/agent-book/travelcard/travel-cards.js +500 -0
  47. package/src/plugin-ui/modules/agent-book/travelcard/travel-engine.js +652 -0
  48. package/src/plugin-ui/modules/agent-book/travelcard/travel-styles.js +251 -0
  49. package/src/plugin-ui/modules/loader/bootstrap.js +38 -0
  50. package/src/plugin-ui/modules/loader/shared-state.js +560 -0
  51. package/src/plugin-ui/modules/loader/ws-intercept.js +199 -0
  52. package/src/plugin-ui/modules/remote-agent/chunk-parser.js +161 -0
  53. package/src/plugin-ui/modules/remote-agent/execution-card.js +269 -0
  54. package/src/plugin-ui/modules/remote-agent/markdown-renderer.js +256 -0
  55. package/src/plugin-ui/modules/remote-agent/native-style-adapter.js +146 -0
  56. package/src/plugin-ui/modules/remote-agent/output-card.js +259 -0
  57. package/src/plugin-ui/modules/remote-agent/progress-store.js +363 -0
  58. package/src/plugin-ui/modules/remote-agent/render-hooks.js +1609 -0
  59. package/src/plugin-ui/modules/remote-agent/styles.js +668 -0
  60. package/src/plugin-ui/modules/remote-agent/tool-card-model.js +56 -0
  61. package/src/plugin-ui/ui-extension-loader/backup.ts +92 -0
  62. package/src/plugin-ui/ui-extension-loader/index.ts +276 -0
  63. package/src/plugin-ui/ui-extension-loader/locator.ts +152 -0
  64. package/src/plugin-ui/ui-extension-loader/manifest.ts +57 -0
  65. package/src/plugin-ui/ui-extension-loader/registry-regex.ts +729 -0
  66. package/src/plugin-ui/ui-extension-loader/removed-extensions.ts +70 -0
  67. package/src/plugin-ui/ui-extension-loader/types.ts +68 -0
  68. package/src/proxy/auth-proxy.ts +356 -0
  69. package/src/runtime/account.ts +572 -0
  70. package/src/runtime/index.ts +7 -0
  71. package/src/runtime/plugin-runtime.ts +94 -0
  72. package/src/runtime/registry.ts +71 -0
  73. package/src/sdk/CLASS_MAP.md +143 -0
  74. package/src/sdk/index.d.ts +126 -0
  75. package/src/sdk/index.js +23990 -0
  76. package/src/sdk/modules/cloud-search-module.js +1117 -0
  77. package/src/sdk/modules/follow-module.js +1069 -0
  78. package/src/sdk/modules/group-module.js +7397 -0
  79. package/src/sdk/modules/relationship-module.js +2269 -0
  80. package/src/sdk/modules/signaling-module.js +1468 -0
  81. package/src/sdk/modules/tim-upload-plugin.js +730 -0
  82. package/src/sdk/node-env/http-request.js +90 -0
  83. package/src/sdk/node-env/index.js +57 -0
  84. package/src/sdk/node-env/storage.js +114 -0
  85. package/src/sdk/package.json +10 -0
  86. package/src/sdk/tsconfig.json +16 -0
  87. package/src/state/pending-invocation-store.ts +43 -0
  88. package/src/state/store.ts +676 -0
  89. package/src/tim/c2c.ts +451 -0
  90. package/src/tim/channels.ts +364 -0
  91. package/src/tim/client.ts +330 -0
  92. package/src/tim/index.ts +18 -0
  93. package/src/tim/messages.ts +166 -0
  94. package/src/tim/sdk-logger-init.ts +50 -0
  95. package/src/tools.ts +10 -0
  96. package/src/transport/factory.ts +95 -0
  97. package/src/transport/oasn/index.ts +17 -0
  98. package/src/transport/oasn/oasn-agent-card.ts +111 -0
  99. package/src/transport/oasn/oasn-discovery.ts +108 -0
  100. package/src/transport/oasn/oasn-files.ts +210 -0
  101. package/src/transport/oasn/oasn-http.ts +483 -0
  102. package/src/transport/oasn/oasn-invocation.ts +527 -0
  103. package/src/transport/oasn/oasn-normalize.ts +159 -0
  104. package/src/transport/oasn/oasn-register.ts +106 -0
  105. package/src/transport/oasn/oasn-transport.ts +341 -0
  106. package/src/transport/oasn/oasn-types.ts +353 -0
  107. package/src/transport/tim/index.ts +8 -0
  108. package/src/transport/tim/tim-transport.ts +515 -0
  109. package/src/transport/types.ts +541 -0
  110. package/src/types/openclaw.d.ts +97 -0
  111. package/src/types/tencentcloud-chat.d.ts +15 -0
  112. package/src/util/http.ts +113 -0
  113. package/src/util/logger.ts +131 -0
@@ -0,0 +1,676 @@
1
+ /**
2
+ * State Store — SQLite persistence via sql.js (pure WASM)
3
+ *
4
+ * Persists channel state and message dedup records.
5
+ * sql.js operates in-memory; explicit persist() writes to disk.
6
+ * No native compilation needed (unlike better-sqlite3).
7
+ *
8
+ * v3: All tables use (account_id, channel_id) composite key.
9
+ * See §0.4 of refactoring-plan.md for field semantics.
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import os from 'node:os';
15
+
16
+ import { logger } from '../util/logger.js';
17
+
18
+ const DB_PATH = path.join(os.homedir(), '.openclaw', 'openagent.db');
19
+
20
+ // ── Types ──
21
+
22
+ export interface ChannelState {
23
+ account_id: string;
24
+ channel_id: string;
25
+ channel_name: string;
26
+ joined: number;
27
+ last_visit: number;
28
+ last_reply: number;
29
+ last_msg_seq: number;
30
+ created_at: number;
31
+ updated_at: number;
32
+ }
33
+
34
+ export interface ChannelStateDisplay {
35
+ id: string;
36
+ name: string;
37
+ lastVisit: string;
38
+ lastReply: string;
39
+ lastMsgSeq: number;
40
+ }
41
+
42
+ /**
43
+ * §11.1 OASN invocation 幂等持久化记录。
44
+ *
45
+ * 同一个 tool_call_id 多次重试时必须复用首次生成的 idempotency_key,
46
+ * 否则服务端会创建多个 Invocation(叠加 §11.2 没有 cancel API 的限制,会泄漏调用配额)。
47
+ *
48
+ * 流程:
49
+ * 1. sendTask 前查询 tool_call_id 是否已有未完成记录 → 复用 idempotency_key
50
+ * 2. POST /api/invocations 成功后 → upsert 写入 invocation_id + status
51
+ * 3. 终态 → markTerminal(status);abort → markAbandoned()
52
+ * 4. 进程启动时扫描 status NOT IN (succeeded,failed,timed_out,cancelled,abandoned)
53
+ * → 调 GET /api/invocations/{id} 续轮询
54
+ */
55
+ export interface PendingInvocationRecord {
56
+ /** LLM 工具调用唯一 id(上层传入) */
57
+ tool_call_id: string;
58
+ /** 首次生成的 UUID,重试必须复用 */
59
+ idempotency_key: string;
60
+ /** POST 返回后回填,POST 之前为 null */
61
+ invocation_id: string | null;
62
+ session_id: string | null;
63
+ target_agent_id: string | null;
64
+ /** accepted / queued / running / succeeded / failed / timed_out / cancelled / abandoned */
65
+ status: string;
66
+ created_at: number;
67
+ updated_at: number;
68
+ }
69
+
70
+ interface SqlJsDatabase {
71
+ run(sql: string, params?: unknown[]): void;
72
+ prepare(sql: string): SqlJsStatement;
73
+ export(): Uint8Array;
74
+ close(): void;
75
+ }
76
+
77
+ interface SqlJsStatement {
78
+ bind(params?: unknown[]): boolean;
79
+ step(): boolean;
80
+ getAsObject(): Record<string, unknown>;
81
+ free(): void;
82
+ }
83
+
84
+ // ── StateStore ──
85
+
86
+ export class StateStore {
87
+ private db: SqlJsDatabase | null = null;
88
+ private accountId: string = 'default';
89
+ private _seenCount = 0;
90
+
91
+ /**
92
+ * Initialize the SQLite database.
93
+ * Must be called before any other methods.
94
+ *
95
+ * @param currentAccountId - The account ID of the currently starting account.
96
+ * Used for schema migration: old data without account_id will be assigned this ID.
97
+ */
98
+ async init(currentAccountId: string): Promise<StateStore> {
99
+ this.accountId = currentAccountId || 'default';
100
+
101
+ const initSqlJs = ((await import('sql.js')) as { default: (config?: unknown) => Promise<{ Database: new (data?: ArrayLike<number>) => SqlJsDatabase }> }).default;
102
+ const SQL = await initSqlJs();
103
+
104
+ // Load existing DB file if present
105
+ if (fs.existsSync(DB_PATH)) {
106
+ const buffer = fs.readFileSync(DB_PATH);
107
+ this.db = new SQL.Database(buffer);
108
+ } else {
109
+ this.db = new SQL.Database();
110
+ }
111
+
112
+ this._migrate();
113
+ return this;
114
+ }
115
+
116
+ private _migrate(): void {
117
+ if (!this.db) return;
118
+
119
+ // Detect old schema (no account_id column)
120
+ const hasAccountId = this._tableHasColumn('channel_state', 'account_id');
121
+
122
+ if (hasAccountId) {
123
+ // Already v3 schema — ensure all tables exist
124
+ this._createV3Tables();
125
+ } else {
126
+ // Old v2 schema detected — migrate
127
+ this._migrateFromV2();
128
+ }
129
+ }
130
+
131
+ private _tableHasColumn(table: string, column: string): boolean {
132
+ if (!this.db) return false;
133
+ try {
134
+ const stmt = this.db.prepare(`PRAGMA table_info(${table})`);
135
+ while (stmt.step()) {
136
+ const row = stmt.getAsObject();
137
+ if (row['name'] === column) {
138
+ stmt.free();
139
+ return true;
140
+ }
141
+ }
142
+ stmt.free();
143
+ } catch {
144
+ // Table doesn't exist
145
+ }
146
+ return false;
147
+ }
148
+
149
+ private _tableExists(table: string): boolean {
150
+ if (!this.db) return false;
151
+ try {
152
+ const stmt = this.db.prepare(
153
+ `SELECT name FROM sqlite_master WHERE type='table' AND name=?`
154
+ );
155
+ stmt.bind([table]);
156
+ const exists = stmt.step();
157
+ stmt.free();
158
+ return exists;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ private _migrateFromV2(): void {
165
+ if (!this.db) return;
166
+ logger.info(`[state] Migrating v2 schema to v3 (account_id='${this.accountId}')`);
167
+
168
+ // 1. Rename old tables
169
+ if (this._tableExists('channel_state')) {
170
+ this.db.run('ALTER TABLE channel_state RENAME TO _v2_channel_state');
171
+ }
172
+ if (this._tableExists('seen_messages')) {
173
+ this.db.run('ALTER TABLE seen_messages RENAME TO _v2_seen_messages');
174
+ }
175
+ if (this._tableExists('channel_skills')) {
176
+ this.db.run('ALTER TABLE channel_skills RENAME TO _v2_channel_skills');
177
+ }
178
+ if (this._tableExists('channel_purpose')) {
179
+ this.db.run('ALTER TABLE channel_purpose RENAME TO _v2_channel_purpose');
180
+ }
181
+
182
+ // 2. Create v3 tables
183
+ this._createV3Tables();
184
+
185
+ // 3. Copy old data with current account_id
186
+ if (this._tableExists('_v2_channel_state')) {
187
+ this.db.run(`
188
+ INSERT INTO channel_state (account_id, channel_id, channel_name, joined, last_visit, last_reply, last_msg_seq, created_at, updated_at)
189
+ SELECT ?, channel_id, channel_name, joined, last_visit, last_reply, last_msg_seq, created_at, updated_at
190
+ FROM _v2_channel_state
191
+ `, [this.accountId]);
192
+ }
193
+ if (this._tableExists('_v2_seen_messages')) {
194
+ this.db.run(`
195
+ INSERT INTO seen_messages (account_id, message_id, channel_id, seen_at)
196
+ SELECT ?, message_id, channel_id, seen_at
197
+ FROM _v2_seen_messages
198
+ `, [this.accountId]);
199
+ }
200
+ if (this._tableExists('_v2_channel_skills')) {
201
+ this.db.run(`
202
+ INSERT INTO channel_skills (account_id, channel_id, skill_content, updated_at)
203
+ SELECT ?, channel_id, skill_content, updated_at
204
+ FROM _v2_channel_skills
205
+ `, [this.accountId]);
206
+ }
207
+ if (this._tableExists('_v2_channel_purpose')) {
208
+ this.db.run(`
209
+ INSERT INTO channel_purpose (account_id, channel_id, purpose, updated_at)
210
+ SELECT ?, channel_id, purpose, updated_at
211
+ FROM _v2_channel_purpose
212
+ `, [this.accountId]);
213
+ }
214
+
215
+ // 4. Drop old tables
216
+ this.db.run('DROP TABLE IF EXISTS _v2_channel_state');
217
+ this.db.run('DROP TABLE IF EXISTS _v2_seen_messages');
218
+ this.db.run('DROP TABLE IF EXISTS _v2_channel_skills');
219
+ this.db.run('DROP TABLE IF EXISTS _v2_channel_purpose');
220
+
221
+ this.persist();
222
+ logger.info('[state] Migration complete');
223
+ }
224
+
225
+ private _createV3Tables(): void {
226
+ if (!this.db) return;
227
+
228
+ this.db.run(`
229
+ CREATE TABLE IF NOT EXISTS channel_state (
230
+ account_id TEXT NOT NULL,
231
+ channel_id TEXT NOT NULL,
232
+ channel_name TEXT NOT NULL DEFAULT '',
233
+ joined INTEGER NOT NULL DEFAULT 0,
234
+ last_visit INTEGER NOT NULL DEFAULT 0,
235
+ last_reply INTEGER NOT NULL DEFAULT 0,
236
+ last_msg_seq INTEGER NOT NULL DEFAULT 0,
237
+ created_at INTEGER NOT NULL DEFAULT 0,
238
+ updated_at INTEGER NOT NULL DEFAULT 0,
239
+ PRIMARY KEY (account_id, channel_id)
240
+ )
241
+ `);
242
+ this.db.run(`
243
+ CREATE TABLE IF NOT EXISTS seen_messages (
244
+ account_id TEXT NOT NULL,
245
+ message_id TEXT NOT NULL,
246
+ channel_id TEXT NOT NULL,
247
+ seen_at INTEGER NOT NULL DEFAULT 0,
248
+ PRIMARY KEY (account_id, message_id)
249
+ )
250
+ `);
251
+ this.db.run(`
252
+ CREATE TABLE IF NOT EXISTS channel_skills (
253
+ account_id TEXT NOT NULL,
254
+ channel_id TEXT NOT NULL,
255
+ skill_content TEXT NOT NULL DEFAULT '',
256
+ updated_at INTEGER NOT NULL DEFAULT 0,
257
+ PRIMARY KEY (account_id, channel_id)
258
+ )
259
+ `);
260
+ this.db.run(`
261
+ CREATE TABLE IF NOT EXISTS channel_purpose (
262
+ account_id TEXT NOT NULL,
263
+ channel_id TEXT NOT NULL,
264
+ purpose TEXT NOT NULL DEFAULT '',
265
+ updated_at INTEGER NOT NULL DEFAULT 0,
266
+ PRIMARY KEY (account_id, channel_id)
267
+ )
268
+ `);
269
+ // §11.1 OASN invocation 幂等持久化。
270
+ // tool_call_id 作为主键 —— 它对应 LLM 一次工具调用,全局唯一。
271
+ // status 索引便于启动时筛非终态记录续轮询。
272
+ this.db.run(`
273
+ CREATE TABLE IF NOT EXISTS pending_invocations (
274
+ account_id TEXT NOT NULL,
275
+ tool_call_id TEXT NOT NULL,
276
+ idempotency_key TEXT NOT NULL,
277
+ invocation_id TEXT,
278
+ session_id TEXT,
279
+ target_agent_id TEXT,
280
+ status TEXT NOT NULL DEFAULT 'pending',
281
+ created_at INTEGER NOT NULL DEFAULT 0,
282
+ updated_at INTEGER NOT NULL DEFAULT 0,
283
+ PRIMARY KEY (account_id, tool_call_id)
284
+ )
285
+ `);
286
+ this.db.run(`
287
+ CREATE INDEX IF NOT EXISTS idx_pending_invocations_status
288
+ ON pending_invocations (account_id, status)
289
+ `);
290
+ this.db.run(`
291
+ CREATE INDEX IF NOT EXISTS idx_pending_invocations_invocation
292
+ ON pending_invocations (account_id, invocation_id)
293
+ `);
294
+ }
295
+
296
+ // ── Write to disk ──
297
+
298
+ persist(): void {
299
+ try {
300
+ if (!this.db) return;
301
+ const data = this.db.export();
302
+ fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
303
+ fs.writeFileSync(DB_PATH, Buffer.from(data));
304
+ } catch (err) {
305
+ logger.error(`[state] persist error: ${(err as Error).message}`);
306
+ }
307
+ }
308
+
309
+ // ── Channel State ──
310
+
311
+ /**
312
+ * Get all joined channels for the current account.
313
+ */
314
+ getJoinedChannels(): ChannelState[] {
315
+ if (!this.db) return [];
316
+ const stmt = this.db.prepare(
317
+ 'SELECT * FROM channel_state WHERE account_id = ? AND joined = 1'
318
+ );
319
+ stmt.bind([this.accountId]);
320
+ const results: ChannelState[] = [];
321
+ while (stmt.step()) results.push(stmt.getAsObject() as unknown as ChannelState);
322
+ stmt.free();
323
+ return results;
324
+ }
325
+
326
+ getJoinedChannelIds(): string[] {
327
+ return this.getJoinedChannels().map(c => c.channel_id);
328
+ }
329
+
330
+ getChannel(channelId: string): ChannelState | null {
331
+ if (!this.db) return null;
332
+ const stmt = this.db.prepare(
333
+ 'SELECT * FROM channel_state WHERE account_id = ? AND channel_id = ?'
334
+ );
335
+ stmt.bind([this.accountId, channelId]);
336
+ const result = stmt.step() ? (stmt.getAsObject() as unknown as ChannelState) : null;
337
+ stmt.free();
338
+ return result;
339
+ }
340
+
341
+ /**
342
+ * Mark a channel as joined.
343
+ * Authoritative writer: openagent_join_channel tool (on success).
344
+ */
345
+ markJoined(channelId: string, channelName: string): void {
346
+ if (!this.db) return;
347
+ const now = Date.now();
348
+ this.db.run(
349
+ `INSERT INTO channel_state (account_id, channel_id, channel_name, joined, last_visit, created_at, updated_at)
350
+ VALUES (?, ?, ?, 1, ?, ?, ?)
351
+ ON CONFLICT(account_id, channel_id) DO UPDATE SET joined=1, channel_name=?, updated_at=?`,
352
+ [this.accountId, channelId, channelName || '', now, now, now, channelName || '', now]
353
+ );
354
+ this.persist();
355
+ }
356
+
357
+ /**
358
+ * Mark a channel as left.
359
+ * Authoritative writer: openagent_leave_channel tool (on success).
360
+ */
361
+ markLeft(channelId: string): void {
362
+ if (!this.db) return;
363
+ this.db.run(
364
+ 'UPDATE channel_state SET joined=0, updated_at=? WHERE account_id=? AND channel_id=?',
365
+ [Date.now(), this.accountId, channelId]
366
+ );
367
+ this.persist();
368
+ }
369
+
370
+ /**
371
+ * Update last_visit timestamp for a channel.
372
+ * Authoritative writer: Collector — on ingest() accepting a message.
373
+ */
374
+ updateLastVisit(channelId: string): void {
375
+ if (!this.db) return;
376
+ const now = Date.now();
377
+ this.db.run(
378
+ 'UPDATE channel_state SET last_visit=?, updated_at=? WHERE account_id=? AND channel_id=?',
379
+ [now, now, this.accountId, channelId]
380
+ );
381
+ this.persist();
382
+ }
383
+
384
+ /**
385
+ * Update last_reply timestamp for a channel.
386
+ * Authoritative writer: openagent_send_message tool — on sendMessage() success.
387
+ */
388
+ updateLastReply(channelId: string): void {
389
+ if (!this.db) return;
390
+ const now = Date.now();
391
+ this.db.run(
392
+ 'UPDATE channel_state SET last_reply=?, updated_at=? WHERE account_id=? AND channel_id=?',
393
+ [now, now, this.accountId, channelId]
394
+ );
395
+ this.persist();
396
+ }
397
+
398
+ /**
399
+ * Update last_msg_seq for a channel.
400
+ * Authoritative writer: Collector — on ingest() taking msg.sequence.
401
+ */
402
+ updateLastMsgSeq(channelId: string, seq: number): void {
403
+ if (!this.db) return;
404
+ this.db.run(
405
+ 'UPDATE channel_state SET last_msg_seq=?, updated_at=? WHERE account_id=? AND channel_id=?',
406
+ [seq, Date.now(), this.accountId, channelId]
407
+ );
408
+ this.persist();
409
+ }
410
+
411
+ // ── Message Dedup (Collector use) ──
412
+
413
+ hasSeen(messageId: string): boolean {
414
+ if (!this.db) return false;
415
+ const stmt = this.db.prepare(
416
+ 'SELECT 1 FROM seen_messages WHERE account_id=? AND message_id=?'
417
+ );
418
+ stmt.bind([this.accountId, messageId]);
419
+ const found = stmt.step();
420
+ stmt.free();
421
+ return found;
422
+ }
423
+
424
+ markSeen(messageId: string, channelId: string): void {
425
+ if (!this.db) return;
426
+ this.db.run(
427
+ 'INSERT OR IGNORE INTO seen_messages (account_id, message_id, channel_id, seen_at) VALUES (?, ?, ?, ?)',
428
+ [this.accountId, messageId, channelId, Date.now()]
429
+ );
430
+ // Batch persist: seen_messages are written frequently
431
+ this._seenCount += 1;
432
+ if (this._seenCount % 100 === 0) this.persist();
433
+ }
434
+
435
+ // ── Channel Skills ──
436
+
437
+ getSkill(channelId: string): string | null {
438
+ if (!this.db) return null;
439
+ const stmt = this.db.prepare(
440
+ 'SELECT skill_content FROM channel_skills WHERE account_id = ? AND channel_id = ?'
441
+ );
442
+ stmt.bind([this.accountId, channelId]);
443
+ const result = stmt.step() ? stmt.getAsObject() : null;
444
+ stmt.free();
445
+ return (result?.['skill_content'] as string) || null;
446
+ }
447
+
448
+ setSkill(channelId: string, skillContent: string): void {
449
+ if (!this.db) return;
450
+ const now = Date.now();
451
+ this.db.run(
452
+ `INSERT INTO channel_skills (account_id, channel_id, skill_content, updated_at)
453
+ VALUES (?, ?, ?, ?)
454
+ ON CONFLICT(account_id, channel_id) DO UPDATE SET skill_content=?, updated_at=?`,
455
+ [this.accountId, channelId, skillContent, now, skillContent, now]
456
+ );
457
+ this.persist();
458
+ }
459
+
460
+ getAllSkills(): Array<{ channel_id: string; skill_content: string }> {
461
+ if (!this.db) return [];
462
+ const stmt = this.db.prepare(
463
+ 'SELECT channel_id, skill_content FROM channel_skills WHERE account_id = ?'
464
+ );
465
+ stmt.bind([this.accountId]);
466
+ const results: Array<{ channel_id: string; skill_content: string }> = [];
467
+ while (stmt.step()) {
468
+ const row = stmt.getAsObject();
469
+ results.push({
470
+ channel_id: row['channel_id'] as string,
471
+ skill_content: row['skill_content'] as string,
472
+ });
473
+ }
474
+ stmt.free();
475
+ return results;
476
+ }
477
+
478
+ // ── Channel Purpose ──
479
+
480
+ getPurpose(channelId: string): string | null {
481
+ if (!this.db) return null;
482
+ const stmt = this.db.prepare(
483
+ 'SELECT purpose FROM channel_purpose WHERE account_id = ? AND channel_id = ?'
484
+ );
485
+ stmt.bind([this.accountId, channelId]);
486
+ const result = stmt.step() ? stmt.getAsObject() : null;
487
+ stmt.free();
488
+ return (result?.['purpose'] as string) || null;
489
+ }
490
+
491
+ setPurpose(channelId: string, purpose: string): void {
492
+ if (!this.db) return;
493
+ const now = Date.now();
494
+ this.db.run(
495
+ `INSERT INTO channel_purpose (account_id, channel_id, purpose, updated_at)
496
+ VALUES (?, ?, ?, ?)
497
+ ON CONFLICT(account_id, channel_id) DO UPDATE SET purpose=?, updated_at=?`,
498
+ [this.accountId, channelId, purpose, now, purpose, now]
499
+ );
500
+ this.persist();
501
+ }
502
+
503
+ removePurpose(channelId: string): void {
504
+ if (!this.db) return;
505
+ this.db.run(
506
+ 'DELETE FROM channel_purpose WHERE account_id = ? AND channel_id = ?',
507
+ [this.accountId, channelId]
508
+ );
509
+ this.persist();
510
+ }
511
+
512
+ /**
513
+ * Clean up old dedup records (older than 24h)
514
+ */
515
+ cleanupSeen(): void {
516
+ if (!this.db) return;
517
+ const cutoff = Date.now() - 86_400_000;
518
+ this.db.run(
519
+ 'DELETE FROM seen_messages WHERE account_id = ? AND seen_at < ?',
520
+ [this.accountId, cutoff]
521
+ );
522
+ this.persist();
523
+ }
524
+
525
+ /**
526
+ * Close the database connection
527
+ */
528
+ close(): void {
529
+ if (this.db) {
530
+ this.persist(); // Final persist
531
+ this.db.close();
532
+ this.db = null;
533
+ }
534
+ }
535
+
536
+ // ═════════════════════════════════════════════════════════════════
537
+ // §11.1 OASN pending_invocations CRUD(OasnInvocation.PendingInvocationStore 适配)
538
+ //
539
+ // 设计依据:docs/specs/2026-06-16-oasn-transport-abstraction-design.md §11.1
540
+ //
541
+ // 表内字段 account_id 用 this.accountId 自动注入,调用方无需关心多账号隔离。
542
+ // ═════════════════════════════════════════════════════════════════
543
+
544
+ /**
545
+ * 查 tool_call_id 是否有未完成记录。命中 → 复用其 idempotency_key 防止重复创建 Invocation。
546
+ *
547
+ * 仅当 status 为非终态(pending/accepted/queued/running)时返回,避免幂等键被复用到新调用上。
548
+ */
549
+ getPendingInvocation(toolCallId: string): { idempotency_key: string; invocation_id?: string } | null {
550
+ if (!this.db) return null;
551
+ const stmt = this.db.prepare(
552
+ `SELECT idempotency_key, invocation_id, status
553
+ FROM pending_invocations
554
+ WHERE account_id = ? AND tool_call_id = ?`,
555
+ );
556
+ stmt.bind([this.accountId, toolCallId]);
557
+ let row: Record<string, unknown> | null = null;
558
+ if (stmt.step()) row = stmt.getAsObject();
559
+ stmt.free();
560
+ if (!row) return null;
561
+ const status = String(row['status']);
562
+ if (this._isTerminalStatus(status)) return null;
563
+ const result: { idempotency_key: string; invocation_id?: string } = {
564
+ idempotency_key: String(row['idempotency_key']),
565
+ };
566
+ const invId = row['invocation_id'];
567
+ if (typeof invId === 'string' && invId.length > 0) result.invocation_id = invId;
568
+ return result;
569
+ }
570
+
571
+ /**
572
+ * 插入或更新一条 pending 记录。
573
+ *
574
+ * 调用时机:
575
+ * - sendTask 之前(尚无 invocation_id,status='pending')
576
+ * - POST /api/invocations 返回后(回填 invocation_id + status)
577
+ */
578
+ upsertPendingInvocation(record: {
579
+ tool_call_id: string;
580
+ idempotency_key: string;
581
+ invocation_id?: string;
582
+ session_id?: string;
583
+ target_agent_id?: string;
584
+ status: string;
585
+ }): void {
586
+ if (!this.db) return;
587
+ const now = Date.now();
588
+ this.db.run(
589
+ `INSERT INTO pending_invocations
590
+ (account_id, tool_call_id, idempotency_key, invocation_id, session_id, target_agent_id, status, created_at, updated_at)
591
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
592
+ ON CONFLICT(account_id, tool_call_id) DO UPDATE SET
593
+ invocation_id = COALESCE(excluded.invocation_id, pending_invocations.invocation_id),
594
+ session_id = COALESCE(excluded.session_id, pending_invocations.session_id),
595
+ target_agent_id = COALESCE(excluded.target_agent_id, pending_invocations.target_agent_id),
596
+ status = excluded.status,
597
+ updated_at = excluded.updated_at`,
598
+ [
599
+ this.accountId,
600
+ record.tool_call_id,
601
+ record.idempotency_key,
602
+ record.invocation_id ?? null,
603
+ record.session_id ?? null,
604
+ record.target_agent_id ?? null,
605
+ record.status,
606
+ now,
607
+ now,
608
+ ],
609
+ );
610
+ this.persist();
611
+ }
612
+
613
+ /**
614
+ * 终态标记。透过 invocation_id 查找(OasnInvocation 在终态回调时只持有 invocation_id)。
615
+ */
616
+ markPendingInvocationTerminal(invocationId: string, status: string): void {
617
+ if (!this.db) return;
618
+ this.db.run(
619
+ `UPDATE pending_invocations
620
+ SET status = ?, updated_at = ?
621
+ WHERE account_id = ? AND invocation_id = ?`,
622
+ [status, Date.now(), this.accountId, invocationId],
623
+ );
624
+ this.persist();
625
+ }
626
+
627
+ /**
628
+ * §11.2 abort 标记。
629
+ *
630
+ * 服务端没有 cancel API,本地只能记录"已放弃跟踪",便于排查 / 配额对账。
631
+ */
632
+ markPendingInvocationAbandoned(invocationId: string): void {
633
+ this.markPendingInvocationTerminal(invocationId, 'abandoned');
634
+ }
635
+
636
+ /**
637
+ * 列出非终态记录(启动时续轮询用)。
638
+ *
639
+ * 返回顺序:按 created_at 升序,先创建的先续。
640
+ */
641
+ listUnsettledInvocations(): PendingInvocationRecord[] {
642
+ if (!this.db) return [];
643
+ const stmt = this.db.prepare(
644
+ `SELECT tool_call_id, idempotency_key, invocation_id, session_id, target_agent_id, status, created_at, updated_at
645
+ FROM pending_invocations
646
+ WHERE account_id = ?
647
+ AND status NOT IN ('succeeded','failed','timed_out','cancelled','abandoned')
648
+ ORDER BY created_at ASC`,
649
+ );
650
+ stmt.bind([this.accountId]);
651
+ const results: PendingInvocationRecord[] = [];
652
+ while (stmt.step()) {
653
+ const row = stmt.getAsObject();
654
+ results.push({
655
+ tool_call_id: row['tool_call_id'] as string,
656
+ idempotency_key: row['idempotency_key'] as string,
657
+ invocation_id: (row['invocation_id'] as string | null) ?? null,
658
+ session_id: (row['session_id'] as string | null) ?? null,
659
+ target_agent_id: (row['target_agent_id'] as string | null) ?? null,
660
+ status: row['status'] as string,
661
+ created_at: Number(row['created_at']),
662
+ updated_at: Number(row['updated_at']),
663
+ });
664
+ }
665
+ stmt.free();
666
+ return results;
667
+ }
668
+
669
+ private _isTerminalStatus(status: string): boolean {
670
+ return status === 'succeeded'
671
+ || status === 'failed'
672
+ || status === 'timed_out'
673
+ || status === 'cancelled'
674
+ || status === 'abandoned';
675
+ }
676
+ }