openclaw-beakdrop 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +46 -2
- package/dist/index.js +422 -0
- package/openclaw.plugin.json +60 -0
- package/package.json +37 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# openclaw-beakdrop
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An OpenClaw Gateway plugin. It keeps one connection per agent identity to a Beakdrop mailbox
|
|
4
|
+
(`GET /api/wake/events`, see [PROTOCOL.md](../PROTOCOL.md)) and, when mail arrives, starts a turn for that
|
|
5
|
+
agent in session `msg:<thread_id>`. The agent reads the thread with the mailbox's own MCP server (`msg`).
|
|
6
|
+
|
|
7
|
+
- Mail from outside senders (`external: true`) never starts a turn; it waits for a person.
|
|
8
|
+
- A turn counts as done once OpenClaw accepts it. OpenClaw resumes interrupted turns after a restart itself.
|
|
9
|
+
- The cursor and pending work live in `<OpenClaw state dir>/beakdrop/openclaw-beakdrop.json`, so updates keep them.
|
|
10
|
+
|
|
11
|
+
## Install and update
|
|
12
|
+
|
|
13
|
+
Install an exact version; the same command updates a running Gateway:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
openclaw plugins install npm:openclaw-beakdrop@0.1.0 --pin --force --accept-capabilities
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`openclaw plugins update` only runs while the Gateway is stopped, so it is not used.
|
|
20
|
+
|
|
21
|
+
## Configure
|
|
22
|
+
|
|
23
|
+
`plugins.entries.openclaw-beakdrop.config`:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"url": "https://mail.example.com",
|
|
28
|
+
"identities": [
|
|
29
|
+
{ "agent": "ada", "token": { "source": "env", "provider": "default", "id": "BEAKDROP_ADA_TOKEN" } }
|
|
30
|
+
]
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- `agent` is both the mailbox identity and the OpenClaw `agentId`.
|
|
35
|
+
- `token` is that identity's mailbox token; use a SecretRef.
|
|
36
|
+
- The agent also needs the mailbox MCP server configured as `msg`.
|
|
37
|
+
- A token that cannot be resolved stops only this plugin (logged as `not started`), not the Gateway.
|
|
38
|
+
|
|
39
|
+
## Develop
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
npm install
|
|
43
|
+
npm run check && npm test
|
|
44
|
+
npm run build # writes dist/index.js (bundles ../core); commit it with each release
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Requires Node 22 or newer; the build uses Bun.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
// ../core/src/index.ts
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from "node:fs";
|
|
7
|
+
import { dirname } from "node:path";
|
|
8
|
+
var PROTOCOL_VERSION = 1;
|
|
9
|
+
var RETRY_DELAYS_MS = [60000, 5 * 60000, 15 * 60000];
|
|
10
|
+
var NET_BACKOFF_MS = [1000, 2000, 5000, 1e4, 30000];
|
|
11
|
+
var CONFLICT_BACKOFF_MS = [2000, 5000, 15000, 60000];
|
|
12
|
+
var AUTH_BACKOFF_MS = 5 * 60000;
|
|
13
|
+
var WATCHDOG_MS = 60000;
|
|
14
|
+
var HEALTHY_STREAM_MS = 30000;
|
|
15
|
+
var consoleLog = {
|
|
16
|
+
info: (m, f) => console.log(`[beakdrop] ${m}`, f ?? ""),
|
|
17
|
+
warn: (m, f) => console.warn(`[beakdrop] ${m}`, f ?? ""),
|
|
18
|
+
error: (m, f) => console.error(`[beakdrop] ${m}`, f ?? "")
|
|
19
|
+
};
|
|
20
|
+
function loadState(file, log = consoleLog) {
|
|
21
|
+
let raw;
|
|
22
|
+
try {
|
|
23
|
+
raw = readFileSync(file, "utf8");
|
|
24
|
+
} catch {
|
|
25
|
+
return { version: 1, identities: {} };
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const s = JSON.parse(raw);
|
|
29
|
+
if (s && s.version === 1 && s.identities && typeof s.identities === "object")
|
|
30
|
+
return s;
|
|
31
|
+
} catch {}
|
|
32
|
+
log.warn("state file unreadable, starting empty", { file });
|
|
33
|
+
return { version: 1, identities: {} };
|
|
34
|
+
}
|
|
35
|
+
function saveState(file, state) {
|
|
36
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
37
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
38
|
+
const fd = openSync(tmp, "w", 384);
|
|
39
|
+
try {
|
|
40
|
+
writeSync(fd, JSON.stringify(state));
|
|
41
|
+
fsyncSync(fd);
|
|
42
|
+
} finally {
|
|
43
|
+
closeSync(fd);
|
|
44
|
+
}
|
|
45
|
+
renameSync(tmp, file);
|
|
46
|
+
}
|
|
47
|
+
var jitter = (ms) => Math.round(ms * (0.8 + Math.random() * 0.4));
|
|
48
|
+
function sleep(ms, signal) {
|
|
49
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
50
|
+
if (signal.aborted)
|
|
51
|
+
return Promise.resolve();
|
|
52
|
+
const t = setTimeout(done, ms);
|
|
53
|
+
function done() {
|
|
54
|
+
clearTimeout(t);
|
|
55
|
+
signal.removeEventListener("abort", done);
|
|
56
|
+
resolve();
|
|
57
|
+
}
|
|
58
|
+
signal.addEventListener("abort", done);
|
|
59
|
+
return promise;
|
|
60
|
+
}
|
|
61
|
+
function startWake(options) {
|
|
62
|
+
const o = options;
|
|
63
|
+
const log = o.log ?? consoleLog;
|
|
64
|
+
const maxConcurrent = o.maxConcurrent ?? 2;
|
|
65
|
+
const rate = o.rate ?? { max: 20, windowMs: 10 * 60000 };
|
|
66
|
+
const conversation = o.conversation ?? ((e) => e.route ?? e.thread_id);
|
|
67
|
+
const base = o.url.replace(/\/+$/, "");
|
|
68
|
+
const instance = randomUUID();
|
|
69
|
+
const state = loadState(o.stateFile, log);
|
|
70
|
+
for (const { agent } of o.identities)
|
|
71
|
+
state.identities[agent] ??= { queue: [] };
|
|
72
|
+
for (const [agent, ids] of Object.entries(state.identities)) {
|
|
73
|
+
ids.queue = ids.queue.filter((it) => {
|
|
74
|
+
if (!it.running)
|
|
75
|
+
return true;
|
|
76
|
+
it.running = false;
|
|
77
|
+
it.attempts++;
|
|
78
|
+
if (it.attempts <= RETRY_DELAYS_MS.length)
|
|
79
|
+
return true;
|
|
80
|
+
log.error("dropping event after retries", { agent, event: it.event.id, thread: it.event.thread_id });
|
|
81
|
+
return false;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const save = () => {
|
|
85
|
+
try {
|
|
86
|
+
saveState(o.stateFile, state);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
log.error("state file write failed", { file: o.stateFile, error: String(e) });
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
save();
|
|
92
|
+
const connAbort = new AbortController;
|
|
93
|
+
const runAbort = new AbortController;
|
|
94
|
+
let draining = false;
|
|
95
|
+
let active = 0;
|
|
96
|
+
const busy = new Set;
|
|
97
|
+
const starts = new Map;
|
|
98
|
+
const running = new Set;
|
|
99
|
+
let idle;
|
|
100
|
+
function enqueue(agent, ev) {
|
|
101
|
+
const ids = state.identities[agent];
|
|
102
|
+
ids.cursor = ev.id;
|
|
103
|
+
if (ev.type === "thread.done") {
|
|
104
|
+
ids.queue = ids.queue.filter((it) => it.running || it.event.thread_id !== ev.thread_id);
|
|
105
|
+
} else if (ev.type === "message.created" || ev.type === "thread.assigned") {
|
|
106
|
+
const waiting = ids.queue.find((it) => !it.running && it.event.thread_id === ev.thread_id);
|
|
107
|
+
if (waiting)
|
|
108
|
+
Object.assign(waiting, { event: ev, attempts: 0, nextAt: Date.now() });
|
|
109
|
+
else
|
|
110
|
+
ids.queue.push({ event: ev, attempts: 0, nextAt: Date.now() });
|
|
111
|
+
}
|
|
112
|
+
save();
|
|
113
|
+
pump();
|
|
114
|
+
}
|
|
115
|
+
function pump() {
|
|
116
|
+
if (draining || runAbort.signal.aborted)
|
|
117
|
+
return;
|
|
118
|
+
const now = Date.now();
|
|
119
|
+
for (const [agent, ids] of Object.entries(state.identities)) {
|
|
120
|
+
const recent = (starts.get(agent) ?? []).filter((t) => now - t < rate.windowMs);
|
|
121
|
+
starts.set(agent, recent);
|
|
122
|
+
for (const it of [...ids.queue].sort((a, b) => a.nextAt - b.nextAt)) {
|
|
123
|
+
if (active >= maxConcurrent)
|
|
124
|
+
return;
|
|
125
|
+
if (recent.length >= rate.max)
|
|
126
|
+
break;
|
|
127
|
+
const key = `${agent}\x00${conversation(it.event)}`;
|
|
128
|
+
if (it.running || it.nextAt > now || busy.has(key))
|
|
129
|
+
continue;
|
|
130
|
+
recent.push(now);
|
|
131
|
+
run(agent, ids, it, key);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function run(agent, ids, it, key) {
|
|
136
|
+
it.running = true;
|
|
137
|
+
active++;
|
|
138
|
+
busy.add(key);
|
|
139
|
+
save();
|
|
140
|
+
const p = (async () => {
|
|
141
|
+
let result;
|
|
142
|
+
try {
|
|
143
|
+
result = await o.trigger(it.event, runAbort.signal);
|
|
144
|
+
} catch (e) {
|
|
145
|
+
log.warn("trigger failed", { agent, event: it.event.id, error: String(e) });
|
|
146
|
+
result = "retry";
|
|
147
|
+
}
|
|
148
|
+
it.running = false;
|
|
149
|
+
if (result === "ok") {
|
|
150
|
+
ids.queue = ids.queue.filter((x) => x !== it);
|
|
151
|
+
} else if (!runAbort.signal.aborted) {
|
|
152
|
+
it.attempts++;
|
|
153
|
+
if (it.attempts > RETRY_DELAYS_MS.length) {
|
|
154
|
+
log.error("dropping event after retries", { agent, event: it.event.id, thread: it.event.thread_id });
|
|
155
|
+
ids.queue = ids.queue.filter((x) => x !== it);
|
|
156
|
+
} else {
|
|
157
|
+
it.nextAt = Date.now() + RETRY_DELAYS_MS[it.attempts - 1];
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
active--;
|
|
161
|
+
busy.delete(key);
|
|
162
|
+
save();
|
|
163
|
+
})();
|
|
164
|
+
running.add(p);
|
|
165
|
+
p.finally(() => {
|
|
166
|
+
running.delete(p);
|
|
167
|
+
if (running.size === 0)
|
|
168
|
+
idle?.();
|
|
169
|
+
pump();
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
async function connect(agent, token) {
|
|
173
|
+
const ac = new AbortController;
|
|
174
|
+
const signal = AbortSignal.any([connAbort.signal, ac.signal]);
|
|
175
|
+
let watchdog = setTimeout(() => ac.abort(), WATCHDOG_MS);
|
|
176
|
+
const kick = () => {
|
|
177
|
+
clearTimeout(watchdog);
|
|
178
|
+
watchdog = setTimeout(() => ac.abort(), WATCHDOG_MS);
|
|
179
|
+
};
|
|
180
|
+
try {
|
|
181
|
+
const cursor = state.identities[agent].cursor;
|
|
182
|
+
const res = await fetch(`${base}/api/wake/events`, {
|
|
183
|
+
headers: {
|
|
184
|
+
Authorization: `Bearer ${token}`,
|
|
185
|
+
Accept: "text/event-stream",
|
|
186
|
+
"X-Wake-Instance": instance,
|
|
187
|
+
"X-Wake-Protocol": String(PROTOCOL_VERSION),
|
|
188
|
+
"X-Wake-Client": o.client,
|
|
189
|
+
...cursor !== undefined ? { "Last-Event-ID": String(cursor) } : {}
|
|
190
|
+
},
|
|
191
|
+
signal
|
|
192
|
+
});
|
|
193
|
+
if (res.status !== 200 || !res.body) {
|
|
194
|
+
const supported = res.headers.get("X-Wake-Protocol-Supported");
|
|
195
|
+
log.warn("wake connect refused", { agent, status: res.status, ...supported ? { supported } : {} });
|
|
196
|
+
await res.body?.cancel().catch(() => {});
|
|
197
|
+
return res.status;
|
|
198
|
+
}
|
|
199
|
+
log.info("wake connected", { agent });
|
|
200
|
+
const reader = res.body.getReader();
|
|
201
|
+
const dec = new TextDecoder;
|
|
202
|
+
let buf = "";
|
|
203
|
+
let id = "";
|
|
204
|
+
let type = "";
|
|
205
|
+
let data = "";
|
|
206
|
+
for (;; ) {
|
|
207
|
+
const { done, value } = await reader.read();
|
|
208
|
+
if (done)
|
|
209
|
+
break;
|
|
210
|
+
kick();
|
|
211
|
+
buf += dec.decode(value, { stream: true });
|
|
212
|
+
const hold = buf.endsWith("\r");
|
|
213
|
+
const lines = (hold ? buf.slice(0, -1) : buf).split(/\r\n|\r|\n/);
|
|
214
|
+
buf = (lines.pop() ?? "") + (hold ? "\r" : "");
|
|
215
|
+
for (const line of lines) {
|
|
216
|
+
if (line === "") {
|
|
217
|
+
if (data && id)
|
|
218
|
+
handleEvent(agent, id, type, data);
|
|
219
|
+
type = data = "";
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (line.startsWith(":"))
|
|
223
|
+
continue;
|
|
224
|
+
const i = line.indexOf(":");
|
|
225
|
+
const field = i < 0 ? line : line.slice(0, i);
|
|
226
|
+
const val = i < 0 ? "" : line.slice(i + 1).replace(/^ /, "");
|
|
227
|
+
if (field === "id")
|
|
228
|
+
id = val;
|
|
229
|
+
else if (field === "event")
|
|
230
|
+
type = val;
|
|
231
|
+
else if (field === "data")
|
|
232
|
+
data = data ? `${data}
|
|
233
|
+
${val}` : val;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return 200;
|
|
237
|
+
} catch (e) {
|
|
238
|
+
if (!connAbort.signal.aborted)
|
|
239
|
+
log.warn("wake connection lost", { agent, error: String(e) });
|
|
240
|
+
return 0;
|
|
241
|
+
} finally {
|
|
242
|
+
clearTimeout(watchdog);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function handleEvent(agent, id, type, data) {
|
|
246
|
+
let ev;
|
|
247
|
+
try {
|
|
248
|
+
ev = { ...JSON.parse(data), id: Number(id) };
|
|
249
|
+
} catch {
|
|
250
|
+
log.warn("bad wake event", { agent, id });
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (!Number.isFinite(ev.id) || type && type !== ev.type || ev.agent !== agent) {
|
|
254
|
+
log.warn("ignoring inconsistent wake event", { agent, id, type });
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
enqueue(agent, ev);
|
|
258
|
+
}
|
|
259
|
+
async function loop(agent, token) {
|
|
260
|
+
await Promise.resolve();
|
|
261
|
+
let failures = 0;
|
|
262
|
+
let conflicts = 0;
|
|
263
|
+
while (!connAbort.signal.aborted) {
|
|
264
|
+
if (o.shouldDrain?.()) {
|
|
265
|
+
drain();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const started = Date.now();
|
|
269
|
+
const status = await connect(agent, token);
|
|
270
|
+
if (connAbort.signal.aborted)
|
|
271
|
+
return;
|
|
272
|
+
let delay;
|
|
273
|
+
if (status === 401 || status === 403 || status === 400) {
|
|
274
|
+
delay = AUTH_BACKOFF_MS;
|
|
275
|
+
} else if (status === 409) {
|
|
276
|
+
delay = CONFLICT_BACKOFF_MS[Math.min(conflicts++, CONFLICT_BACKOFF_MS.length - 1)];
|
|
277
|
+
} else if (status === 200 && Date.now() - started >= HEALTHY_STREAM_MS) {
|
|
278
|
+
failures = conflicts = 0;
|
|
279
|
+
delay = 0;
|
|
280
|
+
} else {
|
|
281
|
+
delay = NET_BACKOFF_MS[Math.min(failures++, NET_BACKOFF_MS.length - 1)];
|
|
282
|
+
}
|
|
283
|
+
if (status === 200)
|
|
284
|
+
conflicts = 0;
|
|
285
|
+
if (delay)
|
|
286
|
+
await sleep(jitter(delay), connAbort.signal);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const { promise: done, resolve: finish } = Promise.withResolvers();
|
|
290
|
+
let finishing;
|
|
291
|
+
function waitIdle() {
|
|
292
|
+
if (running.size === 0)
|
|
293
|
+
return Promise.resolve();
|
|
294
|
+
const w = Promise.withResolvers();
|
|
295
|
+
idle = w.resolve;
|
|
296
|
+
return w.promise;
|
|
297
|
+
}
|
|
298
|
+
function end(abortRuns) {
|
|
299
|
+
draining = true;
|
|
300
|
+
clearInterval(timer);
|
|
301
|
+
connAbort.abort();
|
|
302
|
+
if (abortRuns)
|
|
303
|
+
runAbort.abort();
|
|
304
|
+
finishing ??= (async () => {
|
|
305
|
+
await Promise.all(loops);
|
|
306
|
+
await waitIdle();
|
|
307
|
+
save();
|
|
308
|
+
log.info("wake stopped", { drained: !abortRuns });
|
|
309
|
+
finish();
|
|
310
|
+
})();
|
|
311
|
+
return finishing;
|
|
312
|
+
}
|
|
313
|
+
function drain() {
|
|
314
|
+
if (!draining)
|
|
315
|
+
end(false);
|
|
316
|
+
}
|
|
317
|
+
const timer = setInterval(pump, 1000);
|
|
318
|
+
const loops = o.identities.map(({ agent, token }) => loop(agent, token));
|
|
319
|
+
pump();
|
|
320
|
+
return { stop: () => end(true).then(() => done), done };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// src/index.ts
|
|
324
|
+
var VERSION = "0.1.0";
|
|
325
|
+
var ID = "openclaw-beakdrop";
|
|
326
|
+
function prompt(ev) {
|
|
327
|
+
const what = ev.type === "thread.assigned" ? "指派給你" : "新信";
|
|
328
|
+
return [
|
|
329
|
+
`[Mailbox] 信串 ${ev.thread_id} 有${what}(seq ${ev.seq})。`,
|
|
330
|
+
"請用 msg 的 read 讀這個信串再處理;處理完用 done。",
|
|
331
|
+
"負責人是別人、信裡也沒點名你時,不要動作。"
|
|
332
|
+
].join(`
|
|
333
|
+
`);
|
|
334
|
+
}
|
|
335
|
+
var THREAD_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
336
|
+
function makeTrigger(api, log) {
|
|
337
|
+
return async (ev) => {
|
|
338
|
+
if (ev.external) {
|
|
339
|
+
log.info("external mail, not waking (left unread for a person)", { agent: ev.agent, thread: ev.thread_id });
|
|
340
|
+
return "ok";
|
|
341
|
+
}
|
|
342
|
+
if (!THREAD_ID.test(ev.thread_id) || !Number.isSafeInteger(ev.seq)) {
|
|
343
|
+
log.error("dropping event with unexpected thread id or seq", { agent: ev.agent, event: ev.id });
|
|
344
|
+
return "ok";
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
347
|
+
const r = api.runtime.system.enqueueSessionEvent(prompt(ev), {
|
|
348
|
+
agentId: ev.agent,
|
|
349
|
+
sessionKey: `msg:${ev.thread_id}`,
|
|
350
|
+
createIfMissing: true
|
|
351
|
+
});
|
|
352
|
+
const accepted = await r.accepted;
|
|
353
|
+
if (!accepted?.ok) {
|
|
354
|
+
log.warn("turn not accepted", { agent: ev.agent, thread: ev.thread_id, error: String(accepted?.error) });
|
|
355
|
+
return "retry";
|
|
356
|
+
}
|
|
357
|
+
r.settled.then((s) => s?.status === "failed" && log.warn("turn failed", { agent: ev.agent, thread: ev.thread_id }), () => {});
|
|
358
|
+
return "ok";
|
|
359
|
+
} catch (e) {
|
|
360
|
+
log.warn("enqueue failed", { agent: ev.agent, thread: ev.thread_id, error: String(e) });
|
|
361
|
+
return "retry";
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
function parseConfig(raw) {
|
|
366
|
+
const c = raw;
|
|
367
|
+
if (!c || typeof c.url !== "string" || !/^https?:\/\//.test(c.url))
|
|
368
|
+
return "url must be an http(s) URL";
|
|
369
|
+
if (!Array.isArray(c.identities) || c.identities.length === 0)
|
|
370
|
+
return "identities must list at least one agent";
|
|
371
|
+
for (const i of c.identities) {
|
|
372
|
+
if (typeof i?.agent !== "string" || !i.agent || typeof i.token !== "string" || !i.token) {
|
|
373
|
+
return "each identity needs an agent and a resolved token";
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return c;
|
|
377
|
+
}
|
|
378
|
+
var fieldsLogger = (l) => {
|
|
379
|
+
const fmt = (m, f) => f ? `${m} ${JSON.stringify(f)}` : m;
|
|
380
|
+
return { info: (m, f) => l.info(fmt(m, f)), warn: (m, f) => l.warn(fmt(m, f)), error: (m, f) => l.error(fmt(m, f)) };
|
|
381
|
+
};
|
|
382
|
+
var src_default = {
|
|
383
|
+
id: ID,
|
|
384
|
+
name: "Beakdrop",
|
|
385
|
+
description: "Wakes an agent when mail arrives in its Beakdrop mailbox.",
|
|
386
|
+
register(api) {
|
|
387
|
+
if (api.registrationMode && api.registrationMode !== "full")
|
|
388
|
+
return;
|
|
389
|
+
let handle;
|
|
390
|
+
api.registerService({
|
|
391
|
+
id: ID,
|
|
392
|
+
apiVersion: 2,
|
|
393
|
+
async start(ctx) {
|
|
394
|
+
const log = fieldsLogger(ctx.logger ?? api.logger);
|
|
395
|
+
const cfg = parseConfig(api.pluginConfig);
|
|
396
|
+
if (typeof cfg === "string") {
|
|
397
|
+
log.error(`not started: ${cfg}`);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
handle = startWake({
|
|
401
|
+
url: cfg.url,
|
|
402
|
+
identities: cfg.identities,
|
|
403
|
+
client: `${ID}/${VERSION}`,
|
|
404
|
+
stateFile: join(ctx.stateDir, "beakdrop", `${ID}.json`),
|
|
405
|
+
maxConcurrent: Number.POSITIVE_INFINITY,
|
|
406
|
+
log,
|
|
407
|
+
trigger: makeTrigger(api, log)
|
|
408
|
+
});
|
|
409
|
+
},
|
|
410
|
+
async stop() {
|
|
411
|
+
await handle?.stop();
|
|
412
|
+
handle = undefined;
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
export {
|
|
418
|
+
VERSION,
|
|
419
|
+
src_default as default,
|
|
420
|
+
makeTrigger,
|
|
421
|
+
prompt
|
|
422
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "openclaw-beakdrop",
|
|
3
|
+
"name": "Beakdrop",
|
|
4
|
+
"description": "Wakes an agent when mail arrives in its Beakdrop mailbox.",
|
|
5
|
+
"categories": [
|
|
6
|
+
"other"
|
|
7
|
+
],
|
|
8
|
+
"activation": {
|
|
9
|
+
"onStartup": true
|
|
10
|
+
},
|
|
11
|
+
"configContracts": {
|
|
12
|
+
"secretInputs": {
|
|
13
|
+
"paths": [
|
|
14
|
+
{
|
|
15
|
+
"path": "identities.*.token",
|
|
16
|
+
"expected": "string",
|
|
17
|
+
"ownerKind": "route"
|
|
18
|
+
}
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"configSchema": {
|
|
23
|
+
"type": "object",
|
|
24
|
+
"additionalProperties": false,
|
|
25
|
+
"required": [
|
|
26
|
+
"url",
|
|
27
|
+
"identities"
|
|
28
|
+
],
|
|
29
|
+
"properties": {
|
|
30
|
+
"url": {
|
|
31
|
+
"type": "string",
|
|
32
|
+
"description": "Mailbox base URL, e.g. https://mail.example.com"
|
|
33
|
+
},
|
|
34
|
+
"identities": {
|
|
35
|
+
"type": "array",
|
|
36
|
+
"minItems": 1,
|
|
37
|
+
"items": {
|
|
38
|
+
"type": "object",
|
|
39
|
+
"additionalProperties": false,
|
|
40
|
+
"required": [
|
|
41
|
+
"agent",
|
|
42
|
+
"token"
|
|
43
|
+
],
|
|
44
|
+
"properties": {
|
|
45
|
+
"agent": {
|
|
46
|
+
"type": "string",
|
|
47
|
+
"minLength": 1,
|
|
48
|
+
"description": "Mailbox identity; also the OpenClaw agentId"
|
|
49
|
+
},
|
|
50
|
+
"token": {
|
|
51
|
+
"type": ["string", "object"],
|
|
52
|
+
"minLength": 1,
|
|
53
|
+
"description": "Mailbox token; use a SecretRef"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openclaw-beakdrop",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenClaw Gateway plugin: wakes an agent when mail arrives in its Beakdrop mailbox.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/mics8128/beakdrop-agents.git",
|
|
10
|
+
"directory": "openclaw-beakdrop"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist/index.js",
|
|
14
|
+
"openclaw.plugin.json",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=22"
|
|
20
|
+
},
|
|
21
|
+
"openclaw": {
|
|
22
|
+
"extensions": [
|
|
23
|
+
"./dist/index.js"
|
|
24
|
+
],
|
|
25
|
+
"compat": {
|
|
26
|
+
"pluginApi": ">=2026.11.10",
|
|
27
|
+
"minGatewayVersion": "2026.11.10"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "bun build src/index.ts --target=node --format=esm --outfile dist/index.js",
|
|
32
|
+
"check": "tsc --noEmit -p .",
|
|
33
|
+
"test": "node --test src/"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/node": "^22.20.7",
|
|
37
|
+
"typescript": "^5.9.3"
|
|
38
|
+
}
|
|
39
|
+
}
|