@kagura-agent/atlas-openclaw 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/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # Atlas channel for OpenClaw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Atlas owns conversations, selected canvas context, task permissions and native canvas results. OpenClaw owns model execution. The plugin follows Cove's channel registration and outbound connection pattern.
4
+
5
+ ## Install
6
+
7
+ Requires OpenClaw 2026.10.5 or newer and Node.js 22.13 or newer. On the machine running OpenClaw:
8
+
9
+ ```sh
10
+ openclaw plugins install @kagura-agent/atlas-openclaw
11
+ ```
12
+
13
+ In Atlas, choose **Connect AI tools → OpenClaw** from the account menu. The star's first-use prompt and chat's Connections action open the same setup page. Choose **Create connection** and save the displayed configuration. Merge the generated `channels.atlas` configuration into OpenClaw's configuration. Preserve other channels and plugin entries. Enable the installed `atlas` plugin; if `plugins.allow` is configured, add `atlas` to that list. Set `agentId` to an existing OpenClaw agent with a working model configuration.
14
+
15
+ Restart the OpenClaw gateway after installation. Atlas shows **Connected** when the authenticated socket connects. Select the connection and send a message.
16
+
17
+ Use the public HTTPS Atlas origin when OpenClaw runs on another machine. Forward `/agent-worker` with WebSocket upgrades and `/api/agent-worker/` to the same Atlas server. HTTP is accepted only for loopback development, including an SSH tunnel. Do not expose a development HTTP port on the network.
18
+
19
+ Tokens belong in OpenClaw's private configuration, never in messages, source files or shared installation snippets. Maintainer documentation (repository access required): [Connect agents](https://github.com/kagura-chen/atlas/blob/main/docs/product/AI-TOOLS.md#在画板中与-openclaw-对话) and [Current gaps](https://github.com/kagura-chen/atlas/blob/main/docs/CURRENT-GAPS.md).
20
+
21
+ ## Publish (maintainers)
22
+
23
+ The [Publish OpenClaw plugin workflow](https://github.com/kagura-chen/atlas/actions/workflows/publish-openclaw.yml) packs once, tests the archive in clean OpenClaw installations (the minimum supported version and npm's latest version), and publishes that same archive. Pull requests only verify; manual runs publish only when `publish` is selected and the branch is `main`. Leave `publish` off to download the `atlas-openclaw-package` artifact without publishing.
24
+
25
+ For the first release, create a short-lived granular npm token using the `kagura-agent` account. Grant read/write publication access to the `@kagura-agent` scope and enable **Bypass 2FA** for non-interactive CI publication. Save it as the repository Actions secret `NPM_BOOTSTRAP_TOKEN`. Run the workflow on `main`, select `publish`, and choose `bootstrap-token` authentication. This job uses the token without requesting an OIDC identity.
26
+
27
+ After the package exists, configure its npm **Trusted Publisher** for GitHub Actions:
28
+
29
+ - Organization or user: `kagura-chen`
30
+ - Repository: `atlas`
31
+ - Workflow filename: `publish-openclaw.yml`
32
+ - Environment name: leave empty (this workflow does not use an environment)
33
+ - Allow direct publication with `npm publish` if the settings offer allowed actions.
34
+
35
+ Revoke the bootstrap token in npm and delete `NPM_BOOTSTRAP_TOKEN` from GitHub after configuring the trusted publisher. Subsequent releases select `trusted-publisher` (the default) and use OIDC with no npm token in GitHub Secrets. Provenance is disabled because the source repository is private. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
36
+
37
+ Increase the committed package version before another release. An existing version is not overwritten; registry or authentication errors fail the run. After publishing, verify installation from npm before shipping the corresponding Atlas setup instructions.
38
+
39
+ ## Design
40
+
41
+ WebSocket notifications wake the worker; reconnecting and periodic server notifications refresh the queue. Finishing a run immediately checks for the next queued task. Short renewable run leases prevent a lost worker from silently reexecuting work. Tool writes use stable request IDs; canvas changes, run updates and receipts commit in the same SQLite transaction. Lost HTTP responses can be retried without duplicating writes. Final settlement is idempotent too.
42
+
43
+ Each turn gets a fresh OpenClaw session with Atlas's completed conversation history. Cancelled and failed prompts are excluded so runtime transcript replay cannot revive them. The runtime tool allowlist is `atlas_board`; tool instances exist only for the active run's session and cannot choose another board or acquire a new scope. Stop aborts the dispatcher; only after it returns does the plugin report settlement. OpenClaw error payloads are failures, not successful replies.
44
+
45
+ Maintainer source (repository access required): [Channel registration](https://github.com/kagura-chen/atlas/blob/main/plugins/openclaw-atlas/index.mjs) · [Worker and scoped tool](https://github.com/kagura-chen/atlas/blob/main/plugins/openclaw-atlas/worker.mjs) · [Manifest](https://github.com/kagura-chen/atlas/blob/main/plugins/openclaw-atlas/openclaw.plugin.json) · [Atlas service](https://github.com/kagura-chen/atlas/blob/main/server/agent-chat.ts) · [Scope validation](https://github.com/kagura-chen/atlas/blob/main/server/agent-scope.ts) · [HTTP and gateway](https://github.com/kagura-chen/atlas/blob/main/server/agent-chat-api.ts).
46
+
47
+ Reference: [Cove channel entry](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/index.ts), [channel](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/channel.ts), [dispatch](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/dispatch.ts). The installed SDK requires `contracts.tools` in the manifest; its reply dispatcher replaces Cove's older `runInboundReplyTurn` entry point.
package/index.mjs ADDED
@@ -0,0 +1,43 @@
1
+ import {
2
+ createChatChannelPlugin,
3
+ defineChannelPluginEntry,
4
+ } from "openclaw/plugin-sdk/channel-core";
5
+ import { boardTool, startAccount } from "./worker.mjs";
6
+
7
+ const plugin = createChatChannelPlugin({
8
+ base: {
9
+ id: "atlas",
10
+ meta: {
11
+ id: "atlas",
12
+ label: "Atlas",
13
+ selectionLabel: "Atlas canvas",
14
+ docsPath: "/channels/atlas",
15
+ blurb: "External agent collaboration on an Atlas canvas",
16
+ },
17
+ capabilities: { chatTypes: ["direct"] },
18
+ config: {
19
+ listAccountIds: (cfg) => (cfg.channels?.atlas ? ["default"] : []),
20
+ defaultAccountId: () => "default",
21
+ resolveAccount: (cfg) => ({
22
+ accountId: "default",
23
+ enabled: true,
24
+ ...cfg.channels?.atlas,
25
+ }),
26
+ isConfigured: (account) =>
27
+ Boolean(account.baseUrl && account.token && account.agentId),
28
+ isEnabled: (account) => account.enabled !== false,
29
+ },
30
+ gateway: { startAccount },
31
+ },
32
+ });
33
+
34
+ export default defineChannelPluginEntry({
35
+ id: "atlas",
36
+ name: "Atlas",
37
+ description: "External agents with scoped canvas tools",
38
+ plugin,
39
+ registerFull: (api) =>
40
+ api.registerTool((context) => boardTool(context), {
41
+ names: ["atlas_board"],
42
+ }),
43
+ });
@@ -0,0 +1,29 @@
1
+ {
2
+ "id": "atlas",
3
+ "kind": "channel",
4
+ "name": "Atlas",
5
+ "description": "External agent conversations and scoped canvas editing",
6
+ "channels": ["atlas"],
7
+ "contracts": { "tools": ["atlas_board"] },
8
+ "activation": { "onStartup": true },
9
+ "configSchema": {
10
+ "type": "object",
11
+ "additionalProperties": false,
12
+ "properties": {}
13
+ },
14
+ "channelConfigs": {
15
+ "atlas": {
16
+ "schema": {
17
+ "type": "object",
18
+ "additionalProperties": false,
19
+ "properties": {
20
+ "enabled": { "type": "boolean" },
21
+ "baseUrl": { "type": "string" },
22
+ "token": { "type": "string" },
23
+ "agentId": { "type": "string" }
24
+ }
25
+ },
26
+ "uiHints": { "token": { "sensitive": true } }
27
+ }
28
+ }
29
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@kagura-agent/atlas-openclaw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Connect an external OpenClaw agent to Atlas conversations and canvas tools",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/kagura-chen/atlas.git",
8
+ "directory": "plugins/openclaw-atlas"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "registry": "https://registry.npmjs.org/"
13
+ },
14
+ "type": "module",
15
+ "main": "index.mjs",
16
+ "files": [
17
+ "index.mjs",
18
+ "worker.mjs",
19
+ "openclaw.plugin.json",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=22.13"
24
+ },
25
+ "dependencies": {
26
+ "ws": "^8.18.3"
27
+ },
28
+ "peerDependencies": {
29
+ "openclaw": ">=2026.10.5"
30
+ },
31
+ "openclaw": {
32
+ "extensions": [
33
+ "./index.mjs"
34
+ ],
35
+ "channel": {
36
+ "id": "atlas",
37
+ "label": "Atlas",
38
+ "selectionLabel": "Atlas canvas",
39
+ "docsPath": "/channels/atlas",
40
+ "blurb": "Work on an Atlas canvas from OpenClaw"
41
+ }
42
+ }
43
+ }
package/worker.mjs ADDED
@@ -0,0 +1,323 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { setTimeout as sleep } from "node:timers/promises";
3
+ import WebSocket from "ws";
4
+
5
+ const sessionRegistry = Symbol.for("atlas.openclaw.active-runs");
6
+ export const sessions = (globalThis[sessionRegistry] ||= new Map());
7
+ export function connection(account) {
8
+ const base = new URL(account.baseUrl);
9
+ if (
10
+ base.username ||
11
+ base.password ||
12
+ base.pathname !== "/" ||
13
+ base.search ||
14
+ base.hash ||
15
+ !["http:", "https:"].includes(base.protocol)
16
+ )
17
+ throw new Error("Atlas requires an HTTP(S) origin");
18
+ if (
19
+ base.protocol === "http:" &&
20
+ !["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)
21
+ )
22
+ throw new Error("Use HTTPS for remote Atlas connections");
23
+ return base.origin;
24
+ }
25
+ export function client(account) {
26
+ const base = connection(account);
27
+ return async (path, body) => {
28
+ const response = await fetch(`${base}/api/agent-worker/${path}`, {
29
+ method: body === undefined ? "GET" : "POST",
30
+ headers: {
31
+ Authorization: `Bearer ${account.token}`,
32
+ "Content-Type": "application/json",
33
+ },
34
+ ...(body !== undefined && { body: JSON.stringify(body) }),
35
+ signal: AbortSignal.timeout(15000),
36
+ redirect: "error",
37
+ });
38
+ const value = await response.json();
39
+ if (!response.ok)
40
+ throw Object.assign(
41
+ new Error(value.error || `Atlas request failed (${response.status})`),
42
+ { status: response.status },
43
+ );
44
+ return value;
45
+ };
46
+ }
47
+
48
+ export function boardTool(context) {
49
+ const run = sessions.get(context.sessionKey);
50
+ if (!run) return null;
51
+ return {
52
+ name: "atlas_board",
53
+ label: "Atlas board",
54
+ description:
55
+ "Read the current Atlas run context, get the canvas composer skill, create or update native canvas objects, or ask the user a structured question. Only this run's selected objects and newly created objects are writable. Read skill before writing. Never use another tool to access Atlas.",
56
+ parameters: {
57
+ type: "object",
58
+ additionalProperties: false,
59
+ required: ["action"],
60
+ properties: {
61
+ action: {
62
+ type: "string",
63
+ enum: ["skill", "read", "create", "update", "ask"],
64
+ },
65
+ svg: {
66
+ type: "string",
67
+ description: "Atlas Canvas Composer SVG for create/update",
68
+ },
69
+ question: { type: "string" },
70
+ options: { type: "array", items: { type: "string" }, maxItems: 6 },
71
+ },
72
+ },
73
+ async execute(callId, args) {
74
+ run.controller.signal.throwIfAborted();
75
+ if (sessions.get(context.sessionKey) !== run)
76
+ throw new Error("Atlas run is no longer active");
77
+ const requestId = `tool:${callId}`;
78
+ let result;
79
+ for (let attempt = 0; attempt < 3; attempt++) {
80
+ try {
81
+ result = await run.post("tool", { ...args, requestId });
82
+ break;
83
+ } catch (e) {
84
+ if (e.status || attempt === 2) throw e;
85
+ await sleep(500, undefined, { signal: run.controller.signal });
86
+ }
87
+ }
88
+ if (args.action === "ask") {
89
+ for (;;) {
90
+ await sleep(1000, undefined, { signal: run.controller.signal });
91
+ const state = await run.heartbeat();
92
+ if (
93
+ state.question?.id === result.questionId &&
94
+ state.question.answer !== undefined
95
+ )
96
+ return {
97
+ content: [
98
+ {
99
+ type: "text",
100
+ text: JSON.stringify({ answer: state.question.answer }),
101
+ },
102
+ ],
103
+ };
104
+ }
105
+ }
106
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
107
+ },
108
+ };
109
+ }
110
+
111
+ export async function executeRun(ctx, request, id) {
112
+ const job = await request(`runs/${encodeURIComponent(id)}/claim`, {});
113
+ const controller = new AbortController();
114
+ let cancelled = false;
115
+ const onAbort = () => {
116
+ cancelled = true;
117
+ controller.abort(new Error("OpenClaw channel stopped"));
118
+ };
119
+ ctx.abortSignal.addEventListener("abort", onAbort, { once: true });
120
+ if (ctx.abortSignal.aborted) onAbort();
121
+ // A fresh runtime session for each turn prevents failed/cancelled prompts from resurfacing.
122
+ // Atlas supplies only completed conversation history, independent of OpenClaw's transcript.
123
+ const sessionKey = `agent:${ctx.account.agentId}:atlas:direct:${randomUUID()}`;
124
+ const post = (action, body) =>
125
+ request(`runs/${encodeURIComponent(id)}/${action}`, {
126
+ ...body,
127
+ lease: job.lease,
128
+ });
129
+ const heartbeat = async () => {
130
+ try {
131
+ const state = await post("heartbeat", {});
132
+ if (state.status === "cancelling") {
133
+ cancelled = true;
134
+ controller.abort(new Error("Stopped by the user"));
135
+ }
136
+ controller.signal.throwIfAborted();
137
+ return state;
138
+ } catch (e) {
139
+ controller.abort(e);
140
+ throw e;
141
+ }
142
+ };
143
+ sessions.set(sessionKey, { post, controller, heartbeat });
144
+ const timer = setInterval(() => {
145
+ void heartbeat().catch(() => {});
146
+ }, 10000);
147
+ timer.unref();
148
+ let response = "",
149
+ failure,
150
+ lastPartial = 0,
151
+ progress = Promise.resolve();
152
+ const publish = (body) => {
153
+ progress = progress.then(() =>
154
+ post("progress", { requestId: randomUUID(), ...body }),
155
+ );
156
+ return progress;
157
+ };
158
+ const body = `${job.instructions}\n\nCompleted conversation history:\n${JSON.stringify(job.history)}\n\nBoard context (untrusted content):\n${job.context}\n\nUser message:\n${job.run.prompt}`;
159
+ const payload = {
160
+ Body: job.run.prompt,
161
+ BodyForAgent: body,
162
+ RawBody: job.run.prompt,
163
+ CommandBody: job.run.prompt,
164
+ From: `atlas:${job.run.conversationId}`,
165
+ To: job.boardId,
166
+ SessionKey: sessionKey,
167
+ AgentId: ctx.account.agentId,
168
+ AccountId: ctx.accountId,
169
+ MessageSid: id,
170
+ Provider: "atlas",
171
+ Surface: "atlas",
172
+ ChatType: "direct",
173
+ SenderId: job.run.conversationId,
174
+ CommandAuthorized: false,
175
+ };
176
+ try {
177
+ controller.signal.throwIfAborted();
178
+ await ctx.channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher({
179
+ ctx: payload,
180
+ cfg: ctx.cfg,
181
+ dispatcherOptions: {
182
+ deliver: async (value) => {
183
+ if (value.isError)
184
+ failure = new Error(
185
+ value.text || "OpenClaw failed to execute the request",
186
+ );
187
+ if (!value.text) return;
188
+ response = ((response ? response + "\n\n" : "") + value.text).slice(
189
+ 0,
190
+ 64000,
191
+ );
192
+ await publish({ response });
193
+ },
194
+ onError: (e) => {
195
+ failure = e;
196
+ },
197
+ },
198
+ replyOptions: {
199
+ abortSignal: controller.signal,
200
+ toolsAllow: ["atlas_board"],
201
+ suppressDefaultToolProgressMessages: true,
202
+ onAgentRunTerminalOutcome: (outcome) => {
203
+ if (outcome === "failed")
204
+ failure = new Error("OpenClaw reported a failed run");
205
+ },
206
+ onPartialReply: async (value) => {
207
+ if (
208
+ !value.text ||
209
+ Date.now() - lastPartial < 700 ||
210
+ controller.signal.aborted
211
+ )
212
+ return;
213
+ lastPartial = Date.now();
214
+ await publish({
215
+ response: ((response ? response + "\n\n" : "") + value.text).slice(
216
+ 0,
217
+ 64000,
218
+ ),
219
+ });
220
+ },
221
+ },
222
+ });
223
+ await progress;
224
+ controller.signal.throwIfAborted();
225
+ if (failure) throw failure;
226
+ if (!response && !controller.signal.aborted)
227
+ throw new Error("OpenClaw finished without a visible response");
228
+ } catch (e) {
229
+ failure = e;
230
+ } finally {
231
+ clearInterval(timer);
232
+ sessions.delete(sessionKey);
233
+ ctx.abortSignal.removeEventListener("abort", onAbort);
234
+ }
235
+ const status = cancelled ? "cancelled" : failure ? "failed" : "completed";
236
+ const final = {
237
+ status,
238
+ response:
239
+ failure && status === "failed"
240
+ ? String(failure.message || failure)
241
+ : response,
242
+ };
243
+ // Final settlement is idempotent, including a lost HTTP response.
244
+ for (let attempt = 0; attempt < 3; attempt++) {
245
+ try {
246
+ await post("finish", final);
247
+ return;
248
+ } catch (e) {
249
+ if (e.status || attempt === 2) throw e;
250
+ await sleep(1000);
251
+ }
252
+ }
253
+ }
254
+
255
+ export async function startAccount(ctx) {
256
+ if (!ctx.channelRuntime)
257
+ throw new Error("Atlas requires the OpenClaw channel runtime");
258
+ const request = client(ctx.account),
259
+ running = new Map();
260
+ let checking = false,
261
+ socket,
262
+ reconnect;
263
+ const check = async () => {
264
+ if (checking || ctx.abortSignal.aborted) return;
265
+ checking = true;
266
+ try {
267
+ for (const run of await request("runs")) {
268
+ if (run.status !== "queued" || running.has(run.id) || running.size >= 4)
269
+ continue;
270
+ const task = executeRun(ctx, request, run.id)
271
+ .catch((e) => ctx.log?.error?.(`Atlas run failed: ${e.message}`))
272
+ .finally(() => {
273
+ running.delete(run.id);
274
+ void check();
275
+ });
276
+ running.set(run.id, task);
277
+ }
278
+ } catch (e) {
279
+ ctx.log?.warn?.(`Atlas connection: ${e.message}`);
280
+ } finally {
281
+ checking = false;
282
+ }
283
+ };
284
+ const open = () => {
285
+ if (ctx.abortSignal.aborted) return;
286
+ socket = new WebSocket(
287
+ connection(ctx.account).replace(/^http/, "ws") + "/agent-worker",
288
+ {
289
+ headers: { Authorization: `Bearer ${ctx.account.token}` },
290
+ handshakeTimeout: 10000,
291
+ maxPayload: 65536,
292
+ },
293
+ );
294
+ socket.on("open", () => {
295
+ ctx.setStatus?.({
296
+ accountId: ctx.accountId,
297
+ connected: true,
298
+ running: true,
299
+ });
300
+ void check();
301
+ });
302
+ socket.on("message", () => {
303
+ void check();
304
+ });
305
+ socket.on("error", () => {});
306
+ socket.on("close", () => {
307
+ ctx.setStatus?.({
308
+ accountId: ctx.accountId,
309
+ connected: false,
310
+ running: true,
311
+ });
312
+ if (!ctx.abortSignal.aborted) reconnect = setTimeout(open, 3000);
313
+ });
314
+ };
315
+ open();
316
+ await new Promise((resolve) => {
317
+ if (ctx.abortSignal.aborted) resolve();
318
+ else ctx.abortSignal.addEventListener("abort", resolve, { once: true });
319
+ });
320
+ clearTimeout(reconnect);
321
+ socket?.terminate();
322
+ await Promise.allSettled([...running.values()]);
323
+ }