openclaw-openagent 1.0.0 → 1.0.2

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 (187) hide show
  1. package/dist/index.d.ts +25 -0
  2. package/dist/index.js +105 -0
  3. package/dist/src/app/channel-tools.d.ts +28 -0
  4. package/dist/src/app/channel-tools.js +251 -0
  5. package/dist/src/app/discovery-tools.d.ts +35 -0
  6. package/dist/src/app/discovery-tools.js +243 -0
  7. package/dist/src/app/download-file-tool.d.ts +10 -0
  8. package/dist/src/app/download-file-tool.js +104 -0
  9. package/dist/src/app/hooks.d.ts +14 -0
  10. package/dist/src/app/hooks.js +118 -0
  11. package/dist/src/app/index.d.ts +13 -0
  12. package/dist/src/app/index.js +44 -0
  13. package/dist/src/app/messaging-tools.d.ts +11 -0
  14. package/dist/src/app/messaging-tools.js +79 -0
  15. package/dist/src/app/ops-tools.d.ts +21 -0
  16. package/dist/src/app/ops-tools.js +158 -0
  17. package/dist/src/app/remote-agent-tool.d.ts +27 -0
  18. package/dist/src/app/remote-agent-tool.js +461 -0
  19. package/dist/src/app/types.d.ts +61 -0
  20. package/dist/src/app/types.js +11 -0
  21. package/dist/src/app/upload-file-tool.d.ts +16 -0
  22. package/dist/src/app/upload-file-tool.js +353 -0
  23. package/dist/src/app/verbose-preflight.d.ts +2 -0
  24. package/dist/src/app/verbose-preflight.js +145 -0
  25. package/dist/src/auth/config.d.ts +79 -0
  26. package/dist/src/auth/config.js +133 -0
  27. package/dist/src/auth/credential-manager.d.ts +65 -0
  28. package/dist/src/auth/credential-manager.js +122 -0
  29. package/dist/src/auth/index.d.ts +6 -0
  30. package/dist/src/auth/index.js +6 -0
  31. package/dist/src/auth/verify.d.ts +42 -0
  32. package/dist/src/auth/verify.js +60 -0
  33. package/dist/src/channel.d.ts +269 -0
  34. package/dist/src/channel.js +488 -0
  35. package/dist/src/compat.d.ts +37 -0
  36. package/dist/src/compat.js +70 -0
  37. package/dist/src/config/config-schema.d.ts +56 -0
  38. package/dist/src/config/config-schema.js +34 -0
  39. package/dist/src/messaging/aggregator.d.ts +25 -0
  40. package/dist/src/messaging/aggregator.js +90 -0
  41. package/dist/src/messaging/collector.d.ts +27 -0
  42. package/dist/src/messaging/collector.js +76 -0
  43. package/dist/src/messaging/executor.d.ts +14 -0
  44. package/dist/src/messaging/executor.js +59 -0
  45. package/dist/src/messaging/inbound.d.ts +97 -0
  46. package/dist/src/messaging/inbound.js +63 -0
  47. package/dist/src/messaging/index.d.ts +10 -0
  48. package/dist/src/messaging/index.js +9 -0
  49. package/dist/src/messaging/mention-protocol.d.ts +42 -0
  50. package/dist/src/messaging/mention-protocol.js +74 -0
  51. package/dist/src/messaging/process-c2c-request.d.ts +55 -0
  52. package/dist/src/messaging/process-c2c-request.js +445 -0
  53. package/dist/src/messaging/process-message.d.ts +62 -0
  54. package/dist/src/messaging/process-message.js +282 -0
  55. package/dist/src/messaging/scheduler.d.ts +17 -0
  56. package/dist/src/messaging/scheduler.js +47 -0
  57. package/dist/src/messaging/types.d.ts +34 -0
  58. package/dist/src/messaging/types.js +4 -0
  59. package/dist/src/plugin-ui/assets/openagent-override.js +9267 -0
  60. package/dist/src/plugin-ui/index.d.ts +13 -0
  61. package/dist/src/plugin-ui/index.js +16 -0
  62. package/dist/src/plugin-ui/ui-extension-loader/backup.d.ts +23 -0
  63. package/dist/src/plugin-ui/ui-extension-loader/backup.js +82 -0
  64. package/dist/src/plugin-ui/ui-extension-loader/index.d.ts +28 -0
  65. package/dist/src/plugin-ui/ui-extension-loader/index.js +240 -0
  66. package/dist/src/plugin-ui/ui-extension-loader/locator.d.ts +35 -0
  67. package/dist/src/plugin-ui/ui-extension-loader/locator.js +129 -0
  68. package/dist/src/plugin-ui/ui-extension-loader/manifest.d.ts +26 -0
  69. package/dist/src/plugin-ui/ui-extension-loader/manifest.js +45 -0
  70. package/dist/src/plugin-ui/ui-extension-loader/registry-regex.d.ts +9 -0
  71. package/dist/src/plugin-ui/ui-extension-loader/registry-regex.js +701 -0
  72. package/dist/src/plugin-ui/ui-extension-loader/removed-extensions.d.ts +8 -0
  73. package/dist/src/plugin-ui/ui-extension-loader/removed-extensions.js +58 -0
  74. package/dist/src/plugin-ui/ui-extension-loader/types.d.ts +55 -0
  75. package/dist/src/plugin-ui/ui-extension-loader/types.js +23 -0
  76. package/dist/src/proxy/auth-proxy.d.ts +20 -0
  77. package/dist/src/proxy/auth-proxy.js +337 -0
  78. package/dist/src/runtime/account.d.ts +156 -0
  79. package/dist/src/runtime/account.js +491 -0
  80. package/dist/src/runtime/index.d.ts +5 -0
  81. package/dist/src/runtime/index.js +6 -0
  82. package/dist/src/runtime/plugin-runtime.d.ts +40 -0
  83. package/dist/src/runtime/plugin-runtime.js +72 -0
  84. package/dist/src/runtime/registry.d.ts +41 -0
  85. package/dist/src/runtime/registry.js +60 -0
  86. package/dist/src/sdk/CLASS_MAP.md +143 -0
  87. package/dist/src/sdk/index.d.ts +126 -0
  88. package/dist/src/sdk/index.js +23990 -0
  89. package/dist/src/sdk/modules/cloud-search-module.js +1117 -0
  90. package/dist/src/sdk/modules/follow-module.js +1069 -0
  91. package/dist/src/sdk/modules/group-module.js +7397 -0
  92. package/dist/src/sdk/modules/relationship-module.js +2269 -0
  93. package/dist/src/sdk/modules/signaling-module.js +1468 -0
  94. package/dist/src/sdk/modules/tim-upload-plugin.js +730 -0
  95. package/dist/src/sdk/node-env/http-request.js +90 -0
  96. package/dist/src/sdk/node-env/index.js +57 -0
  97. package/dist/src/sdk/node-env/storage.js +114 -0
  98. package/dist/src/sdk/package.json +10 -0
  99. package/dist/src/sdk/sdk/CLASS_MAP.md +143 -0
  100. package/dist/src/sdk/sdk/index.d.ts +126 -0
  101. package/dist/src/sdk/sdk/index.js +23990 -0
  102. package/dist/src/sdk/sdk/modules/cloud-search-module.js +1117 -0
  103. package/dist/src/sdk/sdk/modules/follow-module.js +1069 -0
  104. package/dist/src/sdk/sdk/modules/group-module.js +7397 -0
  105. package/dist/src/sdk/sdk/modules/relationship-module.js +2269 -0
  106. package/dist/src/sdk/sdk/modules/signaling-module.js +1468 -0
  107. package/dist/src/sdk/sdk/modules/tim-upload-plugin.js +730 -0
  108. package/dist/src/sdk/sdk/node-env/http-request.js +90 -0
  109. package/dist/src/sdk/sdk/node-env/index.js +57 -0
  110. package/dist/src/sdk/sdk/node-env/storage.js +114 -0
  111. package/dist/src/sdk/sdk/package.json +10 -0
  112. package/dist/src/sdk/sdk/tsconfig.json +16 -0
  113. package/dist/src/sdk/tsconfig.json +16 -0
  114. package/dist/src/state/pending-invocation-store.d.ts +26 -0
  115. package/dist/src/state/pending-invocation-store.js +39 -0
  116. package/dist/src/state/store.d.ts +165 -0
  117. package/dist/src/state/store.js +535 -0
  118. package/dist/src/tim/c2c.d.ts +83 -0
  119. package/dist/src/tim/c2c.js +318 -0
  120. package/dist/src/tim/channels.d.ts +95 -0
  121. package/dist/src/tim/channels.js +279 -0
  122. package/dist/src/tim/client.d.ts +54 -0
  123. package/dist/src/tim/client.js +268 -0
  124. package/dist/src/tim/index.d.ts +6 -0
  125. package/dist/src/tim/index.js +6 -0
  126. package/dist/src/tim/messages.d.ts +50 -0
  127. package/dist/src/tim/messages.js +104 -0
  128. package/dist/src/tim/sdk-logger-init.d.ts +13 -0
  129. package/dist/src/tim/sdk-logger-init.js +46 -0
  130. package/dist/src/tools.d.ts +9 -0
  131. package/dist/src/tools.js +8 -0
  132. package/dist/src/transport/factory.d.ts +63 -0
  133. package/dist/src/transport/factory.js +54 -0
  134. package/dist/src/transport/oasn/index.d.ts +12 -0
  135. package/dist/src/transport/oasn/index.js +9 -0
  136. package/dist/src/transport/oasn/oasn-agent-card.d.ts +38 -0
  137. package/dist/src/transport/oasn/oasn-agent-card.js +102 -0
  138. package/dist/src/transport/oasn/oasn-discovery.d.ts +33 -0
  139. package/dist/src/transport/oasn/oasn-discovery.js +97 -0
  140. package/dist/src/transport/oasn/oasn-files.d.ts +64 -0
  141. package/dist/src/transport/oasn/oasn-files.js +174 -0
  142. package/dist/src/transport/oasn/oasn-http.d.ts +98 -0
  143. package/dist/src/transport/oasn/oasn-http.js +362 -0
  144. package/dist/src/transport/oasn/oasn-invocation.d.ts +154 -0
  145. package/dist/src/transport/oasn/oasn-invocation.js +432 -0
  146. package/dist/src/transport/oasn/oasn-normalize.d.ts +6 -0
  147. package/dist/src/transport/oasn/oasn-normalize.js +112 -0
  148. package/dist/src/transport/oasn/oasn-register.d.ts +19 -0
  149. package/dist/src/transport/oasn/oasn-register.js +24 -0
  150. package/dist/src/transport/oasn/oasn-transport.d.ts +114 -0
  151. package/dist/src/transport/oasn/oasn-transport.js +230 -0
  152. package/dist/src/transport/oasn/oasn-types.d.ts +331 -0
  153. package/dist/src/transport/oasn/oasn-types.js +44 -0
  154. package/dist/src/transport/tim/index.d.ts +7 -0
  155. package/dist/src/transport/tim/index.js +6 -0
  156. package/dist/src/transport/tim/tim-transport.d.ts +122 -0
  157. package/dist/src/transport/tim/tim-transport.js +402 -0
  158. package/dist/src/transport/types.d.ts +450 -0
  159. package/dist/src/transport/types.js +38 -0
  160. package/dist/src/util/http.d.ts +21 -0
  161. package/dist/src/util/http.js +93 -0
  162. package/dist/src/util/logger.d.ts +20 -0
  163. package/dist/src/util/logger.js +100 -0
  164. package/dist/src/util/url-resolver.d.ts +7 -0
  165. package/dist/src/util/url-resolver.js +20 -0
  166. package/index.ts +11 -0
  167. package/openclaw.plugin.json +9 -0
  168. package/package.json +7 -4
  169. package/src/app/download-file-tool.ts +133 -0
  170. package/src/app/hooks.ts +89 -5
  171. package/src/app/index.ts +6 -0
  172. package/src/app/remote-agent-tool.ts +46 -0
  173. package/src/app/types.ts +1 -0
  174. package/src/app/upload-file-tool.ts +411 -0
  175. package/src/plugin-ui/assets/openagent-override.js +1 -63
  176. package/src/plugin-ui/modules/agent-book/panel/agent-book.js +0 -61
  177. package/src/plugin-ui/modules/agent-book/panel/agent-data.js +0 -1
  178. package/src/plugin-ui/ui-extension-loader/registry-regex.ts +30 -13
  179. package/src/runtime/account.ts +0 -23
  180. package/src/transport/oasn/oasn-files.ts +5 -5
  181. package/src/transport/oasn/oasn-invocation.ts +44 -2
  182. package/src/transport/oasn/oasn-normalize.ts +0 -26
  183. package/src/transport/oasn/oasn-register.ts +8 -81
  184. package/src/transport/oasn/oasn-transport.ts +9 -32
  185. package/src/transport/oasn/oasn-types.ts +53 -6
  186. package/src/transport/types.ts +33 -36
  187. package/src/util/url-resolver.ts +17 -0
