@workclaw/openclaw-workclaw 1.0.201 → 1.0.202

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 (53) hide show
  1. package/api.ts +3 -0
  2. package/index.ts +326 -0
  3. package/package.json +3 -11
  4. package/setup-entry.ts +13 -0
  5. package/src/accounts.ts +360 -0
  6. package/src/api/accounts-api.ts +156 -0
  7. package/src/api/prompts-api.ts +122 -0
  8. package/src/api/session-api.ts +246 -0
  9. package/src/api/skills-api.ts +74 -0
  10. package/src/api/workspace.ts +45 -0
  11. package/src/channel.ts +226 -0
  12. package/src/config-schema.ts +62 -0
  13. package/src/connection/workclaw-client.ts +618 -0
  14. package/src/gateway/agent-handlers.ts +551 -0
  15. package/src/gateway/config-writer.ts +378 -0
  16. package/src/gateway/cron-tasks-handler.ts +230 -0
  17. package/src/gateway/message-context.ts +645 -0
  18. package/src/gateway/message-dispatcher.ts +688 -0
  19. package/src/gateway/reconnect.ts +260 -0
  20. package/src/gateway/skills-handler.ts +805 -0
  21. package/src/gateway/skills-list-handler.ts +332 -0
  22. package/src/gateway/tools-list-handler.ts +161 -0
  23. package/src/gateway/workclaw-gateway.ts +305 -0
  24. package/src/media/upload.ts +168 -0
  25. package/src/outbound/index.ts +191 -0
  26. package/src/outbound/workclaw-sender.ts +161 -0
  27. package/src/runtime.ts +520 -0
  28. package/src/secret-contract-api.ts +4 -0
  29. package/src/send.ts +1 -0
  30. package/src/setup-api.ts +3 -0
  31. package/src/setup-core.ts +25 -0
  32. package/src/setup-surface.ts +499 -0
  33. package/src/tools/openclaw-workclaw-cron/api/index.ts +326 -0
  34. package/src/tools/openclaw-workclaw-cron/index.ts +39 -0
  35. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +177 -0
  36. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +188 -0
  37. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +100 -0
  38. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +127 -0
  39. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +100 -0
  40. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +127 -0
  41. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +148 -0
  42. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +109 -0
  43. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +127 -0
  44. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +195 -0
  45. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +161 -0
  46. package/src/tools/openclaw-workclaw-cron/types/index.ts +55 -0
  47. package/src/tools/openclaw-workclaw-cron/utils/index.ts +141 -0
  48. package/src/tools/openclaw-workclaw-system/index.ts +17 -0
  49. package/src/tools/openclaw-workclaw-system/src/get/index.ts +77 -0
  50. package/src/tools/openclaw-workclaw-system/src/token/index.ts +93 -0
  51. package/src/types.ts +52 -0
  52. package/src/utils/content.ts +40 -0
  53. package/tsconfig.json +34 -0
