openclaw-openagent 1.0.13 → 1.0.14

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 (128) hide show
  1. package/dist/src/messaging/executor.d.ts +2 -3
  2. package/dist/src/messaging/executor.js +4 -31
  3. package/dist/src/plugin-ui/assets/openagent-override.js +4 -5
  4. package/dist/src/runtime/update-checker.d.ts +1 -1
  5. package/dist/src/runtime/update-checker.js +9 -46
  6. package/package.json +1 -3
  7. package/src/app/channel-tools.ts +0 -249
  8. package/src/app/discovery-tools.ts +0 -273
  9. package/src/app/download-file-tool.ts +0 -133
  10. package/src/app/hooks.ts +0 -144
  11. package/src/app/index.ts +0 -84
  12. package/src/app/messaging-tools.ts +0 -79
  13. package/src/app/ops-tools.ts +0 -155
  14. package/src/app/remote-agent-tool.ts +0 -762
  15. package/src/app/types.ts +0 -68
  16. package/src/app/upload-file-tool.ts +0 -411
  17. package/src/app/verbose-preflight.ts +0 -190
  18. package/src/auth/config.ts +0 -266
  19. package/src/auth/credential-manager.ts +0 -146
  20. package/src/auth/index.ts +0 -24
  21. package/src/auth/verify.ts +0 -99
  22. package/src/channel.ts +0 -566
  23. package/src/compat.ts +0 -94
  24. package/src/config/config-schema.ts +0 -45
  25. package/src/messaging/aggregator.ts +0 -120
  26. package/src/messaging/collector.ts +0 -89
  27. package/src/messaging/executor.ts +0 -72
  28. package/src/messaging/inbound.ts +0 -150
  29. package/src/messaging/index.ts +0 -11
  30. package/src/messaging/mention-protocol.ts +0 -94
  31. package/src/messaging/process-c2c-request.ts +0 -564
  32. package/src/messaging/process-message.ts +0 -373
  33. package/src/messaging/scheduler.ts +0 -55
  34. package/src/messaging/types.ts +0 -38
  35. package/src/plugin-ui/adapters/oc-2026-04.js +0 -103
  36. package/src/plugin-ui/adapters/oc-2026-05.js +0 -125
  37. package/src/plugin-ui/adapters/oc-2026-06.js +0 -125
  38. package/src/plugin-ui/adapters/oc-unknown.js +0 -48
  39. package/src/plugin-ui/assets/agentbook-icon.svg +0 -5
  40. package/src/plugin-ui/assets/bg.png +0 -0
  41. package/src/plugin-ui/assets/icon.png +0 -0
  42. package/src/plugin-ui/assets/magic.svg +0 -5
  43. package/src/plugin-ui/assets/openagent-override.js +0 -11263
  44. package/src/plugin-ui/build.cjs +0 -463
  45. package/src/plugin-ui/index.ts +0 -18
  46. package/src/plugin-ui/modules/agent-book/panel/agent-book.js +0 -570
  47. package/src/plugin-ui/modules/agent-book/panel/agent-card.js +0 -170
  48. package/src/plugin-ui/modules/agent-book/panel/agent-data.js +0 -643
  49. package/src/plugin-ui/modules/agent-book/panel/inject-ui.js +0 -665
  50. package/src/plugin-ui/modules/agent-book/panel/mention-state.js +0 -206
  51. package/src/plugin-ui/modules/agent-book/panel/styles.js +0 -832
  52. package/src/plugin-ui/modules/agent-book/panel/theme-adapter.js +0 -86
  53. package/src/plugin-ui/modules/agent-book/remote-agent-tool/components-core.js +0 -295
  54. package/src/plugin-ui/modules/agent-book/remote-agent-tool/thought-chain-card.js +0 -211
  55. package/src/plugin-ui/modules/agent-book/scanner.js +0 -131
  56. package/src/plugin-ui/modules/agent-book/travelcard/travel-cards.js +0 -500
  57. package/src/plugin-ui/modules/agent-book/travelcard/travel-engine.js +0 -652
  58. package/src/plugin-ui/modules/agent-book/travelcard/travel-styles.js +0 -262
  59. package/src/plugin-ui/modules/loader/bootstrap.js +0 -133
  60. package/src/plugin-ui/modules/loader/shared-state.js +0 -838
  61. package/src/plugin-ui/modules/loader/ws-intercept.js +0 -199
  62. package/src/plugin-ui/modules/remote-agent/chunk-parser.js +0 -161
  63. package/src/plugin-ui/modules/remote-agent/execution-card.js +0 -530
  64. package/src/plugin-ui/modules/remote-agent/markdown-renderer.js +0 -256
  65. package/src/plugin-ui/modules/remote-agent/media-links.js +0 -151
  66. package/src/plugin-ui/modules/remote-agent/native-style-adapter.js +0 -134
  67. package/src/plugin-ui/modules/remote-agent/output-card.js +0 -342
  68. package/src/plugin-ui/modules/remote-agent/progress-store.js +0 -363
  69. package/src/plugin-ui/modules/remote-agent/render-hooks.js +0 -1700
  70. package/src/plugin-ui/modules/remote-agent/styles.js +0 -903
  71. package/src/plugin-ui/modules/remote-agent/tool-card-model.js +0 -130
  72. package/src/plugin-ui/postinstall-deploy.cjs +0 -52
  73. package/src/plugin-ui/ui-extension-loader/backup.ts +0 -92
  74. package/src/plugin-ui/ui-extension-loader/index.ts +0 -276
  75. package/src/plugin-ui/ui-extension-loader/locator.ts +0 -152
  76. package/src/plugin-ui/ui-extension-loader/manifest.ts +0 -57
  77. package/src/plugin-ui/ui-extension-loader/registry-regex.ts +0 -944
  78. package/src/plugin-ui/ui-extension-loader/removed-extensions.ts +0 -70
  79. package/src/plugin-ui/ui-extension-loader/types.ts +0 -72
  80. package/src/proxy/auth-proxy.ts +0 -414
  81. package/src/runtime/account.ts +0 -549
  82. package/src/runtime/index.ts +0 -7
  83. package/src/runtime/plugin-runtime.ts +0 -94
  84. package/src/runtime/registry.ts +0 -71
  85. package/src/runtime/update-checker.ts +0 -286
  86. package/src/sdk/CLASS_MAP.md +0 -143
  87. package/src/sdk/index.d.ts +0 -126
  88. package/src/sdk/index.js +0 -23990
  89. package/src/sdk/modules/cloud-search-module.js +0 -1117
  90. package/src/sdk/modules/follow-module.js +0 -1069
  91. package/src/sdk/modules/group-module.js +0 -7397
  92. package/src/sdk/modules/relationship-module.js +0 -2269
  93. package/src/sdk/modules/signaling-module.js +0 -1468
  94. package/src/sdk/modules/tim-upload-plugin.js +0 -730
  95. package/src/sdk/node-env/http-request.js +0 -90
  96. package/src/sdk/node-env/index.js +0 -57
  97. package/src/sdk/node-env/storage.js +0 -114
  98. package/src/sdk/package.json +0 -10
  99. package/src/sdk/tsconfig.json +0 -16
  100. package/src/state/pending-invocation-store.ts +0 -43
  101. package/src/state/store.ts +0 -756
  102. package/src/tim/c2c.ts +0 -451
  103. package/src/tim/channels.ts +0 -364
  104. package/src/tim/client.ts +0 -330
  105. package/src/tim/index.ts +0 -18
  106. package/src/tim/messages.ts +0 -166
  107. package/src/tim/sdk-logger-init.ts +0 -50
  108. package/src/tools.ts +0 -10
  109. package/src/transport/factory.ts +0 -95
  110. package/src/transport/oasn/index.ts +0 -17
  111. package/src/transport/oasn/oasn-agent-card.ts +0 -111
  112. package/src/transport/oasn/oasn-discovery.ts +0 -108
  113. package/src/transport/oasn/oasn-files.ts +0 -210
  114. package/src/transport/oasn/oasn-http.ts +0 -529
  115. package/src/transport/oasn/oasn-invocation.ts +0 -604
  116. package/src/transport/oasn/oasn-normalize.ts +0 -133
  117. package/src/transport/oasn/oasn-register.ts +0 -33
  118. package/src/transport/oasn/oasn-transport.ts +0 -318
  119. package/src/transport/oasn/oasn-types.ts +0 -404
  120. package/src/transport/tim/index.ts +0 -8
  121. package/src/transport/tim/tim-transport.ts +0 -515
  122. package/src/transport/types.ts +0 -538
  123. package/src/types/openclaw-plugin-sdk-media-store.d.ts +0 -9
  124. package/src/types/openclaw.d.ts +0 -97
  125. package/src/types/tencentcloud-chat.d.ts +0 -15
  126. package/src/util/http.ts +0 -113
  127. package/src/util/logger.ts +0 -131
  128. package/src/util/url-resolver.ts +0 -77
