@kagura-agent/atlas-openclaw 0.1.2 → 0.1.4

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
@@ -10,13 +10,17 @@ Requires OpenClaw 2026.10.5 or newer and Node.js 22.13 or newer. On the machine
10
10
  openclaw plugins install @kagura-agent/atlas-openclaw
11
11
  ```
12
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.
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 account entry into `channels.atlas.accounts` in OpenClaw's configuration. Keep existing accounts, channels and plugin entries. Enable the installed `atlas` plugin; if `plugins.allow` is configured, add `atlas` to that list. Set the account's `agentId` to an existing OpenClaw agent with a working model configuration.
14
+
15
+ Each connection has its own account key, Atlas address, token and agent. Channel-level settings supply shared defaults; an account can override them. A channel-level token represents the default account. `enabled: false` on the channel stops every account; on an account it stops only that connection. Multiple accounts require plugin 0.1.3 or later. To upgrade, run `openclaw plugins install --force --accept-capabilities @kagura-agent/atlas-openclaw`.
16
+
17
+ Add `atlas_board` to `tools.alsoAllow`, preserving existing entries. Atlas includes this permission in the generated configuration. Loading the plugin and connecting the channel do not grant an agent permission to use its tools: a profile such as `coding` with an existing additive allowlist can otherwise reject every Atlas turn before the model runs. The tool is available only with an Atlas task binding; allowing it does not grant arbitrary board access. Explicit deny rules still apply.
14
18
 
15
19
  Restart the OpenClaw gateway after installation. Atlas shows **Connected** when the authenticated socket connects. Select the connection and send a message.
16
20
 
17
21
  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. Loopback HTTP is supported for local development and SSH tunnels.
18
22
 
19
- For development on a trusted LAN, set `channels.atlas.allowPrivateNetworkHttp` to `true` and use the Atlas machine's private IPv4 address in `baseUrl`, such as `http://10.172.208.53:4317`. Atlas must listen on its LAN interface, and the firewall must allow the OpenClaw machine to reach that port. This opt-in accepts only literal addresses in `10.0.0.0/8`, `172.16.0.0/12`, or `192.168.0.0/16`; public HTTP and HTTP hostnames remain rejected. Keep the token private and use HTTPS outside the trusted LAN. The browser's Google callback address can stay on localhost.
23
+ For development on a trusted LAN, set `allowPrivateNetworkHttp` to `true` in the account entry and use the Atlas machine's private IPv4 address in `baseUrl`, such as `http://10.172.208.53:4317`. Atlas must listen on its LAN interface, and the firewall must allow the OpenClaw machine to reach that port. This opt-in accepts only literal addresses in `10.0.0.0/8`, `172.16.0.0/12`, or `192.168.0.0/16`; public HTTP and HTTP hostnames remain rejected. Keep the token private and use HTTPS outside the trusted LAN. The browser's Google callback address can stay on localhost.
20
24
 
21
25
  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).
22
26
 
@@ -40,10 +44,33 @@ Increase the committed package version before another release. An existing versi
40
44
 
41
45
  ## Design
42
46
 
43
- WebSocket notifications wake the worker; reconnecting and periodic server notifications refresh the queue. If no server notification or ping arrives for 45 seconds, the plugin closes the stale socket and reconnects, including when a sleeping computer or a network interruption leaves TCP apparently open. 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.
47
+ WebSocket notifications wake the worker; reconnecting and periodic server notifications refresh the durable queue. If no server notification or ping arrives for 45 seconds, the plugin closes the stale socket and reconnects, including when a sleeping computer leaves TCP apparently open. Repeated disconnects use exponential backoff with jitter, resetting after a stable connection. Authentication rejection ends the account lifecycle with a configuration error. Creating credentials alone never marks an Atlas connection online.
48
+
49
+ Each account runs at most four tasks. Finishing a run checks for queued work; a stop notification bypasses capacity and aborts the requested run immediately. Queue fetches, tools and previews share cancellation signals. Overlapping periodic heartbeat ticks share one renewal. Short renewable run leases prevent a lost worker from silently reexecuting work. Claiming is deliberately not retried after an ambiguous failure: without a confirmed lease, the model must not start. The lease expires and Atlas records the interruption.
50
+
51
+ Reads, heartbeat renewals and writes protected by server receipts retry transient network/5xx failures. Rate limits respect Retry-After within a bounded deadline. Authentication, validation and conflict errors are not retried. Tool writes reuse the same request ID; canvas changes, run updates and receipts commit in the same SQLite transaction. Final settlement is also idempotent and can finish after model cancellation. Exhausted final delivery retries remain an error, never a successful delivery.
52
+
53
+ Streaming previews coalesce, serialize and stop before final settlement. A preview failure does not prevent later updates or the final response. Final delivery seals the draft; callbacks arriving after cancellation or dispatcher completion cannot alter it.
44
54
 