@@ -0,0 +1,535 @@
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
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import os from 'node:os';
14
+ import { logger } from '../util/logger.js';
15
+ const DB_PATH = path.join(os.homedir(), '.openclaw', 'openagent.db');
16
+ // ── StateStore ──
17
+ export class StateStore {
18
+ db = null;
19
+ accountId = 'default';
20
+ _seenCount = 0;
21
+ /**
22
+ * Initialize the SQLite database.
23
+ * Must be called before any other methods.
24
+ *
25
+ * @param currentAccountId - The account ID of the currently starting account.
26
+ * Used for schema migration: old data without account_id will be assigned this ID.
27
+ */
28
+ async init(currentAccountId) {
29
+ this.accountId = currentAccountId || 'default';
30
+ const initSqlJs = (await import('sql.js')).default;
31
+ const SQL = await initSqlJs();
32
+ // Load existing DB file if present
33
+ if (fs.existsSync(DB_PATH)) {
34
+ const buffer = fs.readFileSync(DB_PATH);
35
+ this.db = new SQL.Database(buffer);
36
+ }
37
+ else {
38
+ this.db = new SQL.Database();
39
+ }
40
+ this._migrate();
41
+ return this;
42
+ }
43
+ _migrate() {
44
+ if (!this.db)
45
+ return;
46
+ // Detect old schema (no account_id column)
47
+ const hasAccountId = this._tableHasColumn('channel_state', 'account_id');
48
+ if (hasAccountId) {
49
+ // Already v3 schema — ensure all tables exist
50
+ this._createV3Tables();
51
+ }
52
+ else {
53
+ // Old v2 schema detected — migrate
54
+ this._migrateFromV2();
55
+ }
56
+ }
57
+ _tableHasColumn(table, column) {
58
+ if (!this.db)
59
+ return false;
60
+ try {
61
+ const stmt = this.db.prepare(`PRAGMA table_info(${table})`);
62
+ while (stmt.step()) {
63
+ const row = stmt.getAsObject();
64
+ if (row['name'] === column) {
65
+ stmt.free();
66
+ return true;
67
+ }
68
+ }
69
+ stmt.free();
70
+ }
71
+ catch {
72
+ // Table doesn't exist
73
+ }
74
+ return false;
75
+ }
76
+ _tableExists(table) {
77
+ if (!this.db)
78
+ return false;
79
+ try {
80
+ const stmt = this.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`);
81
+ stmt.bind([table]);
82
+ const exists = stmt.step();
83
+ stmt.free();
84
+ return exists;
85
+ }
86
+ catch {
87
+ return false;
88
+ }
89
+ }
90
+ _migrateFromV2() {
91
+ if (!this.db)
92
+ return;
93
+ logger.info(`[state] Migrating v2 schema to v3 (account_id='${this.accountId}')`);
94
+ // 1. Rename old tables
95
+ if (this._tableExists('channel_state')) {
96
+ this.db.run('ALTER TABLE channel_state RENAME TO _v2_channel_state');
97
+ }
98
+ if (this._tableExists('seen_messages')) {
99
+ this.db.run('ALTER TABLE seen_messages RENAME TO _v2_seen_messages');
100
+ }
101
+ if (this._tableExists('channel_skills')) {
102
+ this.db.run('ALTER TABLE channel_skills RENAME TO _v2_channel_skills');
103
+ }
104
+ if (this._tableExists('channel_purpose')) {
105
+ this.db.run('ALTER TABLE channel_purpose RENAME TO _v2_channel_purpose');
106
+ }
107
+ // 2. Create v3 tables
108
+ this._createV3Tables();
109
+ // 3. Copy old data with current account_id
110
+ if (this._tableExists('_v2_channel_state')) {
111
+ this.db.run(`
112
+ INSERT INTO channel_state (account_id, channel_id, channel_name, joined, last_visit, last_reply, last_msg_seq, created_at, updated_at)
113
+ SELECT ?, channel_id, channel_name, joined, last_visit, last_reply, last_msg_seq, created_at, updated_at
114
+ FROM _v2_channel_state
115
+ `, [this.accountId]);
116
+ }
117
+ if (this._tableExists('_v2_seen_messages')) {
118
+ this.db.run(`
119
+ INSERT INTO seen_messages (account_id, message_id, channel_id, seen_at)
120
+ SELECT ?, message_id, channel_id, seen_at
121
+ FROM _v2_seen_messages
122
+ `, [this.accountId]);
123
+ }
124
+ if (this._tableExists('_v2_channel_skills')) {
125
+ this.db.run(`
126
+ INSERT INTO channel_skills (account_id, channel_id, skill_content, updated_at)
127
+ SELECT ?, channel_id, skill_content, updated_at
128
+ FROM _v2_channel_skills
129
+ `, [this.accountId]);
130
+ }
131
+ if (this._tableExists('_v2_channel_purpose')) {
132
+ this.db.run(`
133
+ INSERT INTO channel_purpose (account_id, channel_id, purpose, updated_at)
134
+ SELECT ?, channel_id, purpose, updated_at
135
+ FROM _v2_channel_purpose
136
+ `, [this.accountId]);
137
+ }
138
+ // 4. Drop old tables
139
+ this.db.run('DROP TABLE IF EXISTS _v2_channel_state');
140
+ this.db.run('DROP TABLE IF EXISTS _v2_seen_messages');
141
+ this.db.run('DROP TABLE IF EXISTS _v2_channel_skills');
142
+ this.db.run('DROP TABLE IF EXISTS _v2_channel_purpose');
143
+ this.persist();
144
+ logger.info('[state] Migration complete');
145
+ }
146
+ _createV3Tables() {
147
+ if (!this.db)
148
+ return;
149
+ this.db.run(`
150
+ CREATE TABLE IF NOT EXISTS channel_state (
151
+ account_id TEXT NOT NULL,
152
+ channel_id TEXT NOT NULL,
153
+ channel_name TEXT NOT NULL DEFAULT '',
154
+ joined INTEGER NOT NULL DEFAULT 0,
155
+ last_visit INTEGER NOT NULL DEFAULT 0,
156
+ last_reply INTEGER NOT NULL DEFAULT 0,
157
+ last_msg_seq INTEGER NOT NULL DEFAULT 0,
158
+ created_at INTEGER NOT NULL DEFAULT 0,
159
+ updated_at INTEGER NOT NULL DEFAULT 0,
160
+ PRIMARY KEY (account_id, channel_id)
161
+ )
162
+ `);
163
+ this.db.run(`
164
+ CREATE TABLE IF NOT EXISTS seen_messages (
165
+ account_id TEXT NOT NULL,
166
+ message_id TEXT NOT NULL,
167
+ channel_id TEXT NOT NULL,
168
+ seen_at INTEGER NOT NULL DEFAULT 0,
169
+ PRIMARY KEY (account_id, message_id)
170
+ )
171
+ `);
172
+ this.db.run(`
173
+ CREATE TABLE IF NOT EXISTS channel_skills (
174
+ account_id TEXT NOT NULL,
175
+ channel_id TEXT NOT NULL,
176
+ skill_content TEXT NOT NULL DEFAULT '',
177
+ updated_at INTEGER NOT NULL DEFAULT 0,
178
+ PRIMARY KEY (account_id, channel_id)
179
+ )
180
+ `);
181
+ this.db.run(`
182
+ CREATE TABLE IF NOT EXISTS channel_purpose (
183
+ account_id TEXT NOT NULL,
184
+ channel_id TEXT NOT NULL,
185
+ purpose TEXT NOT NULL DEFAULT '',
186
+ updated_at INTEGER NOT NULL DEFAULT 0,
187
+ PRIMARY KEY (account_id, channel_id)
188
+ )
189
+ `);
190
+ // §11.1 OASN invocation 幂等持久化。
191
+ // tool_call_id 作为主键 —— 它对应 LLM 一次工具调用,全局唯一。
192
+ // status 索引便于启动时筛非终态记录续轮询。
193
+ this.db.run(`
194
+ CREATE TABLE IF NOT EXISTS pending_invocations (
195
+ account_id TEXT NOT NULL,
196
+ tool_call_id TEXT NOT NULL,
197
+ idempotency_key TEXT NOT NULL,
198
+ invocation_id TEXT,
199
+ session_id TEXT,
200
+ target_agent_id TEXT,
201
+ status TEXT NOT NULL DEFAULT 'pending',
202
+ created_at INTEGER NOT NULL DEFAULT 0,
203
+ updated_at INTEGER NOT NULL DEFAULT 0,
204
+ PRIMARY KEY (account_id, tool_call_id)
205
+ )
206
+ `);
207
+ this.db.run(`
208
+ CREATE INDEX IF NOT EXISTS idx_pending_invocations_status
209
+ ON pending_invocations (account_id, status)
210
+ `);
211
+ this.db.run(`
212
+ CREATE INDEX IF NOT EXISTS idx_pending_invocations_invocation
213
+ ON pending_invocations (account_id, invocation_id)
214
+ `);
215
+ }
216
+ // ── Write to disk ──
217
+ persist() {
218
+ try {
219
+ if (!this.db)
220
+ return;
221
+ const data = this.db.export();
222
+ fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
223
+ fs.writeFileSync(DB_PATH, Buffer.from(data));
224
+ }
225
+ catch (err) {
226
+ logger.error(`[state] persist error: ${err.message}`);
227
+ }
228
+ }
229
+ // ── Channel State ──
230
+ /**
231
+ * Get all joined channels for the current account.
232
+ */
233
+ getJoinedChannels() {
234
+ if (!this.db)
235
+ return [];
236
+ const stmt = this.db.prepare('SELECT * FROM channel_state WHERE account_id = ? AND joined = 1');
237
+ stmt.bind([this.accountId]);
238
+ const results = [];
239
+ while (stmt.step())
240
+ results.push(stmt.getAsObject());
241
+ stmt.free();
242
+ return results;
243
+ }
244
+ getJoinedChannelIds() {
245
+ return this.getJoinedChannels().map(c => c.channel_id);
246
+ }
247
+ getChannel(channelId) {
248
+ if (!this.db)
249
+ return null;
250
+ const stmt = this.db.prepare('SELECT * FROM channel_state WHERE account_id = ? AND channel_id = ?');
251
+ stmt.bind([this.accountId, channelId]);
252
+ const result = stmt.step() ? stmt.getAsObject() : null;
253
+ stmt.free();
254
+ return result;
255
+ }
256
+ /**
257
+ * Mark a channel as joined.
258
+ * Authoritative writer: openagent_join_channel tool (on success).
259
+ */
260
+ markJoined(channelId, channelName) {
261
+ if (!this.db)
262
+ return;
263
+ const now = Date.now();
264
+ this.db.run(`INSERT INTO channel_state (account_id, channel_id, channel_name, joined, last_visit, created_at, updated_at)
265
+ VALUES (?, ?, ?, 1, ?, ?, ?)
266
+ ON CONFLICT(account_id, channel_id) DO UPDATE SET joined=1, channel_name=?, updated_at=?`, [this.accountId, channelId, channelName || '', now, now, now, channelName || '', now]);
267
+ this.persist();
268
+ }
269
+ /**
270
+ * Mark a channel as left.
271
+ * Authoritative writer: openagent_leave_channel tool (on success).
272
+ */
273
+ markLeft(channelId) {
274
+ if (!this.db)
275
+ return;
276
+ this.db.run('UPDATE channel_state SET joined=0, updated_at=? WHERE account_id=? AND channel_id=?', [Date.now(), this.accountId, channelId]);
277
+ this.persist();
278
+ }
279
+ /**
280
+ * Update last_visit timestamp for a channel.
281
+ * Authoritative writer: Collector — on ingest() accepting a message.
282
+ */
283
+ updateLastVisit(channelId) {
284
+ if (!this.db)
285
+ return;
286
+ const now = Date.now();
287
+ this.db.run('UPDATE channel_state SET last_visit=?, updated_at=? WHERE account_id=? AND channel_id=?', [now, now, this.accountId, channelId]);
288
+ this.persist();
289
+ }
290
+ /**
291
+ * Update last_reply timestamp for a channel.
292
+ * Authoritative writer: openagent_send_message tool — on sendMessage() success.
293
+ */
294
+ updateLastReply(channelId) {
295
+ if (!this.db)
296
+ return;
297
+ const now = Date.now();
298
+ this.db.run('UPDATE channel_state SET last_reply=?, updated_at=? WHERE account_id=? AND channel_id=?', [now, now, this.accountId, channelId]);
299
+ this.persist();
300
+ }
301
+ /**
302
+ * Update last_msg_seq for a channel.
303
+ * Authoritative writer: Collector — on ingest() taking msg.sequence.
304
+ */
305
+ updateLastMsgSeq(channelId, seq) {
306
+ if (!this.db)
307
+ return;
308
+ this.db.run('UPDATE channel_state SET last_msg_seq=?, updated_at=? WHERE account_id=? AND channel_id=?', [seq, Date.now(), this.accountId, channelId]);
309
+ this.persist();
310
+ }
311
+ // ── Message Dedup (Collector use) ──
312
+ hasSeen(messageId) {
313
+ if (!this.db)
314
+ return false;
315
+ const stmt = this.db.prepare('SELECT 1 FROM seen_messages WHERE account_id=? AND message_id=?');
316
+ stmt.bind([this.accountId, messageId]);
317
+ const found = stmt.step();
318
+ stmt.free();
319
+ return found;
320
+ }
321
+ markSeen(messageId, channelId) {
322
+ if (!this.db)
323
+ return;
324
+ this.db.run('INSERT OR IGNORE INTO seen_messages (account_id, message_id, channel_id, seen_at) VALUES (?, ?, ?, ?)', [this.accountId, messageId, channelId, Date.now()]);
325
+ // Batch persist: seen_messages are written frequently
326
+ this._seenCount += 1;
327
+ if (this._seenCount % 100 === 0)
328
+ this.persist();
329
+ }
330
+ // ── Channel Skills ──
331
+ getSkill(channelId) {
332
+ if (!this.db)
333
+ return null;
334
+ const stmt = this.db.prepare('SELECT skill_content FROM channel_skills WHERE account_id = ? AND channel_id = ?');
335
+ stmt.bind([this.accountId, channelId]);
336
+ const result = stmt.step() ? stmt.getAsObject() : null;
337
+ stmt.free();
338
+ return result?.['skill_content'] || null;
339
+ }
340
+ setSkill(channelId, skillContent) {
341
+ if (!this.db)
342
+ return;
343
+ const now = Date.now();
344
+ this.db.run(`INSERT INTO channel_skills (account_id, channel_id, skill_content, updated_at)
345
+ VALUES (?, ?, ?, ?)
346
+ ON CONFLICT(account_id, channel_id) DO UPDATE SET skill_content=?, updated_at=?`, [this.accountId, channelId, skillContent, now, skillContent, now]);
347
+ this.persist();
348
+ }
349
+ getAllSkills() {
350
+ if (!this.db)
351
+ return [];
352
+ const stmt = this.db.prepare('SELECT channel_id, skill_content FROM channel_skills WHERE account_id = ?');
353
+ stmt.bind([this.accountId]);
354
+ const results = [];
355
+ while (stmt.step()) {
356
+ const row = stmt.getAsObject();
357
+ results.push({
358
+ channel_id: row['channel_id'],
359
+ skill_content: row['skill_content'],
360
+ });
361
+ }
362
+ stmt.free();
363
+ return results;
364
+ }
365
+ // ── Channel Purpose ──
366
+ getPurpose(channelId) {
367
+ if (!this.db)
368
+ return null;
369
+ const stmt = this.db.prepare('SELECT purpose FROM channel_purpose WHERE account_id = ? AND channel_id = ?');
370
+ stmt.bind([this.accountId, channelId]);
371
+ const result = stmt.step() ? stmt.getAsObject() : null;
372
+ stmt.free();
373
+ return result?.['purpose'] || null;
374
+ }
375
+ setPurpose(channelId, purpose) {
376
+ if (!this.db)
377
+ return;
378
+ const now = Date.now();
379
+ this.db.run(`INSERT INTO channel_purpose (account_id, channel_id, purpose, updated_at)
380
+ VALUES (?, ?, ?, ?)
381
+ ON CONFLICT(account_id, channel_id) DO UPDATE SET purpose=?, updated_at=?`, [this.accountId, channelId, purpose, now, purpose, now]);
382
+ this.persist();
383
+ }
384
+ removePurpose(channelId) {
385
+ if (!this.db)
386
+ return;
387
+ this.db.run('DELETE FROM channel_purpose WHERE account_id = ? AND channel_id = ?', [this.accountId, channelId]);
388
+ this.persist();
389
+ }
390
+ /**
391
+ * Clean up old dedup records (older than 24h)
392
+ */
393
+ cleanupSeen() {
394
+ if (!this.db)
395
+ return;
396
+ const cutoff = Date.now() - 86_400_000;
397
+ this.db.run('DELETE FROM seen_messages WHERE account_id = ? AND seen_at < ?', [this.accountId, cutoff]);
398
+ this.persist();
399
+ }
400
+ /**
401
+ * Close the database connection
402
+ */
403
+ close() {
404
+ if (this.db) {
405
+ this.persist(); // Final persist
406
+ this.db.close();
407
+ this.db = null;
408
+ }
409
+ }
410
+ // ═════════════════════════════════════════════════════════════════
411
+ // §11.1 OASN pending_invocations CRUD(OasnInvocation.PendingInvocationStore 适配)
412
+ //
413
+ // 设计依据:docs/specs/2026-06-16-oasn-transport-abstraction-design.md §11.1
414
+ //
415
+ // 表内字段 account_id 用 this.accountId 自动注入,调用方无需关心多账号隔离。
416
+ // ═════════════════════════════════════════════════════════════════
417
+ /**
418
+ * 查 tool_call_id 是否有未完成记录。命中 → 复用其 idempotency_key 防止重复创建 Invocation。
419
+ *
420
+ * 仅当 status 为非终态(pending/accepted/queued/running)时返回,避免幂等键被复用到新调用上。
421
+ */
422
+ getPendingInvocation(toolCallId) {
423
+ if (!this.db)
424
+ return null;
425
+ const stmt = this.db.prepare(`SELECT idempotency_key, invocation_id, status
426
+ FROM pending_invocations
427
+ WHERE account_id = ? AND tool_call_id = ?`);
428
+ stmt.bind([this.accountId, toolCallId]);
429
+ let row = null;
430
+ if (stmt.step())
431
+ row = stmt.getAsObject();
432
+ stmt.free();
433
+ if (!row)
434
+ return null;
435
+ const status = String(row['status']);
436
+ if (this._isTerminalStatus(status))
437
+ return null;
438
+ const result = {
439
+ idempotency_key: String(row['idempotency_key']),
440
+ };
441
+ const invId = row['invocation_id'];
442
+ if (typeof invId === 'string' && invId.length > 0)
443
+ result.invocation_id = invId;
444
+ return result;
445
+ }
446
+ /**
447
+ * 插入或更新一条 pending 记录。
448
+ *
449
+ * 调用时机:
450
+ * - sendTask 之前(尚无 invocation_id,status='pending')
451
+ * - POST /api/invocations 返回后(回填 invocation_id + status)
452
+ */
453
+ upsertPendingInvocation(record) {
454
+ if (!this.db)
455
+ return;
456
+ const now = Date.now();
457
+ this.db.run(`INSERT INTO pending_invocations
458
+ (account_id, tool_call_id, idempotency_key, invocation_id, session_id, target_agent_id, status, created_at, updated_at)
459
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
460
+ ON CONFLICT(account_id, tool_call_id) DO UPDATE SET
461
+ invocation_id = COALESCE(excluded.invocation_id, pending_invocations.invocation_id),
462
+ session_id = COALESCE(excluded.session_id, pending_invocations.session_id),
463
+ target_agent_id = COALESCE(excluded.target_agent_id, pending_invocations.target_agent_id),
464
+ status = excluded.status,
465
+ updated_at = excluded.updated_at`, [
466
+ this.accountId,
467
+ record.tool_call_id,
468
+ record.idempotency_key,
469
+ record.invocation_id ?? null,
470
+ record.session_id ?? null,
471
+ record.target_agent_id ?? null,
472
+ record.status,
473
+ now,
474
+ now,
475
+ ]);
476
+ this.persist();
477
+ }
478
+ /**
479
+ * 终态标记。透过 invocation_id 查找(OasnInvocation 在终态回调时只持有 invocation_id)。
480
+ */
481
+ markPendingInvocationTerminal(invocationId, status) {
482
+ if (!this.db)
483
+ return;
484
+ this.db.run(`UPDATE pending_invocations
485
+ SET status = ?, updated_at = ?
486
+ WHERE account_id = ? AND invocation_id = ?`, [status, Date.now(), this.accountId, invocationId]);
487
+ this.persist();
488
+ }
489
+ /**
490
+ * §11.2 abort 标记。
491
+ *
492
+ * 服务端没有 cancel API,本地只能记录"已放弃跟踪",便于排查 / 配额对账。
493
+ */
494
+ markPendingInvocationAbandoned(invocationId) {
495
+ this.markPendingInvocationTerminal(invocationId, 'abandoned');
496
+ }
497
+ /**
498
+ * 列出非终态记录(启动时续轮询用)。
499
+ *
500
+ * 返回顺序:按 created_at 升序,先创建的先续。
501
+ */
502
+ listUnsettledInvocations() {
503
+ if (!this.db)
504
+ return [];
505
+ const stmt = this.db.prepare(`SELECT tool_call_id, idempotency_key, invocation_id, session_id, target_agent_id, status, created_at, updated_at
506
+ FROM pending_invocations
507
+ WHERE account_id = ?
508
+ AND status NOT IN ('succeeded','failed','timed_out','cancelled','abandoned')
509
+ ORDER BY created_at ASC`);
510
+ stmt.bind([this.accountId]);
511
+ const results = [];
512
+ while (stmt.step()) {
513
+ const row = stmt.getAsObject();
514
+ results.push({
515
+ tool_call_id: row['tool_call_id'],
516
+ idempotency_key: row['idempotency_key'],
517
+ invocation_id: row['invocation_id'] ?? null,
518
+ session_id: row['session_id'] ?? null,
519
+ target_agent_id: row['target_agent_id'] ?? null,
520
+ status: row['status'],
521
+ created_at: Number(row['created_at']),
522
+ updated_at: Number(row['updated_at']),
523
+ });
524
+ }
525
+ stmt.free();
526
+ return results;
527
+ }
528
+ _isTerminalStatus(status) {
529
+ return status === 'succeeded'
530
+ || status === 'failed'
531
+ || status === 'timed_out'
532
+ || status === 'cancelled'
533
+ || status === 'abandoned';
534
+ }
535
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * TIM C2C — Agent-to-Agent direct messaging
3
+ *
4
+ * Provides C2C (peer-to-peer) communication for remote agent orchestration.
5
+ * Used by openagent_call_remote_agent tool (T2) to send requests and await replies.
6
+ *
7
+ * Architecture:
8
+ * - sendC2CCustomMessage: sends a TIM CustomMessage via CONV_C2C
9
+ * - waitForC2CReply: registers a pending request, resolves when reply arrives
10
+ * - initC2CHandler: listens for client 'c2c_message' events, dispatches to pending requests
11
+ *
12
+ * @see docs/products/orchestrator/specs/T1-c2c-infra.md
13
+ * @see docs/products/orchestrator/openagent-teams-architecture.md §3.3.3
14
+ */
15
+ import type { TIMClient } from './client.js';
16
+ /** C2C message payload types for the OpenAgent orchestration protocol */
17
+ export type C2CMessagePayload = {
18
+ type: 'openagent_task_request';
19
+ request_id: string;
20
+ task: string;
21
+ session_mode: string;
22
+ } | {
23
+ type: 'openagent_task_progress';
24
+ request_id: string;
25
+ content: string;
26
+ } | {
27
+ type: 'openagent_task_result';
28
+ request_id: string;
29
+ status: 'complete' | 'error';
30
+ content: string;
31
+ /** T4: number of TIMFileElem messages sent before this result. 0 or absent = no files. */
32
+ file_count?: number;
33
+ };
34
+ /** Result returned by waitForC2CReply when the remote agent completes */
35
+ export interface C2CReplyResult {
36
+ status: 'complete' | 'error';
37
+ content: string;
38
+ /** T4: local file paths after saveMediaBuffer (populated from pending TIMFileElem messages) */
39
+ mediaUrls?: string[];
40
+ }
41
+ /** Options for waitForC2CReply */
42
+ export interface WaitForC2CReplyOptions {
43
+ timeoutMs: number;
44
+ signal?: AbortSignal;
45
+ onProgress?: (content: string) => void;
46
+ }
47
+ /**
48
+ * Send a C2C custom message to a remote agent.
49
+ *
50
+ * Uses TIM SDK createCustomMessage + CONV_C2C.
51
+ * Protocol payload is JSON-serialized into the custom message `data` field.
52
+ *
53
+ * Timeout pattern matches messages.ts sendMessage (10s SDK-call guard).
54
+ * @see src/tim/messages.ts L61-87
55
+ *
56
+ * @param userId - Target agent's TIM userId
57
+ * @param payload - Structured message payload (request/progress/result)
58
+ */
59
+ export declare function sendC2CCustomMessage(userId: string, payload: C2CMessagePayload): Promise<void>;
60
+ /**
61
+ * Wait for a C2C reply matching a specific requestId.
62
+ *
63
+ * Registers a pending entry in the registry. When c2cMessageHandler receives
64
+ * a matching message, it dispatches to the entry's callbacks:
65
+ * - task_progress → onProgress(content)
66
+ * - task_result → resolve({ status, content })
67
+ *
68
+ * @param requestId - UUID to match replies against
69
+ * @param options - Timeout, abort signal, and progress callback
70
+ */
71
+ export declare function waitForC2CReply(requestId: string, options: WaitForC2CReplyOptions): Promise<C2CReplyResult>;
72
+ /**
73
+ * Initialize the C2C message handler.
74
+ *
75
+ * Listens for 'c2c_message' events from TIMClient and dispatches to:
76
+ * - pendingRequests registry (for progress/result → T2's waitForC2CReply)
77
+ * - 'c2c_request' event (for incoming task requests → T3's handler)
78
+ *
79
+ * Must be called after TIMClient.connect() succeeds.
80
+ *
81
+ * @param client - Connected TIMClient instance
82
+ */
83
+ export declare function initC2CHandler(client: TIMClient): void;