@@ -1,838 +0,0 @@
1
- // ══════════════════════════════════════════════════════════════
2
- // CL — OpenAgent 共享状态与跨模块 hooks
3
- // 所有跨模块依赖必须注册在此,禁止隐式闭包共享
4
- // ══════════════════════════════════════════════════════════════
5
- const CL = {
6
- // ── 数据 ──
7
- agentCache: [], // Agent 列表缓存
8
- lastFetchTime: 0, // 上次拉取时间戳
9
-
10
- // ── Mention 状态 ──
11
- pendingMention: null, // 待注入的 @mention 数据
12
- panel: null, // Agent Book 面板 DOM
13
- escKeyBound: false, // ESC 键是否已绑定
14
-
15
- // ── Trip 数据 ──
16
- tripCardData: null, // 行程卡片 JSON 数据
17
- tripCardDataScoped: null, // 按 toolCallId / routeId / cardId 存储的行程卡片缓存
18
- tripCardDataFetchPromise: null, // trip-card-data.json 的全局单次请求
19
- tripCardDataFetchFailed: false, // 文件不存在时避免扫描器重复 404
20
-
21
- // ── Scanner ──
22
- clScanCount: 0, // 通用 DOM 扫描计数器
23
-
24
- // ── Agent Identity(跨链路传递) ──
25
- lastMentionAgentId: null, // 用户选择 Agent 时保留的 agent_id(100% 可靠)
26
- agentIdentityCache: {}, // 按 id/name 缓存完整身份,避免用 UUID 走搜索接口查头像
27
- remoteSendInFlight: false, // Agent Book remote call 发送锁,避免 async patch 期间重复发送
28
-
29
- // ── Hooks(前向引用安全) ──
30
- // 占位函数,由后续模块赋值覆盖真实实现
31
- handleDelegateWsEvent: function(msg) {},
32
- processCustomCards: function(bubble) {},
33
-
34
- // ── Host 版本(构建时注入,fallback 运行时检测)──
35
- hostVersion: '__OPENCLAW_HOST_VERSION__',
36
-
37
- // ── Override 构建标识(构建时注入,用于缓存自检)──
38
- buildId: '__OPENAGENT_BUILD_ID__',
39
-
40
- // ── 配置 ──
41
- OPENAGENT_API: 'https://api.openagent.club',
42
- AUTH_API: '/plugins/openagent', // Proxied via Gateway registerHttpRoute (see src/proxy/auth-proxy.ts)
43
- POLL_INTERVAL: 800,
44
- MAX_POLL: 30,
45
- CACHE_TTL: 30000,
46
- };
47
-
48
- function _clFindOverrideScript() {
49
- try {
50
- var scripts = document.querySelectorAll('script[src*="openagent-override.js"]');
51
- return scripts.length ? scripts[scripts.length - 1] : null;
52
- } catch (e) {
53
- return null;
54
- }
55
- }
56
-
57
- function _clReadOverrideScriptVersionFromDocument() {
58
- try {
59
- var script = _clFindOverrideScript();
60
- if (!script) return '';
61
- var src = script.getAttribute('src') || '';
62
- var url = new URL(src, window.location.href);
63
- return url.searchParams.get('v') || '';
64
- } catch (e) {
65
- return '';
66
- }
67
- }
68
-
69
- function _clResolveControlUiIndexUrl() {
70
- try {
71
- var script = _clFindOverrideScript();
72
- if (script) {
73
- var scriptUrl = new URL(script.src || script.getAttribute('src'), window.location.href);
74
- return new URL('./', scriptUrl.href).href;
75
- }
76
- } catch (e) {}
77
- try {
78
- var url = new URL(window.location.href);
79
- url.hash = '';
80
- url.search = '';
81
- return url.href;
82
- } catch (e) {
83
- return '/';
84
- }
85
- }
86
-
87
- function _clExtractOverrideScriptVersionFromHtml(html) {
88
- var match = String(html || '').match(/openagent-override\.js\?v=([A-Za-z0-9._-]+)/);
89
- return match ? match[1] : '';
90
- }
91
-
92
- function _clInstallOverrideUpdateCheck() {
93
- if (window.__openagentOverrideUpdateCheckInstalled) return;
94
- window.__openagentOverrideUpdateCheckInstalled = true;
95
-
96
- var currentVersion = _clReadOverrideScriptVersionFromDocument() || CL.buildId || '';
97
- var storageKey = 'openagent.overrideScriptVersion.v1';
98
- var reloadKey = 'openagent.overrideReloadedVersion.v1';
99
- try {
100
- document.documentElement.setAttribute('data-openagent-build-id', CL.buildId || 'unknown');
101
- if (currentVersion) document.documentElement.setAttribute('data-openagent-script-version', currentVersion);
102
- } catch (e) {}
103
-
104
- try {
105
- if (window.localStorage && currentVersion) {
106
- window.localStorage.setItem(storageKey, currentVersion);
107
- }
108
- } catch (e) {}
109
-
110
- function reloadForVersion(nextVersion) {
111
- if (!nextVersion || nextVersion === currentVersion) return;
112
- try {
113
- if (window.sessionStorage && window.sessionStorage.getItem(reloadKey) === nextVersion) return;
114
- if (window.sessionStorage) window.sessionStorage.setItem(reloadKey, nextVersion);
115
- } catch (e) {}
116
- console.info('[openagent] override updated, reloading Control UI', currentVersion, '→', nextVersion);
117
- window.location.reload();
118
- }
119
-
120
- async function checkLatestOverrideVersion() {
121
- if (document.visibilityState && document.visibilityState === 'hidden') return;
122
- try {
123
- var res = await fetch(_clResolveControlUiIndexUrl(), { cache: 'no-store' });
124
- if (!res || !res.ok) return;
125
- var latestVersion = _clExtractOverrideScriptVersionFromHtml(await res.text());
126
- reloadForVersion(latestVersion);
127
- } catch (e) {}
128
- }
129
-
130
- setTimeout(checkLatestOverrideVersion, 3000);
131
- setInterval(checkLatestOverrideVersion, 60000);
132
- window.addEventListener('focus', checkLatestOverrideVersion);
133
- document.addEventListener('visibilitychange', function() {
134
- if (!document.hidden) checkLatestOverrideVersion();
135
- });
136
- }
137
-
138
- _clInstallOverrideUpdateCheck();
139
-
140
- // ── 版本解析与比较(供 execution-card V2 分支使用)──
141
-
142
- function _clParseHostVersion(v) {
143
- if (!v) return [0, 0, 0];
144
- var base = String(v).split('-')[0];
145
- var parts = base.split('.');
146
- if (parts.length !== 3) return [0, 0, 0];
147
- var y = parseInt(parts[0], 10);
148
- var m = parseInt(parts[1], 10);
149
- var d = parseInt(parts[2], 10);
150
- if (isNaN(y) || isNaN(m) || isNaN(d)) return [0, 0, 0];
151
- return [y, m, d];
152
- }
153
-
154
- function _clIsHostVersionGte(minVer) {
155
- if (CL.hostVersionSource !== 'exact' && CL.hostVersionSource !== 'script' && CL.hostVersionSource !== 'runtime') {
156
- _clRefreshHostVersionFromRuntime();
157
- }
158
- var cur = _clParseHostVersion(CL.hostVersion || '');
159
- var min = _clParseHostVersion(minVer);
160
- for (var i = 0; i < 3; i++) {
161
- if (cur[i] > min[i]) return true;
162
- if (cur[i] < min[i]) return false;
163
- }
164
- return true;
165
- }
166
-
167
- function _clResolveHostProfile(version) {
168
- var parsed = _clParseHostVersion(version || '');
169
- if (parsed[0] === 2026 && parsed[1] === 4) return 'oc-2026-04';
170
- if (parsed[0] === 2026 && parsed[1] === 5) return 'oc-2026-05';
171
- if (parsed[0] === 2026 && parsed[1] === 6) return 'oc-2026-06';
172
- return 'oc-unknown';
173
- }
174
-
175
- function _clNormalizeHostVersion(value) {
176
- var match = String(value || '').match(/20\d{2}\.\d{1,2}\.\d{1,2}(?:-[A-Za-z0-9._-]+)?/);
177
- return match ? match[0] : '';
178
- }
179
-
180
- function _clGetByPath(root, path) {
181
- var cur = root;
182
- for (var i = 0; i < path.length; i++) {
183
- if (!cur) return '';
184
- cur = cur[path[i]];
185
- }
186
- return cur;
187
- }
188
-
189
- function _clReadHostVersionFromRuntime() {
190
- try {
191
- var scripts = document.querySelectorAll('script[data-openagent-host-version]');
192
- for (var i = scripts.length - 1; i >= 0; i--) {
193
- var scriptVersion = _clNormalizeHostVersion(scripts[i].getAttribute('data-openagent-host-version'));
194
- if (scriptVersion) return { version: scriptVersion, source: 'script' };
195
- }
196
- } catch (e) {}
197
-
198
- var globals = [
199
- window.__OPENCLAW_HOST_VERSION__,
200
- window.__OPENCLAW_VERSION__,
201
- window.__openclawVersion,
202
- window.openclawVersion,
203
- ];
204
- for (var g = 0; g < globals.length; g++) {
205
- var globalVersion = _clNormalizeHostVersion(globals[g]);
206
- if (globalVersion) return { version: globalVersion, source: 'runtime' };
207
- }
208
-
209
- try {
210
- var metaVersion = _clNormalizeHostVersion(
211
- document.querySelector('meta[name="openclaw-version"],meta[name="openclaw:version"]')?.getAttribute('content')
212
- );
213
- if (metaVersion) return { version: metaVersion, source: 'runtime' };
214
- } catch (e) {}
215
-
216
- try {
217
- var app = document.querySelector('openclaw-app');
218
- if (app) {
219
- var paths = [
220
- ['runtime', 'version'],
221
- ['hello', 'server', 'version'],
222
- ['hello', 'version'],
223
- ['client', 'hello', 'server', 'version'],
224
- ['client', 'version'],
225
- ['version'],
226
- ['appVersion'],
227
- ];
228
- for (var p = 0; p < paths.length; p++) {
229
- var appVersion = _clNormalizeHostVersion(_clGetByPath(app, paths[p]));
230
- if (appVersion) return { version: appVersion, source: 'runtime' };
231
- }
232
- }
233
- } catch (e) {}
234
-
235
- return null;
236
- }
237
-
238
- function _clApplyHostVersion(version, source) {
239
- CL.hostVersion = version || '2026.3.0';
240
- CL.hostVersionSource = source || 'fallback';
241
- CL.hostProfile = _clResolveHostProfile(CL.hostVersion);
242
- try {
243
- document.documentElement.setAttribute('data-openagent-host-version', CL.hostVersion || 'unknown');
244
- document.documentElement.setAttribute('data-openagent-host-profile', CL.hostProfile);
245
- document.documentElement.setAttribute('data-openagent-host-version-source', CL.hostVersionSource);
246
- } catch (e) {}
247
- }
248
-
249
- function _clRefreshHostVersionFromRuntime() {
250
- var detected = _clReadHostVersionFromRuntime();
251
- if (!detected) return false;
252
- if (detected.version !== CL.hostVersion || detected.source !== CL.hostVersionSource) {
253
- _clApplyHostVersion(detected.version, detected.source);
254
- console.log('[cl-version] detected via ' + detected.source + ': ' + detected.version);
255
- }
256
- return true;
257
- }
258
-
259
- function _clScheduleHostVersionRefresh() {
260
- var attempts = 0;
261
- var timer = setInterval(function() {
262
- attempts++;
263
- if (_clRefreshHostVersionFromRuntime() || attempts >= 20) {
264
- clearInterval(timer);
265
- }
266
- }, 500);
267
- }
268
-
269
- var _clInitialExactVersion = _clNormalizeHostVersion(CL.hostVersion);
270
- if (_clInitialExactVersion) {
271
- _clApplyHostVersion(_clInitialExactVersion, 'exact');
272
- } else if (!_clRefreshHostVersionFromRuntime()) {
273
- // ─ 运行时 fallback:只做版本族保守判断,避免把 2026.5 误判为 2026.6.9 ──
274
- // v5.x (2026.5+) 有 data-theme / --glass-*;v4.x 有 data-theme-mode / --vscode-*。
275
- try {
276
- var cs = getComputedStyle(document.documentElement);
277
- if (document.documentElement.hasAttribute('data-theme-mode')
278
- || cs.getPropertyValue('--vscode-editor-background').trim()) {
279
- _clApplyHostVersion('2026.4.0', 'feature-fallback');
280
- } else if (document.documentElement.hasAttribute('data-theme')
281
- || cs.getPropertyValue('--glass-surface').trim()
282
- || cs.getPropertyValue('--kn-bg-primary').trim()) {
283
- _clApplyHostVersion('2026.5.0', 'feature-fallback');
284
- } else {
285
- _clApplyHostVersion('2026.3.0', 'feature-fallback');
286
- }
287
- console.log('[cl-version] fallback via DOM/CSS features: ' + CL.hostVersion);
288
- } catch (e) {
289
- _clApplyHostVersion('2026.3.0', 'feature-fallback');
290
- }
291
- _clScheduleHostVersionRefresh();
292
- }
293
-
294
- // 暴露到 window 供控制台调试/测试
295
- window.__CL = CL;
296
-
297
- CL._agentIdentityStorageKey = 'openagent.agentIdentityCache.v1';
298
-
299
- CL._agentIdentityCacheLoaded = false;
300
-
301
- CL._tripCardScopedStorageKey = 'openagent.tripCardData.scoped.v1';
302
- CL._tripCardScopedLoaded = false;
303
- CL._tripCardScopedMaxEntries = 240;
304
-
305
- CL._loadAgentIdentityCache = function() {
306
- if (CL._agentIdentityCacheLoaded) return;
307
- CL._agentIdentityCacheLoaded = true;
308
- try {
309
- var raw = window.localStorage && window.localStorage.getItem(CL._agentIdentityStorageKey);
310
- if (!raw) return;
311
- var parsed = JSON.parse(raw);
312
- if (parsed && typeof parsed === 'object') {
313
- CL.agentIdentityCache = parsed;
314
- }
315
- } catch (err) {
316
- CL.agentIdentityCache = CL.agentIdentityCache || {};
317
- }
318
- };
319
-
320
- CL._saveAgentIdentityCache = function() {
321
- try {
322
- if (!window.localStorage) return;
323
- window.localStorage.setItem(CL._agentIdentityStorageKey, JSON.stringify(CL.agentIdentityCache || {}));
324
- } catch (err) {}
325
- };
326
-
327
- CL.pickAgentIdentityDescription = function(agent) {
328
- if (!agent || typeof agent !== 'object') return '';
329
- var keys = [
330
- 'agent_bio',
331
- 'agentBio',
332
- 'bio',
333
- 'description',
334
- 'desc',
335
- 'agent_description',
336
- 'agentDescription',
337
- 'MOM',
338
- 'mom',
339
- 'introduction',
340
- 'summary'
341
- ];
342
- for (var i = 0; i < keys.length; i++) {
343
- var value = agent[keys[i]];
344
- if (typeof value === 'string' && value.trim()) return value.trim();
345
- }
346
- return '';
347
- };
348
-
349
- CL.storeAgentIdentity = function(agent, fallbackName) {
350
- if (!agent || typeof agent !== 'object') return null;
351
- CL._loadAgentIdentityCache();
352
-
353
- var id = agent.agent_id || agent.agentId || agent.id || agent.tag ||
354
- agent.user_id || agent.userId || agent.identifier || agent.tim_user_id || agent.timUserId || '';
355
- var name = agent.name || agent.agent_name || agent.agentName || fallbackName || '';
356
- var avatar = agent.avatar || agent.avatar_url || agent.avatarUrl || agent.image || agent.logo || agent.photo || '';
357
- var bio = CL.pickAgentIdentityDescription(agent);
358
- var record = {
359
- id: id,
360
- agent_id: id,
361
- tag: agent.tag || id,
362
- name: name,
363
- avatar: avatar || null,
364
- bio: bio,
365
- description: agent.description || bio || '',
366
- MOM: agent.MOM || agent.mom || '',
367
- };
368
-
369
- var keys = [id, record.tag, name, fallbackName].filter(Boolean);
370
- if (keys.length === 0) return null;
371
- for (var i = 0; i < keys.length; i++) {
372
- CL.agentIdentityCache[String(keys[i])] = record;
373
- }
374
- CL._saveAgentIdentityCache();
375
- return record;
376
- };
377
-
378
- CL.getAgentIdentity = function(identifier, fallbackName) {
379
- CL._loadAgentIdentityCache();
380
- var keys = [identifier, fallbackName].filter(Boolean);
381
- for (var i = 0; i < keys.length; i++) {
382
- var hit = CL.agentIdentityCache && CL.agentIdentityCache[String(keys[i])];
383
- if (hit) return hit;
384
- }
385
- return null;
386
- };
387
-
388
- CL.getOpenClawApp = function() {
389
- var app = document.querySelector('openclaw-app');
390
- if (app) return app;
391
- var nodes = document.querySelectorAll('*');
392
- for (var i = 0; i < nodes.length; i++) {
393
- if (typeof nodes[i].handleSendChat === 'function' && nodes[i].client) {
394
- return nodes[i];
395
- }
396
- }
397
- return null;
398
- };
399
-
400
- CL.getCurrentSessionKey = function(app) {
401
- var key = app && typeof app.sessionKey === 'string' ? app.sessionKey : '';
402
- if (!key) {
403
- try {
404
- key = new URL(window.location.href).searchParams.get('session') || '';
405
- } catch (err) {}
406
- }
407
- if (key === 'main') return 'agent:main:main';
408
- return key;
409
- };
410
-
411
- CL.sendRemoteAgentMessage = async function(message) {
412
- var app = CL.getOpenClawApp();
413
- if (!app || typeof app.handleSendChat !== 'function') {
414
- throw new Error('OpenClaw send handler is not available');
415
- }
416
- await app.handleSendChat(message);
417
- };
418
-
419
- CL.createEmptyTripCardData = function() {
420
- return { unitContexts: {}, dayList: [], foodData: null, budgetData: null };
421
- };
422
-
423
- CL.cloneTripCardData = function(data) {
424
- if (!data || typeof data !== 'object') return null;
425
- try {
426
- return JSON.parse(JSON.stringify(data));
427
- } catch (err) {
428
- var clone = CL.createEmptyTripCardData();
429
- clone.unitContexts = data.unitContexts && typeof data.unitContexts === 'object'
430
- ? Object.assign({}, data.unitContexts)
431
- : {};
432
- clone.dayList = Array.isArray(data.dayList) ? data.dayList.slice() : [];
433
- clone.foodData = data.foodData || null;
434
- clone.budgetData = data.budgetData || data.budget || null;
435
- return clone;
436
- }
437
- };
438
-
439
- CL.extractTripCardRefsFromText = function(text) {
440
- var result = {
441
- routeIds: [],
442
- cardRefs: [],
443
- cardIds: [],
444
- unitIds: []
445
- };
446
- if (!text) return result;
447
-
448
- var source = String(text);
449
- var routeSeen = Object.create(null);
450
- var cardSeen = Object.create(null);
451
- var unitSeen = Object.create(null);
452
-
453
- function addRoute(id) {
454
- id = String(id || '').trim();
455
- if (!id || routeSeen[id]) return;
456
- routeSeen[id] = true;
457
- result.routeIds.push(id);
458
- }
459
-
460
- function addCard(tag, id) {
461
- tag = String(tag || '').toLowerCase().trim();
462
- id = String(id || '').trim();
463
- if (!tag || !id) return;
464
- if (tag === 'la_card') return;
465
- var ref = tag + ':' + id;
466
- if (!cardSeen[ref]) {
467
- cardSeen[ref] = true;
468
- result.cardRefs.push(ref);
469
- result.cardIds.push(id);
470
- }
471
- if ((tag === 'tr_card' || tag === 'i_card') && !unitSeen[id]) {
472
- unitSeen[id] = true;
473
- result.unitIds.push(id);
474
- }
475
- if (tag === 'sh_card') {
476
- var prefix = id.match(/^([A-Za-z0-9-]+)(?:[_:])/);
477
- if (prefix && prefix[1]) addRoute(prefix[1]);
478
- }
479
- }
480
-
481
- var routeMatch;
482
- var routeRegex = /[?&]routeId=([A-Za-z0-9_-]+)/g;
483
- while ((routeMatch = routeRegex.exec(source))) {
484
- addRoute(routeMatch[1]);
485
- }
486
-
487
- var tagMatch;
488
- var tagRegex = /(?:&lt;|<)(sh_card|tr_card|i_card|la_card|fr_card|bg_card|time_data_card)(?:&gt;|>)([\s\S]*?)(?:&lt;|<)\/\1(?:&gt;|>)/gi;
489
- while ((tagMatch = tagRegex.exec(source))) {
490
- addCard(tagMatch[1], tagMatch[2]);
491
- }
492
-
493
- return result;
494
- };
495
-
496
- CL.normalizeTripScope = function(scope) {
497
- scope = scope && typeof scope === 'object' ? scope : {};
498
- var normalized = {
499
- toolCallId: String(scope.toolCallId || scope.tcid || '').trim(),
500
- routeIds: [],
501
- cardRefs: [],
502
- cardIds: [],
503
- unitIds: []
504
- };
505
- var routeSeen = Object.create(null);
506
- var cardSeen = Object.create(null);
507
- var cardIdSeen = Object.create(null);
508
- var unitSeen = Object.create(null);
509
-
510
- function addList(target, seen, value) {
511
- if (Array.isArray(value)) {
512
- for (var i = 0; i < value.length; i++) addList(target, seen, value[i]);
513
- return;
514
- }
515
- if (typeof value === 'string' && value.indexOf(',') !== -1) {
516
- var parts = value.split(',');
517
- for (var pi = 0; pi < parts.length; pi++) addList(target, seen, parts[pi]);
518
- return;
519
- }
520
- var item = String(value || '').trim();
521
- if (!item || seen[item]) return;
522
- seen[item] = true;
523
- target.push(item);
524
- }
525
-
526
- addList(normalized.routeIds, routeSeen, scope.routeIds || scope.routeId || '');
527
- addList(normalized.cardRefs, cardSeen, scope.cardRefs || scope.cardRef || '');
528
- addList(normalized.cardIds, cardIdSeen, scope.cardIds || scope.cardId || '');
529
- addList(normalized.unitIds, unitSeen, scope.unitIds || scope.unitId || '');
530
-
531
- var rawRefs = CL.extractTripCardRefsFromText(scope.rawText || scope.html || scope.text || '');
532
- addList(normalized.routeIds, routeSeen, rawRefs.routeIds);
533
- addList(normalized.cardRefs, cardSeen, rawRefs.cardRefs);
534
- addList(normalized.cardIds, cardIdSeen, rawRefs.cardIds);
535
- addList(normalized.unitIds, unitSeen, rawRefs.unitIds);
536
-
537
- for (var ci = 0; ci < normalized.cardRefs.length; ci++) {
538
- var refParts = normalized.cardRefs[ci].split(':');
539
- if (refParts.length >= 2) {
540
- addList(normalized.cardIds, cardIdSeen, refParts.slice(1).join(':'));
541
- var tag = refParts[0];
542
- var id = refParts.slice(1).join(':');
543
- if (tag === 'tr_card' || tag === 'i_card') {
544
- addList(normalized.unitIds, unitSeen, id);
545
- }
546
- }
547
- }
548
-
549
- return normalized;
550
- };
551
-
552
- CL.getTripCardScopeKeys = function(scope) {
553
- var normalized = CL.normalizeTripScope(scope);
554
- var keys = [];
555
- var seen = Object.create(null);
556
-
557
- function add(key) {
558
- key = String(key || '').trim();
559
- if (!key || seen[key]) return;
560
- seen[key] = true;
561
- keys.push(key);
562
- }
563
-
564
- if (normalized.toolCallId) add('tool:' + normalized.toolCallId);
565
- for (var ri = 0; ri < normalized.routeIds.length; ri++) add('route:' + normalized.routeIds[ri]);
566
- for (var cr = 0; cr < normalized.cardRefs.length; cr++) add('card:' + normalized.cardRefs[cr]);
567
- for (var ci = 0; ci < normalized.cardIds.length; ci++) add('card-id:' + normalized.cardIds[ci]);
568
- for (var ui = 0; ui < normalized.unitIds.length; ui++) add('unit:' + normalized.unitIds[ui]);
569
- return keys;
570
- };
571
-
572
- CL._loadTripCardScopedCache = function() {
573
- if (CL._tripCardScopedLoaded) return;
574
- CL._tripCardScopedLoaded = true;
575
- CL.tripCardDataScoped = { version: 1, entries: {} };
576
- try {
577
- var raw = window.localStorage && window.localStorage.getItem(CL._tripCardScopedStorageKey);
578
- if (!raw) return;
579
- var parsed = JSON.parse(raw);
580
- if (parsed && parsed.entries && typeof parsed.entries === 'object') {
581
- CL.tripCardDataScoped = parsed;
582
- }
583
- } catch (err) {
584
- CL.tripCardDataScoped = { version: 1, entries: {} };
585
- }
586
- };
587
-
588
- CL._saveTripCardScopedCache = function() {
589
- try {
590
- if (!window.localStorage || !CL.tripCardDataScoped) return;
591
- var entries = CL.tripCardDataScoped.entries || {};
592
- var keys = Object.keys(entries);
593
- if (keys.length > CL._tripCardScopedMaxEntries) {
594
- keys.sort(function(a, b) {
595
- return ((entries[b] && entries[b].updatedAt) || 0) - ((entries[a] && entries[a].updatedAt) || 0);
596
- });
597
- for (var i = CL._tripCardScopedMaxEntries; i < keys.length; i++) {
598
- delete entries[keys[i]];
599
- }
600
- }
601
- window.localStorage.setItem(CL._tripCardScopedStorageKey, JSON.stringify(CL.tripCardDataScoped));
602
- } catch (err) {}
603
- };
604
-
605
- CL.getScopedTripCardData = function(scope) {
606
- var keys = CL.getTripCardScopeKeys(scope);
607
- if (keys.length === 0) return null;
608
- CL._loadTripCardScopedCache();
609
- var entries = (CL.tripCardDataScoped && CL.tripCardDataScoped.entries) || {};
610
- for (var i = 0; i < keys.length; i++) {
611
- var entry = entries[keys[i]];
612
- if (entry && entry.data && typeof entry.data === 'object') {
613
- console.log('[trip-cache] hit', keys[i]);
614
- return CL.cloneTripCardData(entry.data);
615
- }
616
- }
617
- console.log('[trip-cache] miss', keys.join(','));
618
- return null;
619
- };
620
-
621
- CL.saveScopedTripCardData = function(data, scope) {
622
- if (!data || typeof data !== 'object') return false;
623
- var keys = CL.getTripCardScopeKeys(scope);
624
- if (keys.length === 0) return false;
625
-
626
- CL._loadTripCardScopedCache();
627
- var normalized = CL.normalizeTripScope(scope);
628
- var entry = {
629
- version: 1,
630
- updatedAt: Date.now(),
631
- keys: keys,
632
- meta: normalized,
633
- data: CL.cloneTripCardData(data)
634
- };
635
- if (!entry.data) return false;
636
-
637
- CL.tripCardDataScoped.entries = CL.tripCardDataScoped.entries || {};
638
- for (var i = 0; i < keys.length; i++) {
639
- CL.tripCardDataScoped.entries[keys[i]] = entry;
640
- }
641
- CL._saveTripCardScopedCache();
642
- console.log('[trip-cache] saved', keys.join(','));
643
- return true;
644
- };
645
-
646
- CL._mergeTripDataIntoTarget = function(target, data, replaceDayList) {
647
- if (!target || !data || typeof data !== 'object') return false;
648
- if (!target.unitContexts || typeof target.unitContexts !== 'object') target.unitContexts = {};
649
- if (!Array.isArray(target.dayList)) target.dayList = [];
650
-
651
- var changed = false;
652
-
653
- if (data.unitContexts && typeof data.unitContexts === 'object') {
654
- var ids = Object.keys(data.unitContexts);
655
- for (var i = 0; i < ids.length; i++) {
656
- target.unitContexts[ids[i]] = data.unitContexts[ids[i]];
657
- }
658
- if (ids.length > 0) changed = true;
659
- }
660
-
661
- if (data.unitContext && data.unitContext.id) {
662
- target.unitContexts[data.unitContext.id] = data.unitContext;
663
- changed = true;
664
- }
665
-
666
- if (Array.isArray(data.dayList) && (replaceDayList || target.dayList.length === 0)) {
667
- target.dayList = data.dayList;
668
- changed = true;
669
- }
670
-
671
- if (data.foodData) {
672
- target.foodData = data.foodData;
673
- changed = true;
674
- }
675
-
676
- var incomingBudget = data.budgetData
677
- || data.budget
678
- || (data.result && (data.result.budgetData || data.result.budget));
679
- if (incomingBudget) {
680
- target.budgetData = incomingBudget;
681
- changed = true;
682
- }
683
-
684
- return changed;
685
- };
686
-
687
- CL.mergeScopedTripCardData = function(data, scope, options) {
688
- if (!data || typeof data !== 'object') return false;
689
- var keys = CL.getTripCardScopeKeys(scope);
690
- if (keys.length === 0) return false;
691
-
692
- var existing = CL.getScopedTripCardData(scope);
693
- var target = existing || CL.createEmptyTripCardData();
694
- var changed = CL._mergeTripDataIntoTarget(target, data, !!(options && options.replaceDayList));
695
- if (changed) {
696
- CL.saveScopedTripCardData(target, scope);
697
- }
698
- return changed;
699
- };
700
-
701
- CL.tripCardDataMatchesScope = function(data, scope) {
702
- if (!data || typeof data !== 'object') return false;
703
- var normalized = CL.normalizeTripScope(scope);
704
- var hasScope = !!(normalized.toolCallId || normalized.routeIds.length || normalized.cardRefs.length || normalized.cardIds.length || normalized.unitIds.length);
705
- if (!hasScope) return true;
706
-
707
- var unitContexts = data.unitContexts || {};
708
- for (var i = 0; i < normalized.unitIds.length; i++) {
709
- if (!unitContexts[normalized.unitIds[i]]) return false;
710
- }
711
-
712
- var needsDayList = normalized.cardRefs.some(function(ref) { return ref.indexOf('sh_card:') === 0; });
713
- if (needsDayList && (!Array.isArray(data.dayList) || data.dayList.length === 0)) return false;
714
-
715
- var needsFood = normalized.cardRefs.some(function(ref) { return ref.indexOf('fr_card:') === 0; });
716
- if (needsFood && !data.foodData) return false;
717
-
718
- var needsBudget = normalized.cardRefs.some(function(ref) { return ref.indexOf('bg_card:') === 0; });
719
- if (needsBudget && !(data.budgetData || data.budget || (data.result && (data.result.budgetData || data.result.budget)))) return false;
720
-
721
- return normalized.unitIds.length > 0 || needsDayList || needsFood || needsBudget;
722
- };
723
-
724
- CL.ensureTripCardData = function() {
725
- if (!CL.tripCardData || typeof CL.tripCardData !== 'object') {
726
- CL.tripCardData = CL.createEmptyTripCardData();
727
- }
728
- if (!CL.tripCardData.unitContexts || typeof CL.tripCardData.unitContexts !== 'object') {
729
- CL.tripCardData.unitContexts = {};
730
- }
731
- if (!Array.isArray(CL.tripCardData.dayList)) {
732
- CL.tripCardData.dayList = [];
733
- }
734
- return CL.tripCardData;
735
- };
736
-
737
- CL.mergeTripCardData = function(data, options) {
738
- if (!data || typeof data !== 'object') return false;
739
-
740
- var target = CL.ensureTripCardData();
741
- var replaceDayList = !!(options && options.replaceDayList);
742
- var changed = CL._mergeTripDataIntoTarget(target, data, replaceDayList);
743
- var scope = options && (options.scope || options.meta);
744
- var scopedChanged = scope ? CL.mergeScopedTripCardData(data, scope, options) : false;
745
-
746
- if (changed) {
747
- CL.tripCardDataFetchFailed = false;
748
- try {
749
- localStorage.setItem('openagent_tripCardData', JSON.stringify(target));
750
- } catch (e) {}
751
- }
752
-
753
- return changed || scopedChanged;
754
- };
755
-
756
- CL.diagCardSeq = 0;
757
-
758
- CL.diagMarkCard = function(node, source, meta) {
759
- if (!node || !node.dataset) return '';
760
- var uid = 'clc-' + (++CL.diagCardSeq) + '-' + Date.now().toString(36);
761
- var tcid = (meta && meta.tcid) || '';
762
- node.dataset.clCardUid = uid;
763
- node.dataset.clCardSource = source || '';
764
- node.dataset.clCardTcid = tcid;
765
- node.__clCardUid = uid;
766
- node.__clCardSource = source || '';
767
- console.log('[cl-diag][card-create] uid=' + uid
768
- + ' source=' + (source || '')
769
- + ' tcid=' + String(tcid).substring(0, 8));
770
- return uid;
771
- };
772
-
773
- CL.diagHtmlRewrite = function(label, el, extra) {
774
- try {
775
- if (!el || !el.querySelectorAll) return;
776
- var cards = Array.from(el.querySelectorAll('.cl-remote-agent-card'));
777
- if (el.classList && el.classList.contains('cl-remote-agent-card')) {
778
- cards.unshift(el);
779
- }
780
- if (cards.length === 0) return;
781
-
782
- var cardInfo = cards.map(function(card) {
783
- var uid = card.dataset ? (card.dataset.clCardUid || '') : '';
784
- var jsUid = card.__clCardUid || '';
785
- var img = card.querySelector && card.querySelector('.cl-agent-pill-avatar');
786
- return {
787
- uid: uid,
788
- jsUid: jsUid,
789
- alive: !!uid && uid === jsUid,
790
- tcid: card.dataset ? (card.dataset.clCardTcid || '') : '',
791
- imgAlt: img ? img.getAttribute('alt') : null,
792
- imgSrc: img ? img.getAttribute('src') : null,
793
- text: (card.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 120)
794
- };
795
- });
796
-
797
- console.warn('[cl-diag][html-write] ' + label + ' ' + JSON.stringify({
798
- target: el.className || el.tagName,
799
- extra: extra || null,
800
- cards: cardInfo
801
- }));
802
- console.warn('[cl-diag][html-stack] ' + label + '\n'
803
- + (new Error().stack || '').split('\n').slice(1, 8).join('\n'));
804
- } catch (err) {
805
- console.warn('[cl-diag][html-write-error] ' + label + ' ' + err.message);
806
- }
807
- };
808
-
809
- if (!window.__clDiagClickProbeInstalled) {
810
- window.__clDiagClickProbeInstalled = true;
811
- document.addEventListener('click', function(evt) {
812
- var target = evt.target;
813
- if (!target || !target.closest) return;
814
- var header = target.closest('.cl-tools-collapse-header');
815
- if (!header) return;
816
- var card = header.closest('.cl-remote-agent-card');
817
- if (!card) return;
818
-
819
- var body = card.querySelector('.cl-tools-collapse-body');
820
- var title = card.querySelector('.cl-tools-collapse-header-title');
821
- var uid = card.dataset ? (card.dataset.clCardUid || '') : '';
822
- var jsUid = card.__clCardUid || '';
823
- console.log('[cl-diag][click-probe] before uid=' + uid
824
- + ' jsUid=' + jsUid
825
- + ' alive=' + (!!uid && uid === jsUid)
826
- + ' title=' + JSON.stringify(title ? title.textContent.trim() : '')
827
- + ' bodyClass=' + (body ? body.className : '')
828
- + ' steps=' + (body ? body.querySelectorAll('.cl-tools-collapse-step').length : 0));
829
-
830
- setTimeout(function() {
831
- var afterBody = card.querySelector('.cl-tools-collapse-body');
832
- console.log('[cl-diag][click-probe] after uid=' + uid
833
- + ' jsUid=' + (card.__clCardUid || '')
834
- + ' bodyClass=' + (afterBody ? afterBody.className : '')
835
- + ' steps=' + (afterBody ? afterBody.querySelectorAll('.cl-tools-collapse-step').length : 0));
836
- }, 0);
837
- }, true);
838
- }