45
55
  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.
46
56
 
57
+ Tool discovery can load the plugin separately from its channel worker. Run authority therefore travels through OpenClaw's native tool binding, rather than a process-global session map. The binding is separate from model input; credentials come from the selected account's host configuration. The host checks invocation lifetime, and Atlas validates the lease and canvas scope on every request.
58
+
47
59
  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).
48
60
 
49
- 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.
61
+ ### Cove reference
62
+
63
+ This comparison uses static source at Cove commit `3de8390882e8b0170b493d4f81001b498a78cdc1`; it does not claim that every Cove path was verified live.
64
+
65
+ | Area | Cove evidence | Atlas decision |
66
+ | --- | --- | --- |
67
+ | Accounts and routing | [channel](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/channel.ts) uses SDK account resolution, root defaults and named overrides | Use the same SDK helpers; each generated Atlas connection gets an independent account |
68
+ | Heartbeat and reconnect | [gateway client](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/gateway-client.ts) detects missed acknowledgements and backs off reconnects | Use Atlas's native WebSocket ping/notification watchdog, backoff and truthful connection status |
69
+ | Recovery | Cove's client sends RESUME and falls back to IDENTIFY; the inspected [server gateway](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/server/src/ws/index.ts) has no RESUME handler | Re-read Atlas's durable queue on reconnect; never replay a claimed model turn |
70
+ | HTTP delivery | [REST client](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/rest-client.ts) distinguishes safe retries and rate limits | Decide retry safety by Atlas receipts, preserve status on non-JSON errors and cancel outstanding I/O |
71
+ | Queue and stop | Cove serializes by conversation and dispatches control messages immediately after authorization | Atlas enforces one active turn per conversation on the server; authenticated stop notifications bypass worker capacity |
72
+ | Draft and final reply | [dispatch](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/dispatch.ts) seals drafts and guards callbacks; [outbound](https://github.com/kagura-chen/cove/blob/3de8390882e8b0170b493d4f81001b498a78cdc1/packages/plugin/src/outbound.ts) requires delivery confirmation | Separate best-effort previews from the durable finish receipt; await writes before settlement |
73
+ | Authorization and sessions | Cove admits channel messages before enrichment and uses canonical thread sessions | Atlas checks worker and board permissions before claim; fresh sessions use completed Atlas history and only the scoped board tool |
74
+ | Platform features | Cove has group policy, commands, reactions, recurring tasks, media delivery, child-run hooks and usage collection | These need separate Atlas product contracts; they are not added as side effects of connection reliability changes |
75
+
76
+ The supported OpenClaw SDK requires `contracts.tools` in the manifest. Atlas uses its buffered reply dispatcher; Cove's `runInboundReplyTurn` wrapper is not exported by the minimum supported host. Package verification checks installation and account resolution, then starts a real gateway against an isolated Atlas fixture and deterministic model. It must discover and execute the board tool and deliver the final reply on both the minimum and latest OpenClaw versions. Failure regressions live in [channel tests](https://github.com/kagura-chen/atlas/blob/main/tests/openclaw-channel.test.ts).
package/accounts.mjs ADDED
@@ -0,0 +1,24 @@
1
+ import { createAccountListHelpers } from "openclaw/plugin-sdk/account-resolution";
2
+
3
+ const accounts = createAccountListHelpers("atlas", {
4
+ implicitDefaultAccount: { channelKeys: ["token"] },
5
+ fallbackAccountIdWhenEmpty: false,
6
+ });
7
+
8
+ export const accountConfig = {
9
+ listAccountIds: accounts.listAccountIds,
10
+ defaultAccountId: accounts.resolveDefaultAccountId,
11
+ resolveAccount: (cfg, accountId) => {
12
+ const id = accountId ?? accounts.resolveDefaultAccountId(cfg);
13
+ const merged = accounts.resolveAccountConfig(cfg, id);
14
+ return {
15
+ ...merged,
16
+ accountId: id,
17
+ enabled:
18
+ cfg.channels?.atlas?.enabled !== false && merged.enabled !== false,
19
+ };
20
+ },
21
+ isConfigured: (account) =>
22
+ Boolean(account.baseUrl && account.token && account.agentId),
23
+ isEnabled: (account) => account.enabled !== false,
24
+ };
package/index.mjs CHANGED
@@ -2,7 +2,8 @@ import {
2
2
  createChatChannelPlugin,
3
3
  defineChannelPluginEntry,
4
4
  } from "openclaw/plugin-sdk/channel-core";
5
- import { boardTool, startAccount } from "./worker.mjs";
5
+ import { boardTool, client, startAccount } from "./worker.mjs";
6
+ import { accountConfig } from "./accounts.mjs";
6
7
 
7
8
  const plugin = createChatChannelPlugin({
8
9
  base: {
@@ -15,18 +16,7 @@ const plugin = createChatChannelPlugin({
15
16
  blurb: "External agent collaboration on an Atlas canvas",
16
17
  },
17
18
  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
- },
19
+ config: accountConfig,
30
20
  gateway: { startAccount },
31
21
  },
32
22
  });
@@ -37,7 +27,18 @@ export default defineChannelPluginEntry({
37
27
  description: "External agents with scoped canvas tools",
38
28
  plugin,
39
29
  registerFull: (api) =>
40
- api.registerTool((context) => boardTool(context), {
41
- names: ["atlas_board"],
42
- }),
30
+ api.registerTool(
31
+ (context) => {
32
+ const binding = context.toolBindings?.atlas;
33
+ if (!binding || binding.sessionKey !== context.sessionKey) return null;
34
+ const account = accountConfig.resolveAccount(
35
+ context.runtimeConfig ?? context.config,
36
+ binding.accountId,
37
+ );
38
+ return boardTool(context, client(account));
39
+ },
40
+ {
41
+ names: ["atlas_board"],
42
+ },
43
+ ),
43
44
  });
@@ -21,6 +21,21 @@
21
21
  "baseUrl": { "type": "string" },
22
22
  "token": { "type": "string" },
23
23
  "agentId": { "type": "string" },
24
+ "defaultAccount": { "type": "string" },
25
+ "accounts": {
26
+ "type": "object",
27
+ "additionalProperties": {
28
+ "type": "object",
29
+ "additionalProperties": false,
30
+ "properties": {
31
+ "enabled": { "type": "boolean" },
32
+ "baseUrl": { "type": "string" },
33
+ "token": { "type": "string" },
34
+ "agentId": { "type": "string" },
35
+ "allowPrivateNetworkHttp": { "type": "boolean" }
36
+ }
37
+ }
38
+ },
24
39
  "allowPrivateNetworkHttp": {
25
40
  "type": "boolean",
26
41
  "default": false,
@@ -28,7 +43,10 @@
28
43
  }
29
44
  }
