@2en/clawly-plugins 1.16.1 → 1.16.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.
package/auto-pair.ts ADDED
@@ -0,0 +1,72 @@
1
+ import type {PluginApi} from './index'
2
+
3
+ const AUTO_APPROVE_CLIENT_IDS = new Set(['openclaw-ios'])
4
+ const POLL_INTERVAL_MS = 3_000
5
+
6
+ type PendingRequest = {
7
+ requestId: string
8
+ deviceId: string
9
+ clientId?: string
10
+ displayName?: string
11
+ platform?: string
12
+ }
13
+
14
+ type PairedDevice = {
15
+ deviceId: string
16
+ displayName?: string
17
+ platform?: string
18
+ }
19
+
20
+ type DevicePairingList = {
21
+ pending: PendingRequest[]
22
+ paired: PairedDevice[]
23
+ }
24
+
25
+ export function registerAutoPair(api: PluginApi) {
26
+ let timer: ReturnType<typeof setInterval> | null = null
27
+ let sdk: {
28
+ listDevicePairing: () => Promise<DevicePairingList>
29
+ approveDevicePairing: (
30
+ requestId: string,
31
+ ) => Promise<{requestId: string; device: PairedDevice} | null>
32
+ } | null = null
33
+
34
+ api.on('gateway_start', async () => {
35
+ try {
36
+ sdk = await import('openclaw/plugin-sdk')
37
+ } catch {
38
+ api.logger.warn('auto-pair: openclaw/plugin-sdk not available, skipping')
39
+ return
40
+ }
41
+
42
+ api.logger.info('auto-pair: started polling for pending pairing requests')
43
+
44
+ timer = setInterval(async () => {
45
+ if (!sdk) return
46
+ try {
47
+ const {pending} = await sdk.listDevicePairing()
48
+ for (const req of pending) {
49
+ if (req.clientId && AUTO_APPROVE_CLIENT_IDS.has(req.clientId)) {
50
+ const result = await sdk.approveDevicePairing(req.requestId)
51
+ if (result) {
52
+ api.logger.info(
53
+ `auto-pair: approved device=${result.device.deviceId} ` +
54
+ `name=${result.device.displayName ?? 'unknown'} ` +
55
+ `platform=${result.device.platform ?? 'unknown'}`,
56
+ )
57
+ }
58
+ }
59
+ }
60
+ } catch (err) {
61
+ api.logger.warn(`auto-pair: poll error: ${String(err)}`)
62
+ }
63
+ }, POLL_INTERVAL_MS)
64
+ })
65
+
66
+ api.on('gateway_stop', () => {
67
+ if (timer) {
68
+ clearInterval(timer)
69
+ timer = null
70
+ }
71
+ })
72
+ }
package/gateway/index.ts CHANGED
@@ -5,6 +5,7 @@ import {registerClawhub2gateway} from './clawhub2gateway'
5
5
  import {registerInject} from './inject'
6
6
  import {registerMemoryBrowser} from './memory'
7
7
  import {registerNotification} from './notification'
8
+ import {registerOfflinePush} from './offline-push'
8
9
  import {registerPlugins} from './plugins'
9
10
  import {registerPresence} from './presence'
10
11
 
@@ -17,4 +18,5 @@ export function registerGateway(api: PluginApi) {
17
18
  registerClawhub2gateway(api)
18
19
  registerPlugins(api)
19
20
  registerChannelsConfigure(api)
21
+ registerOfflinePush(api)
20
22
  }
package/gateway/memory.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * - clawly.workspace.get — read a .md file from workspace root
9
9
  */
10
10
 
11
+ import fsSync from 'node:fs'
11
12
  import fs from 'node:fs/promises'
12
13
  import os from 'node:os'
13
14
  import path from 'node:path'
@@ -39,6 +40,37 @@ function coercePluginConfig(api: PluginApi): Record<string, unknown> {
39
40
  return isRecord(api.pluginConfig) ? api.pluginConfig : {}
40
41
  }