@@ -0,0 +1,3 @@
1
+ export { workclawPlugin } from './channel.js'
2
+ export * from './setup-core.js'
3
+ export * from './setup-surface.js'
@@ -0,0 +1,25 @@
1
+ import type { ChannelSetupAdapter, OpenClawConfig } from 'openclaw/plugin-sdk/setup'
2
+ import {
3
+
4
+ DEFAULT_ACCOUNT_ID,
5
+
6
+ } from 'openclaw/plugin-sdk/setup'
7
+ import { resolveDefaultWorkclawAccountId } from './accounts.js'
8
+ import { patchWorkclawConfig } from './setup-surface.js'
9
+
10
+ export function setWorkclawNamedAccountEnabled(
11
+ cfg: OpenClawConfig,
12
+ accountId: string,
13
+ enabled: boolean,
14
+ ): OpenClawConfig {
15
+ return patchWorkclawConfig(cfg, accountId, { enabled })
16
+ }
17
+
18
+ export const workclawSetupAdapter: ChannelSetupAdapter = {
19
+ resolveAccountId: ({ cfg, accountId }) =>
20
+ accountId?.trim() || resolveDefaultWorkclawAccountId(cfg),
21
+ applyAccountConfig: ({ cfg, accountId }) => {
22
+ const isDefault = !accountId || accountId === DEFAULT_ACCOUNT_ID
23
+ return patchWorkclawConfig(cfg, isDefault ? DEFAULT_ACCOUNT_ID : accountId, { enabled: true })
24
+ },
25
+ }
@@ -0,0 +1,499 @@
1
+ import type { ChannelSetupWizard, OpenClawConfig } from 'openclaw/plugin-sdk/setup'
2
+ import type { WorkclawConfig } from './types.js'
3
+ import {
4
+
5
+ DEFAULT_ACCOUNT_ID,
6
+ formatDocsLink,
7
+
8
+ patchTopLevelChannelConfigSection,
9
+ } from 'openclaw/plugin-sdk/setup'
10
+ import { inspectWorkclawCredentials, resolveDefaultWorkclawAccountId } from './accounts.js'
11
+ import { doFetchJson } from './connection/workclaw-client.js'
12
+
13
+ const channel = 'openclaw-workclaw' as const
14
+
15
+ /**
16
+ * 规范化字符串值
17
+ */
18
+ function normalizeString(value: unknown): string | undefined {
19
+ if (typeof value !== 'string') {
20
+ return undefined
21
+ }
22
+ const trimmed = value.trim()
23
+ return trimmed || undefined
24
+ }
25
+
26
+ function trimTrailingSlash(value: string): string {
27
+ return value.endsWith('/') ? value.slice(0, -1) : value
28
+ }
29
+
30
+ function resolveSetupApiBases(cfg: OpenClawConfig): {
31
+ authBaseUrl: string
32
+ openApiBaseUrl: string
33
+ allowInsecureTls?: boolean
34
+ requestTimeout?: number
35
+ } {
36
+ const workclawCfg = cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
37
+ const configuredBaseUrl
38
+ = normalizeString(workclawCfg?.baseUrl)
39
+ ?? normalizeString(process.env.WORKCLAW_BASE_URL)
40
+ const configuredAuthBaseUrl = normalizeString(process.env.WORKCLAW_AUTH_BASE_URL)
41
+ const configuredOpenApiBaseUrl = normalizeString(process.env.WORKCLAW_OPEN_API_BASE_URL)
42
+
43
+ const defaultAuthBaseUrl = 'https://workbrain.cn/backend-api'
44
+ const defaultOpenApiBaseUrl = `${defaultAuthBaseUrl}/open-apis`
45
+
46
+ const fromBaseUrl = (() => {
47
+ if (!configuredBaseUrl) {
48
+ return null
49
+ }
50
+
51
+ const normalized = trimTrailingSlash(configuredBaseUrl)
52
+ if (normalized.endsWith('/open-apis')) {
53
+ return {
54
+ authBaseUrl: normalized.slice(0, -'/open-apis'.length),
55
+ openApiBaseUrl: normalized,
56
+ }
57
+ }
58
+
59
+ return {
60
+ authBaseUrl: normalized,
61
+ openApiBaseUrl: `${normalized}/open-apis`,
62
+ }
63
+ })()
64
+
65
+ return {
66
+ authBaseUrl: trimTrailingSlash(
67
+ configuredAuthBaseUrl ?? fromBaseUrl?.authBaseUrl ?? defaultAuthBaseUrl,
68
+ ),
69
+ openApiBaseUrl: trimTrailingSlash(
70
+ configuredOpenApiBaseUrl ?? fromBaseUrl?.openApiBaseUrl ?? defaultOpenApiBaseUrl,
71
+ ),
72
+ allowInsecureTls: workclawCfg?.allowInsecureTls,
73
+ requestTimeout: workclawCfg?.requestTimeout,
74
+ }
75
+ }
76
+
77
+ /**
78
+ * 检查 Workclaw 是否已配置
79
+ */
80
+ function isWorkclawConfigured(cfg: OpenClawConfig): boolean {
81
+ const workclawCfg = cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
82
+
83
+ // 检查字符串值是否已配置
84
+ const isConfigured = (value: unknown): boolean => {
85
+ const asString = normalizeString(value)
86
+ return !!asString
87
+ }
88
+
89
+ const topLevelConfigured
90
+ = isConfigured(workclawCfg?.appKey)
91
+ && isConfigured(workclawCfg?.appSecret)
92
+
93
+ const accountConfigured = Object.values(workclawCfg?.accounts ?? {}).some((account) => {
94
+ if (!account || typeof account !== 'object') {
95
+ return false
96
+ }
97
+ const hasOwnAppKey = Object.prototype.hasOwnProperty.call(account, 'appKey')
98
+ const hasOwnAppSecret = Object.prototype.hasOwnProperty.call(account, 'appSecret')
99
+ const accountAppKeyConfigured = hasOwnAppKey
100
+ ? isConfigured((account as Record<string, unknown>).appKey)
101
+ : isConfigured(workclawCfg?.appKey)
102
+ const accountSecretConfigured = hasOwnAppSecret
103
+ ? isConfigured((account as Record<string, unknown>).appSecret)
104
+ : isConfigured(workclawCfg?.appSecret)
105
+ return accountAppKeyConfigured && accountSecretConfigured
106
+ })
107
+
108
+ return topLevelConfigured || accountConfigured
109
+ }
110
+
111
+ /**
112
+ * 修补 Workclaw 配置
113
+ */
114
+ export function patchWorkclawConfig(
115
+ cfg: OpenClawConfig,
116
+ accountId: string,
117
+ patch: Record<string, unknown>,
118
+ ): OpenClawConfig {
119
+ const workclawCfg = cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
120
+ if (accountId === DEFAULT_ACCOUNT_ID) {
121
+ return patchTopLevelChannelConfigSection({
122
+ cfg,
123
+ channel,
124
+ enabled: true,
125
+ patch,
126
+ })
127
+ }
128
+ const nextAccountPatch = {
129
+ ...(workclawCfg?.accounts?.[accountId] as Record<string, unknown> | undefined),
130
+ enabled: true,
131
+ ...patch,
132
+ }
133
+ return patchTopLevelChannelConfigSection({
134
+ cfg,
135
+ channel,
136
+ enabled: true,
137
+ patch: {
138
+ accounts: {
139
+ ...workclawCfg?.accounts,
140
+ [accountId]: nextAccountPatch,
141
+ },
142
+ },
143
+ })
144
+ }
145
+
146
+ type WizardPrompter = Parameters<NonNullable<ChannelSetupWizard['finalize']>>[0]['prompter']
147
+
148
+ /**
149
+ * 提示凭证帮助信息
150
+ */
151
+ async function noteWorkclawCredentialHelp(prompter: WizardPrompter): Promise<void> {
152
+ await prompter.note(
153
+ [
154
+ '智小途插件安装引导',
155
+ '',
156
+ '准备事项:',
157
+ '1. 访问 workbrain.cn 获取 App Key 和 App Secret',
158
+ '2. 确保您的账号已开通智小途服务',
159
+ '3. 准备好您的手机号(用于获取配置信息)',
160
+ '',
161
+ `文档: ${formatDocsLink('/channels/openclaw-workclaw', '智小途')}`,
162
+ ].join('\n'),
163
+ '智小途配置',
164
+ )
165
+ }
166
+
167
+ /**
168
+ * 提示 App Key 输入
169
+ */
170
+ async function promptWorkclawAppKey(params: {
171
+ prompter: WizardPrompter
172
+ initialValue?: string
173
+ }): Promise<string> {
174
+ return (
175
+ await params.prompter.text({
176
+ message: '智小途 App Key',
177
+ initialValue: params.initialValue,
178
+ validate: value => (value?.trim() ? undefined : 'App Key 不能为空'),
179
+ })
180
+ ).trim()
181
+ }
182
+
183
+ /**
184
+ * 提示 App Secret 输入
185
+ */
186
+ async function promptWorkclawAppSecret(params: {
187
+ prompter: WizardPrompter
188
+ initialValue?: string
189
+ }): Promise<string> {
190
+ return (
191
+ await params.prompter.text({
192
+ message: '智小途 App Secret',
193
+ initialValue: params.initialValue,
194
+ validate: value => (value?.trim() ? undefined : 'App Secret 不能为空'),
195
+ })
196
+ ).trim()
197
+ }
198
+
199
+ /**
200
+ * 提示手机号输入
201
+ */
202
+ async function promptWorkclawPhone(params: {
203
+ prompter: WizardPrompter
204
+ initialValue?: string
205
+ }): Promise<string> {
206
+ return (
207
+ await params.prompter.text({
208
+ message: '智小途手机号',
209
+ initialValue: params.initialValue,
210
+ validate: (value) => {
211
+ if (!value?.trim())
212
+ return '手机号不能为空'
213
+ if (!/^1[3-9]\d{9}$/.test(value.trim()))
214
+ return '请输入正确的手机号格式'
215
+ return undefined
216
+ },
217
+ })
218
+ ).trim()
219
+ }
220
+
221
+ /**
222
+ * 通过手机号获取 agentId 和 userId
223
+ */
224
+ async function fetchAgentInfoByPhone(cfg: OpenClawConfig, appKey: string, appSecret: string, phone: string, prompter: WizardPrompter): Promise<{
225
+ agentId?: string
226
+ userId?: string
227
+ } | null> {
228
+ prompter.note?.('正在通过手机号获取配置信息...', '获取配置')
229
+
230
+ try {
231
+ const { authBaseUrl, openApiBaseUrl, allowInsecureTls, requestTimeout }
232
+ = resolveSetupApiBases(cfg)
233
+
234
+ // 1. 获取 access token
235
+ const tokenData = await doFetchJson(
236
+ `${authBaseUrl}/authen/v1/access_token/internal`,
237
+ {
238
+ method: 'POST',
239
+ headers: {
240
+ 'Content-Type': 'application/json',
241
+ },
242
+ body: JSON.stringify({
243
+ app_key: appKey,
244
+ app_secret: appSecret,
245
+ }),
246
+ },
247
+ allowInsecureTls,
248
+ requestTimeout,
249
+ )
250
+
251
+ if (tokenData.code !== 200 || !tokenData.data?.accessToken) {
252
+ prompter.note?.(`获取 Token 失败: ${tokenData.message || '未知错误'}`, '获取配置')
253
+ return null
254
+ }
255
+
256
+ const accessToken = tokenData.data.accessToken
257
+
258
+ // 2. 通过手机号获取 agentId 和 userId
259
+ const agentData = await doFetchJson(
260
+ `${openApiBaseUrl}/instance/local/agentInf`,
261
+ {
262
+ method: 'POST',
263
+ headers: {
264
+ 'Content-Type': 'application/json',
265
+ 'Authorization': `Bearer ${accessToken}`,
266
+ },
267
+ body: JSON.stringify({
268
+ appKey,
269
+ phone,
270
+ }),
271
+ },
272
+ allowInsecureTls,
273
+ requestTimeout,
274
+ )
275
+
276
+ if (agentData.code !== 200 || !agentData.data) {
277
+ prompter.note?.(`获取配置信息失败: ${agentData.message || '未知错误'}`, '获取配置')
278
+ return null
279
+ }
280
+
281
+ prompter.note?.(`成功获取配置信息`, '获取配置')
282
+
283
+ return {
284
+ agentId: agentData.data.agentId,
285
+ userId: agentData.data.userId,
286
+ }
287
+ }
288
+ catch (error) {
289
+ prompter.note?.(`获取配置失败: ${(error as Error).message}`, '获取配置')
290
+ return null
291
+ }
292
+ }
293
+
294
+ /**
295
+ * 运行新应用流程
296
+ */
297
+ async function runNewAppFlow(params: {
298
+ cfg: OpenClawConfig
299
+ prompter: WizardPrompter
300
+ options?: Parameters<NonNullable<ChannelSetupWizard['finalize']>>[0]['options']
301
+ }): Promise<{ cfg: OpenClawConfig }> {
302
+ const { prompter } = params
303
+ let next = params.cfg
304
+
305
+ // 1. 显示帮助信息
306
+ await noteWorkclawCredentialHelp(prompter)
307
+
308
+ // 2. 获取 App Key
309
+ const appKey = await promptWorkclawAppKey({
310
+ prompter,
311
+ initialValue: normalizeString(process.env.WORKCLAW_APP_KEY),
312
+ })
313
+
314
+ // 3. 获取 App Secret
315
+ const appSecret = await promptWorkclawAppSecret({
316
+ prompter,
317
+ initialValue: normalizeString(process.env.WORKCLAW_APP_SECRET),
318
+ })
319
+
320
+ // 4. 获取手机号(通过手机号获取 agentId 和 userId)
321
+ const phone = await promptWorkclawPhone({
322
+ prompter,
323
+ initialValue: normalizeString(process.env.WORKCLAW_PHONE),
324
+ })
325
+
326
+ // 5. 配置基础信息
327
+ next = patchWorkclawConfig(next, DEFAULT_ACCOUNT_ID, {
328
+ appKey,
329
+ appSecret,
330
+ connectionMode: 'websocket',
331
+ enabled: true,
332
+ })
333
+
334
+ // 6. 通过手机号获取 agentId 和 userId
335
+ const agentInfo = await fetchAgentInfoByPhone(next, appKey, appSecret, phone, prompter)
336
+
337
+ if (agentInfo) {
338
+ // 更新配置中的 agentId 和 userId
339
+ const accountConfig: Record<string, unknown> = {
340
+ enabled: true,
341
+ }
342
+
343
+ if (agentInfo.agentId) {
344
+ accountConfig.agentId = agentInfo.agentId
345
+ }
346
+
347
+ if (agentInfo.userId) {
348
+ accountConfig.userId = agentInfo.userId
349
+ }
350
+
351
+ next = patchWorkclawConfig(next, DEFAULT_ACCOUNT_ID, accountConfig)
352
+ }
353
+
354
+ // 6. DM 策略固定为 open
355
+ next = patchWorkclawConfig(next, DEFAULT_ACCOUNT_ID, {
356
+ dmPolicy: 'open',
357
+ allowFrom: ['*'],
358
+ })
359
+
360
+ await prompter.note('智小途配置完成!', '')
361
+
362
+ return { cfg: next }
363
+ }
364
+
365
+ /**
366
+ * 运行编辑配置流程
367
+ */
368
+ async function runEditFlow(params: {
369
+ cfg: OpenClawConfig
370
+ prompter: WizardPrompter
371
+ options?: Parameters<NonNullable<ChannelSetupWizard['finalize']>>[0]['options']
372
+ }): Promise<{ cfg: OpenClawConfig } | null> {
373
+ const workclawCfg = params.cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
374
+ const existingAppKey = workclawCfg?.appKey
375
+
376
+ await params.prompter.note(
377
+ `当前配置的 App Key: ${existingAppKey ?? '(未配置)'}`,
378
+ '智小途配置',
379
+ )
380
+
381
+ const useExisting = await params.prompter.confirm({
382
+ message: `使用现有的智小途配置 (App Key: ${existingAppKey})?`,
383
+ initialValue: true,
384
+ })
385
+
386
+ if (!useExisting) {
387
+ return runNewAppFlow(params)
388
+ }
389
+
390
+ await params.prompter.note('保持现有配置不变。', '')
391
+ return { cfg: params.cfg }
392
+ }
393
+
394
+ /**
395
+ * 运行凭证探测流程
396
+ */
397
+ async function runProbeFlow(params: {
398
+ cfg: OpenClawConfig
399
+ prompter: WizardPrompter
400
+ }): Promise<OpenClawConfig> {
401
+ const workclawCfg = params.cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
402
+ const resolvedCredentials = inspectWorkclawCredentials(workclawCfg)
403
+
404
+ if (resolvedCredentials) {
405
+ try {
406
+ const probeResult = await resolvedCredentials()
407
+ params.prompter.note(
408
+ `智小途连接测试成功! ${probeResult.botName ? `Bot名称: ${probeResult.botName}` : ''}`,
409
+ '连接测试',
410
+ )
411
+ }
412
+ catch {
413
+ params.prompter.note('智小途连接测试失败,请检查配置。', '连接测试')
414
+ }
415
+ }
416
+
417
+ return params.cfg
418
+ }
419
+
420
+ export { workclawSetupAdapter } from './setup-core.js'
421
+
422
+ export const workclawSetupWizard: ChannelSetupWizard = {
423
+ channel,
424
+ resolveAccountIdForConfigure: ({ accountOverride, defaultAccountId, cfg }) =>
425
+ (typeof accountOverride === 'string' && accountOverride.trim()
426
+ ? accountOverride.trim()
427
+ : undefined)
428
+ ?? resolveDefaultWorkclawAccountId(cfg)
429
+ ?? defaultAccountId,
430
+ resolveShouldPromptAccountIds: () => false,
431
+ status: {
432
+ configuredLabel: '已配置',
433
+ unconfiguredLabel: '需要配置',
434
+ configuredHint: '已配置',
435
+ unconfiguredHint: '需要凭证',
436
+ configuredScore: 2,
437
+ unconfiguredScore: 0,
438
+ resolveConfigured: ({ cfg }) => isWorkclawConfigured(cfg),
439
+ resolveStatusLines: async ({ cfg, configured }) => {
440
+ const workclawCfg = cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
441
+ const resolvedCredentials = inspectWorkclawCredentials(workclawCfg)
442
+ let probeResult = null
443
+ if (configured && resolvedCredentials) {
444
+ try {
445
+ probeResult = await resolvedCredentials()
446
+ }
447
+ catch {}
448
+ }
449
+ if (!configured) {
450
+ return ['智小途: 需要 App Key 和 App Secret']
451
+ }
452
+ if (probeResult?.ok) {
453
+ return [`智小途: 已连接${probeResult.botName ? ` (${probeResult.botName})` : ''}`]
454
+ }
455
+ return ['智小途: 已配置 (连接未验证)']
456
+ },
457
+ },
458
+
459
+ prepare: async ({ cfg, credentialValues }) => {
460
+ const alreadyConfigured = isWorkclawConfigured(cfg)
461
+
462
+ if (alreadyConfigured) {
463
+ return {
464
+ credentialValues: { ...credentialValues, _flow: 'edit' },
465
+ }
466
+ }
467
+
468
+ return {
469
+ credentialValues: { ...credentialValues, _flow: 'new' },
470
+ }
471
+ },
472
+
473
+ credentials: [],
474
+
475
+ finalize: async ({ cfg, prompter, options, credentialValues }) => {
476
+ const flow = credentialValues._flow ?? 'new'
477
+
478
+ if (flow === 'edit') {
479
+ const result = await runEditFlow({ cfg, prompter, options })
480
+ if (result === null) {
481
+ return { cfg }
482
+ }
483
+ cfg = result.cfg
484
+ }
485
+ else {
486
+ cfg = (await runNewAppFlow({ cfg, prompter, options })).cfg
487
+ }
488
+
489
+ await runProbeFlow({ cfg, prompter })
490
+ return { cfg }
491
+ },
492
+
493
+ disable: cfg =>
494
+ patchTopLevelChannelConfigSection({
495
+ cfg,
496
+ channel,
497
+ patch: { enabled: false },
498
+ }),
499
+ }