30
45
  },
31
- "uiHints": { "token": { "sensitive": true } }
46
+ "uiHints": {
47
+ "token": { "sensitive": true },
48
+ "accounts.*.token": { "sensitive": true }
49
+ }
32
50
  }
33
51
  }
34
52
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kagura-agent/atlas-openclaw",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Connect an external OpenClaw agent to Atlas conversations and canvas tools",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,6 +16,8 @@
16
16
  "files": [
17
17
  "index.mjs",
18
18
  "worker.mjs",
19
+ "transport.mjs",
20
+ "accounts.mjs",
19
21
  "openclaw.plugin.json",
20
22
  "README.md"
21
23
  ],
package/transport.mjs ADDED
@@ -0,0 +1,70 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+
3
+ export function createClient(base, token) {
4
+ return async (path, body, { signal } = {}) => {
5
+ const response = await fetch(`${base}/api/agent-worker/${path}`, {
6
+ method: body === undefined ? "GET" : "POST",
7
+ headers: {
8
+ Authorization: `Bearer ${token}`,
9
+ "Content-Type": "application/json",
10
+ },
11
+ ...(body !== undefined && { body: JSON.stringify(body) }),
12
+ signal: AbortSignal.any([
13
+ AbortSignal.timeout(15000),
14
+ ...(signal ? [signal] : []),
15
+ ]),
16
+ redirect: "error",
17
+ });
18
+ if (!response.ok) {
19
+ const value = await response.json().catch(() => null);
20
+ const retryAfter = response.headers.get("retry-after");
21
+ const seconds = Number(retryAfter);
22
+ const delay =
23
+ retryAfter === null
24
+ ? undefined
25
+ : Number.isFinite(seconds)
26
+ ? seconds * 1000
27
+ : Date.parse(retryAfter) - Date.now();
28
+ throw Object.assign(
29
+ new Error(
30
+ typeof value?.error === "string"
31
+ ? value.error
32
+ : `Atlas request failed (${response.status})`,
33
+ ),
34
+ {
35
+ status: response.status,
36
+ retryAfterMs: Number.isFinite(delay) ? Math.max(0, delay) : undefined,
37
+ },
38
+ );
39
+ }
40
+ return response.json();
41
+ };
42
+ }
43
+
44
+ // Only reads and operations with server-side receipts may retry ambiguous failures.
45
+ // The total deadline leaves time to settle before the 60-second run lease expires.
46
+ export async function requestWithRetry(
47
+ request,
48
+ path,
49
+ body,
50
+ { signal, idempotent = false } = {},
51
+ ) {
52
+ const deadline = AbortSignal.any([
53
+ AbortSignal.timeout(30000),
54
+ ...(signal ? [signal] : []),
55
+ ]);
56
+ for (let attempt = 0; ; attempt++) {
57
+ deadline.throwIfAborted();
58
+ try {
59
+ return await request(path, body, { signal: deadline });
60
+ } catch (error) {
61
+ deadline.throwIfAborted();
62
+ const transient = !error.status || error.status >= 500;
63
+ if (attempt === 2 || !(error.status === 429 || (idempotent && transient)))
64
+ throw error;
65
+ const delay =
66
+ error.retryAfterMs ?? 500 * 2 ** attempt + Math.random() * 250;
67
+ await sleep(delay, undefined, { signal: deadline });
68
+ }
69
+ }
70
+ }
package/worker.mjs CHANGED
@@ -2,9 +2,8 @@ import { randomUUID } from "node:crypto";
2
2
  import { isIP } from "node:net";