41
42
 
43
+ function resolveStateDir(api: PluginApi): string {
44
+ return api.runtime.state?.resolveStateDir?.(process.env) ?? process.env.OPENCLAW_STATE_DIR ?? ''
45
+ }
46
+
47
+ /** Read the default agent's workspace path from openclaw.json (cached). */
48
+ let _cachedAgentWorkspace: string | null | undefined
49
+ function readAgentWorkspace(api: PluginApi): string | null {
50
+ if (_cachedAgentWorkspace !== undefined) return _cachedAgentWorkspace
51
+ try {
52
+ const stateDir = resolveStateDir(api)
53
+ if (!stateDir) {
54
+ _cachedAgentWorkspace = null
55
+ return null
56
+ }
57
+ const raw = fsSync.readFileSync(path.join(stateDir, 'openclaw.json'), 'utf-8')
58
+ const config = JSON.parse(raw)
59
+ const agents = config?.agents?.list
60
+ if (!Array.isArray(agents)) {
61
+ _cachedAgentWorkspace = null
62
+ return null
63
+ }
64
+ const defaultAgent = agents.find((a: any) => a.default) ?? agents[0]
65
+ const ws = typeof defaultAgent?.workspace === 'string' ? defaultAgent.workspace : null
66
+ _cachedAgentWorkspace = ws
67
+ return ws
68
+ } catch {
69
+ _cachedAgentWorkspace = null
70
+ return null
71
+ }
72
+ }
73
+
42
74
  /** Resolve the workspace root directory (without /memory suffix). */