3
3
  import { setTimeout as sleep } from "node:timers/promises";
4
4
  import WebSocket from "ws";
5
+ import { createClient, requestWithRetry } from "./transport.mjs";
5
6
 
6
- const sessionRegistry = Symbol.for("atlas.openclaw.active-runs");
7
- export const sessions = (globalThis[sessionRegistry] ||= new Map());
8
7
  export function connection(account) {
9
8
  const base = new URL(account.baseUrl);
10
9
  if (
@@ -33,31 +32,12 @@ export function connection(account) {
33
32
  return base.origin;
34
33
  }
35
34
  export function client(account) {
36
- const base = connection(account);
37
- return async (path, body) => {
38
- const response = await fetch(`${base}/api/agent-worker/${path}`, {
39
- method: body === undefined ? "GET" : "POST",
40
- headers: {
41
- Authorization: `Bearer ${account.token}`,
42
- "Content-Type": "application/json",
43
- },
44
- ...(body !== undefined && { body: JSON.stringify(body) }),
45
- signal: AbortSignal.timeout(15000),
46
- redirect: "error",
47
- });
48
- const value = await response.json();
49
- if (!response.ok)
50
- throw Object.assign(
51
- new Error(value.error || `Atlas request failed (${response.status})`),
52
- { status: response.status },
53
- );
54
- return value;
55
- };
35
+ return createClient(connection(account), account.token);
56
36
  }
57
37
 
58
- export function boardTool(context) {
59
- const run = sessions.get(context.sessionKey);
60
- if (!run) return null;
38
+ export function boardTool(context, request) {
39
+ const binding = context.toolBindings?.atlas;
40
+ if (!binding || binding.sessionKey !== context.sessionKey) return null;
61
41
  return {
62
42
  name: "atlas_board",
63
43
  label: "Atlas board",
@@ -80,25 +60,25 @@ export function boardTool(context) {
80
60
  options: { type: "array", items: { type: "string" }, maxItems: 6 },
81
61
  },
82
62
  },
83
- async execute(callId, args) {
84
- run.controller.signal.throwIfAborted();
85
- if (sessions.get(context.sessionKey) !== run)
86
- throw new Error("Atlas run is no longer active");
63
+ async execute(callId, args, signal) {
64
+ const post = (action, body) =>
65
+ requestWithRetry(
66
+ (path, payload, options) => {
67
+ context.assertInvocationCurrent?.();
68
+ return request(path, payload, options);
69
+ },
70
+ `runs/${encodeURIComponent(binding.runId)}/${action}`,
71
+ { ...body, lease: binding.lease },
72
+ { signal, idempotent: true },
73
+ );
87
74
  const requestId = `tool:${callId}`;
88
- let result;
89
- for (let attempt = 0; attempt < 3; attempt++) {
90
- try {
91
- result = await run.post("tool", { ...args, requestId });
92
- break;
93
- } catch (e) {
94
- if (e.status || attempt === 2) throw e;
95
- await sleep(500, undefined, { signal: run.controller.signal });
96
- }
97
- }
75
+ const result = await post("tool", { ...args, requestId });
98
76
  if (args.action === "ask") {
99
77
  for (;;) {
100
- await sleep(1000, undefined, { signal: run.controller.signal });
101
- const state = await run.heartbeat();
78
+ await sleep(1000, undefined, { signal });
79
+ const state = await post("heartbeat", {});
80
+ if (state.status === "cancelling")
81
+ throw new Error("Stopped by the user");
102
82
  if (
103
83
  state.question?.id === result.questionId &&
104
84
  state.question.answer !== undefined
@@ -119,7 +99,16 @@ export function boardTool(context) {
119
99
  }
120
100
 
121
101
  export async function executeRun(ctx, request, id) {
122
- const job = await request(`runs/${encodeURIComponent(id)}/claim`, {});
102
+ ctx.abortSignal.throwIfAborted();
103
+ // Claim is not idempotent. A lost claim response must expire, never rerun the model.
104
+ const job = await requestWithRetry(
105
+ request,
106
+ `runs/${encodeURIComponent(id)}/claim`,
107
+ {},
108
+ {
109
+ signal: ctx.abortSignal,
110
+ },
111
+ );
123
112
  const controller = new AbortController();
124
113
  let cancelled = false;
125
114
  const onAbort = () => {
@@ -131,12 +120,22 @@ export async function executeRun(ctx, request, id) {
131
120
  // A fresh runtime session for each turn prevents failed/cancelled prompts from resurfacing.
132
121
  // Atlas supplies only completed conversation history, independent of OpenClaw's transcript.
133
122
  const sessionKey = `agent:${ctx.account.agentId}:atlas:direct:${randomUUID()}`;
134
- const post = (action, body) =>
135
- request(`runs/${encodeURIComponent(id)}/${action}`, {
136
- ...body,
137
- lease: job.lease,
138
- });
139
- const heartbeat = async () => {
123
+ const post = (action, body, signal = controller.signal) =>
124
+ requestWithRetry(
125
+ request,
126
+ `runs/${encodeURIComponent(id)}/${action}`,
127
+ {
128
+ ...body,
129
+ lease: job.lease,
130
+ },
131
+ { signal, idempotent: true },
132
+ );
133
+ let heartbeatPending;
134
+ const heartbeat = () =>
135
+ (heartbeatPending ||= renew().finally(() => {
136
+ heartbeatPending = undefined;
137
+ }));
138
+ const renew = async () => {
140
139
  try {
141
140
  const state = await post("heartbeat", {});
142
141
  if (state.status === "cancelling") {
@@ -150,19 +149,43 @@ export async function executeRun(ctx, request, id) {
150
149
  throw e;
151
150
  }
152
151
  };
153
- sessions.set(sessionKey, { post, controller, heartbeat });
154
152
  const timer = setInterval(() => {
155
153
  void heartbeat().catch(() => {});
156
154
  }, 10000);
157
155
  timer.unref();
158
156
  let response = "",
159
157
  failure,
160
- lastPartial = 0,
161
- progress = Promise.resolve();
162
- const publish = (body) => {
163
- progress = progress.then(() =>
164
- post("progress", { requestId: randomUUID(), ...body }),
165
- );
158
+ closed = false,
159
+ sealed = false;
160
+ let pendingPreview,
161
+ progress,
162
+ previousPreview,
163
+ lastPreviewAt = 0;
164
+ const active = () => !closed && !controller.signal.aborted;
165
+ // Coalesce partials while a write is in flight. Preview failure cannot poison final delivery.
166
+ const publish = (text) => {
167
+ if (!active() || text === previousPreview) return progress;
168
+ pendingPreview = text;
169
+ progress ||= (async () => {
170
+ while (pendingPreview !== undefined && active()) {
171
+ try {
172
+ const delay = 250 - (Date.now() - lastPreviewAt);
173
+ if (delay > 0)
174
+ await sleep(delay, undefined, { signal: controller.signal });
175
+ if (!active()) break;
176
+ const next = pendingPreview;
177
+ pendingPreview = undefined;
178
+ lastPreviewAt = Date.now();
179
+ await post("progress", { requestId: randomUUID(), response: next });
180
+ previousPreview = next;
181
+ } catch (error) {
182
+ if (active())
183
+ ctx.log?.warn?.(`Atlas preview failed: ${error.message}`);
184
+ }
185
+ }
186
+ })().finally(() => {
187
+ progress = undefined;
188
+ });
166
189
  return progress;
167
190
  };
168
191
  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}`;
@@ -182,6 +205,16 @@ export async function executeRun(ctx, request, id) {
182
205
  ChatType: "direct",
183
206
  SenderId: job.run.conversationId,
184
207
  CommandAuthorized: false,
208
+ // The host carries this binding into tool discovery, including cold-loaded registries.
209
+ // It is not model input; the server still validates the lease and canvas scope.
210
+ GatewayRunToolBindings: {
211
+ atlas: {
212
+ runId: id,
213
+ lease: job.lease,
214
+ sessionKey,
215
+ accountId: ctx.accountId,
216
+ },
217
+ },
185
218
  };
186
219
  try {
187
220
  controller.signal.throwIfAborted();
@@ -189,20 +222,23 @@ export async function executeRun(ctx, request, id) {
189
222
  ctx: payload,
190
223
  cfg: ctx.cfg,
191
224
  dispatcherOptions: {
192
- deliver: async (value) => {
225
+ deliver: async (value, info) => {
226
+ if (!active()) return;
193
227
  if (value.isError)
194
228
  failure = new Error(
195
229
  value.text || "OpenClaw failed to execute the request",
196
230
  );
197
- if (!value.text) return;
198
- response = ((response ? response + "\n\n" : "") + value.text).slice(
231
+ const text = value.text?.trimEnd();
232
+ if (!text?.trim()) return;
233
+ if (!info || info.kind === "final") sealed = true;
234
+ response = ((response ? response + "\n\n" : "") + text).slice(
199
235
  0,
200
236
  64000,
201
237
  );
202
- await publish({ response });
238
+ await publish(response);
203
239
  },
204
240
  onError: (e) => {
205
- failure = e;
241
+ if (active()) failure = e;
206
242
  },
207
243
  },
208
244
  replyOptions: {
@@ -210,27 +246,20 @@ export async function executeRun(ctx, request, id) {
210
246
  toolsAllow: ["atlas_board"],
211
247
  suppressDefaultToolProgressMessages: true,
212
248
  onAgentRunTerminalOutcome: (outcome) => {
213
- if (outcome === "failed")
249
+ if (active() && outcome === "failed")
214
250
  failure = new Error("OpenClaw reported a failed run");
215
251
  },
216
252
  onPartialReply: async (value) => {
217
- if (
218
- !value.text ||
219
- Date.now() - lastPartial < 700 ||
220
- controller.signal.aborted
221
- )
222
- return;
223
- lastPartial = Date.now();
224
- await publish({
225
- response: ((response ? response + "\n\n" : "") + value.text).slice(
253
+ if (!active() || sealed || !value.text?.trim()) return;
254
+ await publish(
255
+ ((response ? response + "\n\n" : "") + value.text.trimEnd()).slice(
226
256
  0,
227
257
  64000,
228
258
  ),
229
- });
259
+ );
230
260
  },
231
261
  },
232
262
  });
233
- await progress;
234
263
  controller.signal.throwIfAborted();
235
264
  if (failure) throw failure;
236
265
  if (!response && !controller.signal.aborted)
@@ -238,28 +267,25 @@ export async function executeRun(ctx, request, id) {
238
267
  } catch (e) {
239
268
  failure = e;
240
269
  } finally {
270
+ closed = true;
271
+ pendingPreview = undefined;
272
+ // Drain in-flight presentation writes before committing the terminal receipt.
273
+ await progress;
241
274
  clearInterval(timer);
242
- sessions.delete(sessionKey);
275
+ await heartbeatPending?.catch(() => {});
243
276
  ctx.abortSignal.removeEventListener("abort", onAbort);
244
277
  }
278
+ if (controller.signal.aborted) failure ||= controller.signal.reason;
245
279
  const status = cancelled ? "cancelled" : failure ? "failed" : "completed";
246
280
  const final = {
247
281
  status,
248
282
  response:
249
283
  failure && status === "failed"
250
- ? String(failure.message || failure)
284
+ ? String(failure.message || failure).slice(0, 64000)
251
285
  : response,
252
286
  };
253
- // Final settlement is idempotent, including a lost HTTP response.
254
- for (let attempt = 0; attempt < 3; attempt++) {
255
- try {
256
- await post("finish", final);
257
- return;
258
- } catch (e) {
259
- if (e.status || attempt === 2) throw e;
260
- await sleep(1000);
261
- }
262
- }
287
+ // Settlement has its own bounded lifetime, even after cancellation of model/tool I/O.
288
+ await post("finish", final, AbortSignal.timeout(30000));
263
289
  }
264
290
 
265
291
  export async function startAccount(ctx) {
@@ -267,32 +293,80 @@ export async function startAccount(ctx) {
267
293
  throw new Error("Atlas requires the OpenClaw channel runtime");
268
294
  const request = client(ctx.account),
269
295
  running = new Map();
270
- let checking = false,
296
+ const lifecycle = new AbortController();
297
+ const signal = AbortSignal.any([ctx.abortSignal, lifecycle.signal]);
298
+ let checking,
299
+ checkAgain = false,
271
300
  socket,
272
- reconnect;
301
+ reconnect,
302
+ fatal;
303
+ let retryDelay = 1000;
304
+ const status = (patch) =>
305
+ ctx.setStatus?.({ accountId: ctx.accountId, ...patch });
306
+ const rejectCredentials = (message) => {
307
+ fatal = new Error(message);
308
+ status({ connected: false, lastError: message });
309
+ lifecycle.abort(fatal);
310
+ };
273
311
  const check = async () => {
274
- if (checking || ctx.abortSignal.aborted) return;
275
- checking = true;
276
- try {
277
- for (const run of await request("runs")) {
278
- if (run.status !== "queued" || running.has(run.id) || running.size >= 4)
279
- continue;
280
- const task = executeRun(ctx, request, run.id)
281
- .catch((e) => ctx.log?.error?.(`Atlas run failed: ${e.message}`))
282
- .finally(() => {
283
- running.delete(run.id);
284
- void check();
312
+ if (signal.aborted) return;
313
+ checkAgain = true;
314
+ if (checking) return checking;
315
+ checking = (async () => {
316
+ while (checkAgain && !signal.aborted) {
317
+ checkAgain = false;
318
+ try {
319
+ const pending = await requestWithRetry(request, "runs", undefined, {
320
+ signal,
321
+ idempotent: true,
285
322
  });
286
- running.set(run.id, task);
323
+ for (const run of pending) {
324
+ if (signal.aborted) break;
325
+ if (run.status === "cancelling")
326
+ running
327
+ .get(run.id)
328
+ ?.controller.abort(new Error("Stopped by the user"));
329
+ if (
330
+ run.status !== "queued" ||
331
+ running.has(run.id) ||
332
+ running.size >= 4
333
+ )
334
+ continue;
335
+ const controller = new AbortController();
336
+ const task = executeRun(
337
+ {
338
+ ...ctx,
339
+ abortSignal: AbortSignal.any([signal, controller.signal]),
340
+ },
341
+ request,
342
+ run.id,
343
+ )
344
+ .catch((error) => {
345
+ if (!signal.aborted)
346
+ ctx.log?.error?.(`Atlas run failed: ${error.message}`);
347
+ })
348
+ .finally(() => {
349
+ running.delete(run.id);
350
+ void check();
351
+ });
352
+ running.set(run.id, { task, controller });
353
+ }
354
+ } catch (error) {
355
+ if (signal.aborted) break;
356
+ if ([401, 403].includes(error.status))
357
+ rejectCredentials(
358
+ "Atlas connection rejected. Check or replace this account's token.",
359
+ );
360
+ else ctx.log?.warn?.(`Atlas queue: ${error.message}`);
361
+ }
287
362
  }
288
- } catch (e) {
289
- ctx.log?.warn?.(`Atlas connection: ${e.message}`);
290
- } finally {
291
- checking = false;
292
- }
363
+ })().finally(() => {
364
+ checking = undefined;
365
+ });
366
+ return checking;
293
367
  };
294
368
  const open = () => {
295
- if (ctx.abortSignal.aborted) return;
369
+ if (signal.aborted) return;
296
370
  const ws = new WebSocket(
297
371
  connection(ctx.account).replace(/^http/, "ws") + "/agent-worker",
298
372
  {
@@ -302,45 +376,98 @@ export async function startAccount(ctx) {
302
376
  },
303
377
  );
304
378
  socket = ws;
305
- let inactivity;
379
+ let inactivity, stable;
306
380
  const received = () => {
307
381
  clearTimeout(inactivity);
308
382
  // Atlas sends queue notifications every 10 seconds and pings every 20.
309
383
  // A broken network path may leave TCP open without ever emitting close.
310
- inactivity = setTimeout(() => ws.terminate(), 45000);
384
+ inactivity = setTimeout(() => {
385
+ status({ connected: false, lastError: "Atlas heartbeat timed out" });
386
+ ws.terminate();
387
+ }, 45000);
311
388
  inactivity.unref?.();
312
389
  };
313
390
  ws.on("open", () => {
391
+ if (signal.aborted) {
392
+ ws.terminate();
393
+ return;
394
+ }
314
395
  received();
315
- ctx.setStatus?.({
316
- accountId: ctx.accountId,
317
- connected: true,
318
- running: true,
319
- });
396
+ stable = setTimeout(() => {
397
+ retryDelay = 1000;
398
+ }, 30000);
399
+ stable.unref?.();
400
+ status({ connected: true, running: true, lastError: null });
320
401
  void check();
321
402
  });
322
403
  ws.on("ping", received);
323
- ws.on("message", () => {
404
+ ws.on("message", (data) => {
324
405
  received();
406
+ // An authenticated server cancellation bypasses queue capacity and HTTP polling.
407
+ try {
408
+ const event = JSON.parse(data.toString());
409
+ if (event.type === "runs" && Array.isArray(event.runs)) {
410
+ for (const run of event.runs) {
411
+ if (run.status === "cancelling")
412
+ running
413
+ .get(run.id)
414
+ ?.controller.abort(new Error("Stopped by the user"));
415
+ }
416
+ }
417
+ } catch {
418
+ ctx.log?.warn?.("Atlas sent an invalid queue notification");
419
+ }
325
420
  void check();
326
421
  });
327
- ws.on("error", () => {});
328
- ws.on("close", () => {
422
+ ws.on("unexpected-response", (_request, response) => {
423
+ response.resume();
424
+ if ([401, 403].includes(response.statusCode))
425
+ rejectCredentials(
426
+ "Atlas connection rejected. Check or replace this account's token.",
427
+ );
428
+ else
429
+ status({
430
+ lastError: `Atlas gateway rejected the connection (${response.statusCode})`,
431
+ });
432
+ ws.terminate();
433
+ });
434
+ ws.on("error", (error) => {
435
+ if (!signal.aborted)
436
+ status({ connected: false, lastError: error.message });
437
+ });
438
+ ws.on("close", (code) => {
329
439
  clearTimeout(inactivity);
330
- ctx.setStatus?.({
331
- accountId: ctx.accountId,
332
- connected: false,
333
- running: !ctx.abortSignal.aborted,
334
- });
335
- if (!ctx.abortSignal.aborted) reconnect = setTimeout(open, 3000);
440
+ clearTimeout(stable);
441
+ if (code === 1008 && !signal.aborted)
442
+ rejectCredentials(
443
+ "Atlas connection expired or was revoked. Create a new connection.",
444
+ );
445
+ status({ connected: false, running: !signal.aborted });
446
+ if (!signal.aborted) {
447
+ reconnect = setTimeout(
448
+ open,
449
+ retryDelay + Math.random() * retryDelay * 0.2,
450
+ );
451
+ retryDelay = Math.min(retryDelay * 2, 30000);
452
+ }
336
453
  });
337
454
  };
455
+ if (signal.aborted) return;
456
+ status({ running: true, connected: false, lastError: null });
338
457
  open();
339
458
  await new Promise((resolve) => {
340
- if (ctx.abortSignal.aborted) resolve();
341
- else ctx.abortSignal.addEventListener("abort", resolve, { once: true });
459
+ if (signal.aborted) resolve();
460
+ else signal.addEventListener("abort", resolve, { once: true });
342
461
  });
343
462
  clearTimeout(reconnect);
463
+ const socketClosed =
464
+ socket && socket.readyState !== WebSocket.CLOSED
465
+ ? new Promise((resolve) => socket.once("close", resolve))
466
+ : undefined;
344
467
  socket?.terminate();
345
- await Promise.allSettled([...running.values()]);
468
+ await socketClosed;
469
+ await checking;
470
+ await Promise.allSettled([...running.values()].map(({ task }) => task));
471
+ status({ connected: false, running: false });
472
+ if (fatal) throw fatal;
346
473
  }