43
75
  function resolveWorkspaceRoot(api: PluginApi, profile?: string): string {
44
76
  const cfg = coercePluginConfig(api)
@@ -46,7 +78,9 @@ function resolveWorkspaceRoot(api: PluginApi, profile?: string): string {
46
78
  if (configPath) return path.dirname(configPath) // strip /memory if configured
47
79
 
48
80
  const baseDir =
49
- process.env.OPENCLAW_WORKSPACE ?? path.join(os.homedir(), '.openclaw', 'workspace')
81
+ process.env.OPENCLAW_WORKSPACE ??
82
+ readAgentWorkspace(api) ??
83
+ path.join(os.homedir(), '.openclaw', 'workspace')
50
84
  if (profile && profile !== 'main') {
51
85
  const parentDir = path.dirname(baseDir)
52
86
  const baseName = path.basename(baseDir)
@@ -0,0 +1,149 @@
1
+ import {afterEach, beforeEach, describe, expect, mock, test} from 'bun:test'
2
+ import type {PluginApi} from '../index'
3
+ import {PUSH_COOLDOWN_S, _resetCooldowns, registerOfflinePush} from './offline-push'
4
+
5
+ // ── Mocks ────────────────────────────────────────────────────────
6
+
7
+ let mockOnline = false
8
+ let mockPushSent = true
9
+
10
+ mock.module('./presence', () => ({
11
+ isClientOnline: async () => mockOnline,
12
+ }))
13
+
14
+ mock.module('./notification', () => ({
15
+ sendPushNotification: async () => mockPushSent,
16
+ }))
17
+
18
+ // ── Helpers ──────────────────────────────────────────────────────
19
+
20
+ function createMockApi(): {
21
+ api: PluginApi
22
+ logs: {level: string; msg: string}[]
23
+ handlers: Map<string, (event: Record<string, unknown>) => Promise<void>>
24
+ } {
25
+ const logs: {level: string; msg: string}[] = []
26
+ const handlers = new Map<string, (event: Record<string, unknown>) => Promise<void>>()
27
+ const api = {
28
+ id: 'test',
29
+ name: 'test',
30
+ logger: {
31
+ info: (msg: string) => logs.push({level: 'info', msg}),
32
+ warn: (msg: string) => logs.push({level: 'warn', msg}),
33
+ error: (msg: string) => logs.push({level: 'error', msg}),
34
+ },
35
+ on: (hookName: string, handler: (...args: any[]) => any) => {
36
+ handlers.set(hookName, handler as any)
37
+ },
38
+ } as unknown as PluginApi
39
+ return {api, logs, handlers}
40
+ }
41
+
42
+ // ── Tests ────────────────────────────────────────────────────────
43
+
44
+ beforeEach(() => {
45
+ mockOnline = false
46
+ mockPushSent = true
47
+ _resetCooldowns()
48
+ })
49
+
50
+ describe('offline-push', () => {
51
+ test('sends push when client is offline', async () => {
52
+ const {api, logs, handlers} = createMockApi()
53
+ registerOfflinePush(api)
54
+
55
+ const handler = handlers.get('agent_end')!
56
+ await handler({sessionKey: 'sess-1'})
57
+
58
+ expect(logs).toContainEqual({
59
+ level: 'info',
60
+ msg: expect.stringContaining('notified (session=sess-1)'),
61
+ })
62
+ })
63
+
64
+ test('skips push when client is online', async () => {
65
+ mockOnline = true
66
+ const {api, logs, handlers} = createMockApi()
67
+ registerOfflinePush(api)
68
+
69
+ await handlers.get('agent_end')!({sessionKey: 'sess-1'})
70
+
71
+ expect(logs.filter((l) => l.msg.includes('notified'))).toHaveLength(0)
72
+ expect(logs.filter((l) => l.msg.includes('skipped'))).toHaveLength(0)
73
+ })
74
+
75
+ test('respects per-session cooldown', async () => {
76
+ const {api, logs, handlers} = createMockApi()
77
+ registerOfflinePush(api)
78
+
79
+ const handler = handlers.get('agent_end')!
80
+
81
+ // First call — should send
82
+ await handler({sessionKey: 'sess-1'})
83
+ expect(logs.filter((l) => l.msg.includes('notified'))).toHaveLength(1)
84
+
85
+ // Second call same session — should be cooldown-skipped
86
+ await handler({sessionKey: 'sess-1'})
87
+ expect(logs).toContainEqual({
88
+ level: 'info',
89
+ msg: expect.stringContaining('skipped (cooldown, session=sess-1)'),
90
+ })
91
+ })
92
+
93
+ test('different sessions have independent cooldowns', async () => {
94
+ const {api, logs, handlers} = createMockApi()
95
+ registerOfflinePush(api)
96
+
97
+ const handler = handlers.get('agent_end')!
98
+
99
+ await handler({sessionKey: 'sess-1'})
100
+ await handler({sessionKey: 'sess-2'})
101
+
102
+ const notified = logs.filter((l) => l.msg.includes('notified'))
103
+ expect(notified).toHaveLength(2)
104
+ expect(notified[0].msg).toContain('sess-1')
105
+ expect(notified[1].msg).toContain('sess-2')
106
+ })
107
+
108
+ test('uses __global__ key when sessionKey is missing', async () => {
109
+ const {api, logs, handlers} = createMockApi()
110
+ registerOfflinePush(api)
111
+
112
+ const handler = handlers.get('agent_end')!
113
+ await handler({})
114
+ await handler({})
115
+
116
+ expect(logs).toContainEqual({
117
+ level: 'info',
118
+ msg: expect.stringContaining('notified (session=unknown)'),
119
+ })
120
+ expect(logs).toContainEqual({
121
+ level: 'info',
122
+ msg: expect.stringContaining('skipped (cooldown, session=__global__)'),
123
+ })
124
+ })
125
+
126
+ test('does not update cooldown when push is not sent', async () => {
127
+ mockPushSent = false
128
+ const {api, logs, handlers} = createMockApi()
129
+ registerOfflinePush(api)
130
+
131
+ const handler = handlers.get('agent_end')!
132
+
133
+ // Push returns false (e.g. no token) — cooldown should NOT be set
134
+ await handler({sessionKey: 'sess-1'})
135
+ expect(logs.filter((l) => l.msg.includes('notified'))).toHaveLength(0)
136
+
137
+ // Second call should NOT be cooldown-skipped since first wasn't sent
138
+ mockPushSent = true
139
+ await handler({sessionKey: 'sess-1'})
140
+ expect(logs).toContainEqual({
141
+ level: 'info',
142
+ msg: expect.stringContaining('notified (session=sess-1)'),
143
+ })
144
+ })
145
+
146
+ test('exports PUSH_COOLDOWN_S as 30', () => {
147
+ expect(PUSH_COOLDOWN_S).toBe(30)
148
+ })
149
+ })
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Offline push notification on agent_end — sends a push notification
3
+ * when an agent run completes and the mobile client is disconnected.
4
+ *
5
+ * Hook: agent_end → check presence → send Expo push if offline
6
+ *
7
+ * Avoids double-push with clawly.agent.send (which pushes at dispatch
8
+ * time for cron/external triggers) via a 30-second cooldown window.
9
+ */
10
+
11
+ import type {PluginApi} from '../index'
12
+ import {sendPushNotification} from './notification'
13
+ import {isClientOnline} from './presence'
14
+
15
+ /** Minimum seconds between consecutive push notifications per session. */
16
+ export const PUSH_COOLDOWN_S = 30
17
+
18
+ /** Per-session cooldown tracker. Key = sessionKey (or "__global__" for unknown). */
19
+ const lastPushBySession = new Map<string, number>()
20
+
21
+ export function registerOfflinePush(api: PluginApi) {
22
+ api.on('agent_end', async (event: Record<string, unknown>) => {
23
+ try {
24
+ // Skip if client is still connected — they got the response in real-time.
25
+ const online = await isClientOnline()
26
+ if (online) return
27
+
28
+ const sessionKey = typeof event.sessionKey === 'string' ? event.sessionKey : undefined
29
+ const cooldownKey = sessionKey ?? '__global__'
30
+
31
+ // Cooldown: skip if a push was sent recently for this session
32
+ // (e.g. by clawly.agent.send).
33
+ const now = Date.now() / 1000
34
+ const lastPush = lastPushBySession.get(cooldownKey) ?? 0
35
+ if (now - lastPush < PUSH_COOLDOWN_S) {
36
+ api.logger.info(`offline-push: skipped (cooldown, session=${cooldownKey})`)
37
+ return
38
+ }
39
+
40
+ const sent = await sendPushNotification(
41
+ {
42
+ body: 'Your response is ready',
43
+ data: {
44
+ type: 'agent_end',
45
+ ...(sessionKey ? {sessionKey} : {}),
46
+ },
47
+ },
48
+ api,
49
+ )
50
+
51
+ if (sent) {
52
+ lastPushBySession.set(cooldownKey, Date.now() / 1000)
53
+ api.logger.info(`offline-push: notified (session=${sessionKey ?? 'unknown'})`)
54
+ }
55
+ } catch (err) {
56
+ api.logger.error(`offline-push: ${err instanceof Error ? err.message : String(err)}`)
57
+ }
58
+ })
59
+
60
+ api.logger.info('offline-push: registered agent_end hook')
61
+ }
62
+
63
+ /** @internal — exposed for testing */
64
+ export function _resetCooldowns() {
65
+ lastPushBySession.clear()
66
+ }
@@ -0,0 +1,32 @@
1
+ import {describe, expect, test} from 'bun:test'
2
+ import {isOnlineEntry} from './presence'
3
+
4
+ describe('isOnlineEntry', () => {
5
+ test('returns true for reason "foreground"', () => {
6
+ expect(isOnlineEntry({host: 'openclaw-ios', reason: 'foreground'})).toBe(true)
7
+ })
8
+
9
+ test('returns true for reason "connect" (backward compat)', () => {
10
+ expect(isOnlineEntry({host: 'openclaw-ios', reason: 'connect'})).toBe(true)
11
+ })
12
+
13
+ test('returns false for reason "background"', () => {
14
+ expect(isOnlineEntry({host: 'openclaw-ios', reason: 'background'})).toBe(false)
15
+ })
16
+
17
+ test('returns false for reason "disconnect"', () => {
18
+ expect(isOnlineEntry({host: 'openclaw-ios', reason: 'disconnect'})).toBe(false)
19
+ })
20
+
21
+ test('returns false for undefined entry (host not found)', () => {
22
+ expect(isOnlineEntry(undefined)).toBe(false)
23
+ })
24
+
25
+ test('returns false for entry with no reason', () => {
26
+ expect(isOnlineEntry({host: 'openclaw-ios'})).toBe(false)
27
+ })
28
+
29
+ test('returns false for empty entry', () => {
30
+ expect(isOnlineEntry({})).toBe(false)
31
+ })
32
+ })
@@ -19,6 +19,12 @@ interface PresenceEntry {
19
19
  reason?: string
20
20
  }
21
21
 
22
+ /** Returns true if the presence entry indicates the client is actively connected. */
23
+ export function isOnlineEntry(entry: PresenceEntry | undefined): boolean {
24
+ if (!entry) return false
25
+ return entry.reason === 'foreground' || entry.reason === 'connect'
26
+ }
27
+
22
28
  /**
23
29
  * Shells out to `openclaw gateway call system-presence` and checks
24
30
  * whether the given host has a non-"disconnect" entry.
@@ -29,8 +35,7 @@ export async function isClientOnline(host = DEFAULT_HOST): Promise<boolean> {
29
35
  const jsonStr = stripCliLogs(result.stdout)
30
36
  const entries: PresenceEntry[] = JSON.parse(jsonStr)
31
37
  const entry = entries.find((e) => e.host === host)
32
- if (!entry) return false
33
- return entry.reason === 'connect'
38
+ return isOnlineEntry(entry)
34
39
  } catch {
35
40
  return false
36
41
  }
package/index.ts CHANGED
@@ -24,8 +24,11 @@
24
24
  * Hooks:
25
25
  * - tool_result_persist — copies TTS audio to persistent outbound directory
26
26
  * - before_tool_call — enforces delivery fields on cron.create
27
+ * - agent_end — sends push notification when client is offline
28
+ * - gateway_start — auto-approves device pairing for Clawly mobile clients (clientId: openclaw-ios)
27
29
  */
28
30
 
31
+ import {registerAutoPair} from './auto-pair'
29
32
  import {registerCalendar} from './calendar'
30
33
  import {registerClawlyCronChannel} from './channel'
31
34
  import {registerCommands} from './command'
@@ -115,6 +118,7 @@ export default {
115
118
  registerClawlyCronChannel(api)
116
119
  registerCronHook(api)
117
120
  registerGateway(api)
121
+ registerAutoPair(api)
118
122
  setupModelGateway(api)
119
123
 
120
124
  // Email & calendar (optional — requires skillGatewayBaseUrl + skillGatewayToken in config)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@2en/clawly-plugins",
3
- "version": "1.16.1",
3
+ "version": "1.16.2",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "repository": {
@@ -17,13 +17,13 @@
17
17
  "lib",
18
18
  "tools",
19
19
  "index.ts",
20
+ "auto-pair.ts",
20
21
  "calendar.ts",
21
22
  "channel.ts",
22
23
  "cron-hook.ts",
23
24
  "email.ts",
24
25
  "gateway-fetch.ts",
25
26
  "outbound.ts",
26
- "auto-pair.ts",
27
27
  "model-gateway-setup.ts",
28
28
  "openclaw.plugin.json"
29
29
  ],