@kagura-agent/atlas-openclaw 0.1.1 → 0.1.3
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 +27 -4
- package/accounts.mjs +24 -0
- package/index.mjs +2 -12
- package/openclaw.plugin.json +19 -1
- package/package.json +3 -1
- package/transport.mjs +70 -0
- package/worker.mjs +236 -111
package/README.md
CHANGED
|
@@ -10,13 +10,15 @@ 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`
|
|
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`.
|
|
14
16
|
|
|
15
17
|
Restart the OpenClaw gateway after installation. Atlas shows **Connected** when the authenticated socket connects. Select the connection and send a message.
|
|
16
18
|
|
|
17
19
|
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
20
|
|
|
19
|
-
For development on a trusted LAN, set `
|
|
21
|
+
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
22
|
|
|
21
23
|
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
24
|
|
|
@@ -40,10 +42,31 @@ Increase the committed package version before another release. An existing versi
|
|
|
40
42
|
|
|
41
43
|
## Design
|
|
42
44
|
|
|
43
|
-
WebSocket notifications wake the worker; reconnecting and periodic server notifications refresh the queue.
|
|
45
|
+
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.
|
|
46
|
+
|
|
47
|
+
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. Concurrent heartbeat callers 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.
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
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
52
|
|
|
45
53
|
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
54
|
|
|
47
55
|
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
56
|
|
|
49
|
-
|
|
57
|
+
### Cove reference
|
|
58
|
+
|
|
59
|
+
This comparison uses static source at Cove commit `3de8390882e8b0170b493d4f81001b498a78cdc1`; it does not claim that every Cove path was verified live.
|
|
60
|
+
|
|
61
|
+
| Area | Cove evidence | Atlas decision |
|
|
62
|
+
| --- | --- | --- |
|
|
63
|
+
| 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 |
|
|
64
|
+
| 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 |
|
|
65
|
+
| 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 |
|
|
66
|
+
| 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 |
|
|
67
|
+
| 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 |
|
|
68
|
+
| 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 |
|
|
69
|
+
| 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 |
|
|
70
|
+
| 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 |
|
|
71
|
+
|
|
72
|
+
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 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
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
defineChannelPluginEntry,
|
|
4
4
|
} from "openclaw/plugin-sdk/channel-core";
|
|
5
5
|
import { boardTool, 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
|
});
|
package/openclaw.plugin.json
CHANGED
|
@@ -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": {
|
|
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.
|
|
3
|
+
"version": "0.1.3",
|
|
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,6 +2,7 @@ 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
7
|
const sessionRegistry = Symbol.for("atlas.openclaw.active-runs");
|
|
7
8
|
export const sessions = (globalThis[sessionRegistry] ||= new Map());
|
|
@@ -33,26 +34,7 @@ export function connection(account) {
|
|
|
33
34
|
return base.origin;
|
|
34
35
|
}
|
|
35
36
|
export function client(account) {
|
|
36
|
-
|
|
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
|
-
};
|
|
37
|
+
return createClient(connection(account), account.token);
|
|
56
38
|
}
|
|
57
39
|
|
|
58
40
|
export function boardTool(context) {
|
|
@@ -85,16 +67,7 @@ export function boardTool(context) {
|
|
|
85
67
|
if (sessions.get(context.sessionKey) !== run)
|
|
86
68
|
throw new Error("Atlas run is no longer active");
|
|
87
69
|
const requestId = `tool:${callId}`;
|
|
88
|
-
|
|
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
|
-
}
|
|
70
|
+
const result = await run.post("tool", { ...args, requestId });
|
|
98
71
|
if (args.action === "ask") {
|
|
99
72
|
for (;;) {
|
|
100
73
|
await sleep(1000, undefined, { signal: run.controller.signal });
|
|
@@ -119,7 +92,16 @@ export function boardTool(context) {
|
|
|
119
92
|
}
|
|
120
93
|
|
|
121
94
|
export async function executeRun(ctx, request, id) {
|
|
122
|
-
|
|
95
|
+
ctx.abortSignal.throwIfAborted();
|
|
96
|
+
// Claim is not idempotent. A lost claim response must expire, never rerun the model.
|
|
97
|
+
const job = await requestWithRetry(
|
|
98
|
+
request,
|
|
99
|
+
`runs/${encodeURIComponent(id)}/claim`,
|
|
100
|
+
{},
|
|
101
|
+
{
|
|
102
|
+
signal: ctx.abortSignal,
|
|
103
|
+
},
|
|
104
|
+
);
|
|
123
105
|
const controller = new AbortController();
|
|
124
106
|
let cancelled = false;
|
|
125
107
|
const onAbort = () => {
|
|
@@ -131,12 +113,22 @@ export async function executeRun(ctx, request, id) {
|
|
|
131
113
|
// A fresh runtime session for each turn prevents failed/cancelled prompts from resurfacing.
|
|
132
114
|
// Atlas supplies only completed conversation history, independent of OpenClaw's transcript.
|
|
133
115
|
const sessionKey = `agent:${ctx.account.agentId}:atlas:direct:${randomUUID()}`;
|
|
134
|
-
const post = (action, body) =>
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
116
|
+
const post = (action, body, signal = controller.signal) =>
|
|
117
|
+
requestWithRetry(
|
|
118
|
+
request,
|
|
119
|
+
`runs/${encodeURIComponent(id)}/${action}`,
|
|
120
|
+
{
|
|
121
|
+
...body,
|
|
122
|
+
lease: job.lease,
|
|
123
|
+
},
|
|
124
|
+
{ signal, idempotent: true },
|
|
125
|
+
);
|
|
126
|
+
let heartbeatPending;
|
|
127
|
+
const heartbeat = () =>
|
|
128
|
+
(heartbeatPending ||= renew().finally(() => {
|
|
129
|
+
heartbeatPending = undefined;
|
|
130
|
+
}));
|
|
131
|
+
const renew = async () => {
|
|
140
132
|
try {
|
|
141
133
|
const state = await post("heartbeat", {});
|
|
142
134
|
if (state.status === "cancelling") {
|
|
@@ -157,12 +149,37 @@ export async function executeRun(ctx, request, id) {
|
|
|
157
149
|
timer.unref();
|
|
158
150
|
let response = "",
|
|
159
151
|
failure,
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
progress
|
|
164
|
-
|
|
165
|
-
|
|
152
|
+
closed = false,
|
|
153
|
+
sealed = false;
|
|
154
|
+
let pendingPreview,
|
|
155
|
+
progress,
|
|
156
|
+
previousPreview,
|
|
157
|
+
lastPreviewAt = 0;
|
|
158
|
+
const active = () => !closed && !controller.signal.aborted;
|
|
159
|
+
// Coalesce partials while a write is in flight. Preview failure cannot poison final delivery.
|
|
160
|
+
const publish = (text) => {
|
|
161
|
+
if (!active() || text === previousPreview) return progress;
|
|
162
|
+
pendingPreview = text;
|
|
163
|
+
progress ||= (async () => {
|
|
164
|
+
while (pendingPreview !== undefined && active()) {
|
|
165
|
+
try {
|
|
166
|
+
const delay = 250 - (Date.now() - lastPreviewAt);
|
|
167
|
+
if (delay > 0)
|
|
168
|
+
await sleep(delay, undefined, { signal: controller.signal });
|
|
169
|
+
if (!active()) break;
|
|
170
|
+
const next = pendingPreview;
|
|
171
|
+
pendingPreview = undefined;
|
|
172
|
+
lastPreviewAt = Date.now();
|
|
173
|
+
await post("progress", { requestId: randomUUID(), response: next });
|
|
174
|
+
previousPreview = next;
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (active())
|
|
177
|
+
ctx.log?.warn?.(`Atlas preview failed: ${error.message}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
})().finally(() => {
|
|
181
|
+
progress = undefined;
|
|
182
|
+
});
|
|
166
183
|
return progress;
|
|
167
184
|
};
|
|
168
185
|
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}`;
|
|
@@ -189,20 +206,23 @@ export async function executeRun(ctx, request, id) {
|
|
|
189
206
|
ctx: payload,
|
|
190
207
|
cfg: ctx.cfg,
|
|
191
208
|
dispatcherOptions: {
|
|
192
|
-
deliver: async (value) => {
|
|
209
|
+
deliver: async (value, info) => {
|
|
210
|
+
if (!active()) return;
|
|
193
211
|
if (value.isError)
|
|
194
212
|
failure = new Error(
|
|
195
213
|
value.text || "OpenClaw failed to execute the request",
|
|
196
214
|
);
|
|
197
|
-
|
|
198
|
-
|
|
215
|
+
const text = value.text?.trimEnd();
|
|
216
|
+
if (!text?.trim()) return;
|
|
217
|
+
if (!info || info.kind === "final") sealed = true;
|
|
218
|
+
response = ((response ? response + "\n\n" : "") + text).slice(
|
|
199
219
|
0,
|
|
200
220
|
64000,
|
|
201
221
|
);
|
|
202
|
-
await publish(
|
|
222
|
+
await publish(response);
|
|
203
223
|
},
|
|
204
224
|
onError: (e) => {
|
|
205
|
-
failure = e;
|
|
225
|
+
if (active()) failure = e;
|
|
206
226
|
},
|
|
207
227
|
},
|
|
208
228
|
replyOptions: {
|
|
@@ -210,27 +230,20 @@ export async function executeRun(ctx, request, id) {
|
|
|
210
230
|
toolsAllow: ["atlas_board"],
|
|
211
231
|
suppressDefaultToolProgressMessages: true,
|
|
212
232
|
onAgentRunTerminalOutcome: (outcome) => {
|
|
213
|
-
if (outcome === "failed")
|
|
233
|
+
if (active() && outcome === "failed")
|
|
214
234
|
failure = new Error("OpenClaw reported a failed run");
|
|
215
235
|
},
|
|
216
236
|
onPartialReply: async (value) => {
|
|
217
|
-
if (
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
controller.signal.aborted
|
|
221
|
-
)
|
|
222
|
-
return;
|
|
223
|
-
lastPartial = Date.now();
|
|
224
|
-
await publish({
|
|
225
|
-
response: ((response ? response + "\n\n" : "") + value.text).slice(
|
|
237
|
+
if (!active() || sealed || !value.text?.trim()) return;
|
|
238
|
+
await publish(
|
|
239
|
+
((response ? response + "\n\n" : "") + value.text.trimEnd()).slice(
|
|
226
240
|
0,
|
|
227
241
|
64000,
|
|
228
242
|
),
|
|
229
|
-
|
|
243
|
+
);
|
|
230
244
|
},
|
|
231
245
|
},
|
|
232
246
|
});
|
|
233
|
-
await progress;
|
|
234
247
|
controller.signal.throwIfAborted();
|
|
235
248
|
if (failure) throw failure;
|
|
236
249
|
if (!response && !controller.signal.aborted)
|
|
@@ -238,28 +251,26 @@ export async function executeRun(ctx, request, id) {
|
|
|
238
251
|
} catch (e) {
|
|
239
252
|
failure = e;
|
|
240
253
|
} finally {
|
|
241
|
-
|
|
254
|
+
closed = true;
|
|
255
|
+
pendingPreview = undefined;
|
|
242
256
|
sessions.delete(sessionKey);
|
|
257
|
+
// Drain in-flight presentation writes before committing the terminal receipt.
|
|
258
|
+
await progress;
|
|
259
|
+
clearInterval(timer);
|
|
260
|
+
await heartbeatPending?.catch(() => {});
|
|
243
261
|
ctx.abortSignal.removeEventListener("abort", onAbort);
|
|
244
262
|
}
|
|
263
|
+
if (controller.signal.aborted) failure ||= controller.signal.reason;
|
|
245
264
|
const status = cancelled ? "cancelled" : failure ? "failed" : "completed";
|
|
246
265
|
const final = {
|
|
247
266
|
status,
|
|
248
267
|
response:
|
|
249
268
|
failure && status === "failed"
|
|
250
|
-
? String(failure.message || failure)
|
|
269
|
+
? String(failure.message || failure).slice(0, 64000)
|
|
251
270
|
: response,
|
|
252
271
|
};
|
|
253
|
-
//
|
|
254
|
-
|
|
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
|
-
}
|
|
272
|
+
// Settlement has its own bounded lifetime, even after cancellation of model/tool I/O.
|
|
273
|
+
await post("finish", final, AbortSignal.timeout(30000));
|
|
263
274
|
}
|
|
264
275
|
|
|
265
276
|
export async function startAccount(ctx) {
|
|
@@ -267,33 +278,81 @@ export async function startAccount(ctx) {
|
|
|
267
278
|
throw new Error("Atlas requires the OpenClaw channel runtime");
|
|
268
279
|
const request = client(ctx.account),
|
|
269
280
|
running = new Map();
|
|
270
|
-
|
|
281
|
+
const lifecycle = new AbortController();
|
|
282
|
+
const signal = AbortSignal.any([ctx.abortSignal, lifecycle.signal]);
|
|
283
|
+
let checking,
|
|
284
|
+
checkAgain = false,
|
|
271
285
|
socket,
|
|
272
|
-
reconnect
|
|
286
|
+
reconnect,
|
|
287
|
+
fatal;
|
|
288
|
+
let retryDelay = 1000;
|
|
289
|
+
const status = (patch) =>
|
|
290
|
+
ctx.setStatus?.({ accountId: ctx.accountId, ...patch });
|
|
291
|
+
const rejectCredentials = (message) => {
|
|
292
|
+
fatal = new Error(message);
|
|
293
|
+
status({ connected: false, lastError: message });
|
|
294
|
+
lifecycle.abort(fatal);
|
|
295
|
+
};
|
|
273
296
|
const check = async () => {
|
|
274
|
-
if (
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
void check();
|
|
297
|
+
if (signal.aborted) return;
|
|
298
|
+
checkAgain = true;
|
|
299
|
+
if (checking) return checking;
|
|
300
|
+
checking = (async () => {
|
|
301
|
+
while (checkAgain && !signal.aborted) {
|
|
302
|
+
checkAgain = false;
|
|
303
|
+
try {
|
|
304
|
+
const pending = await requestWithRetry(request, "runs", undefined, {
|
|
305
|
+
signal,
|
|
306
|
+
idempotent: true,
|
|
285
307
|
});
|
|
286
|
-
|
|
308
|
+
for (const run of pending) {
|
|
309
|
+
if (signal.aborted) break;
|
|
310
|
+
if (run.status === "cancelling")
|
|
311
|
+
running
|
|
312
|
+
.get(run.id)
|
|
313
|
+
?.controller.abort(new Error("Stopped by the user"));
|
|
314
|
+
if (
|
|
315
|
+
run.status !== "queued" ||
|
|
316
|
+
running.has(run.id) ||
|
|
317
|
+
running.size >= 4
|
|
318
|
+
)
|
|
319
|
+
continue;
|
|
320
|
+
const controller = new AbortController();
|
|
321
|
+
const task = executeRun(
|
|
322
|
+
{
|
|
323
|
+
...ctx,
|
|
324
|
+
abortSignal: AbortSignal.any([signal, controller.signal]),
|
|
325
|
+
},
|
|
326
|
+
request,
|
|
327
|
+
run.id,
|
|
328
|
+
)
|
|
329
|
+
.catch((error) => {
|
|
330
|
+
if (!signal.aborted)
|
|
331
|
+
ctx.log?.error?.(`Atlas run failed: ${error.message}`);
|
|
332
|
+
})
|
|
333
|
+
.finally(() => {
|
|
334
|
+
running.delete(run.id);
|
|
335
|
+
void check();
|
|
336
|
+
});
|
|
337
|
+
running.set(run.id, { task, controller });
|
|
338
|
+
}
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (signal.aborted) break;
|
|
341
|
+
if ([401, 403].includes(error.status))
|
|
342
|
+
rejectCredentials(
|
|
343
|
+
"Atlas connection rejected. Check or replace this account's token.",
|
|
344
|
+
);
|
|
345
|
+
else ctx.log?.warn?.(`Atlas queue: ${error.message}`);
|
|
346
|
+
}
|
|
287
347
|
}
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
}
|
|
348
|
+
})().finally(() => {
|
|
349
|
+
checking = undefined;
|
|
350
|
+
});
|
|
351
|
+
return checking;
|
|
293
352
|
};
|
|
294
353
|
const open = () => {
|
|
295
|
-
if (
|
|
296
|
-
|
|
354
|
+
if (signal.aborted) return;
|
|
355
|
+
const ws = new WebSocket(
|
|
297
356
|
connection(ctx.account).replace(/^http/, "ws") + "/agent-worker",
|
|
298
357
|
{
|
|
299
358
|
headers: { Authorization: `Bearer ${ctx.account.token}` },
|
|
@@ -301,33 +360,99 @@ export async function startAccount(ctx) {
|
|
|
301
360
|
maxPayload: 65536,
|
|
302
361
|
},
|
|
303
362
|
);
|
|
304
|
-
socket
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
363
|
+
socket = ws;
|
|
364
|
+
let inactivity, stable;
|
|
365
|
+
const received = () => {
|
|
366
|
+
clearTimeout(inactivity);
|
|
367
|
+
// Atlas sends queue notifications every 10 seconds and pings every 20.
|
|
368
|
+
// A broken network path may leave TCP open without ever emitting close.
|
|
369
|
+
inactivity = setTimeout(() => {
|
|
370
|
+
status({ connected: false, lastError: "Atlas heartbeat timed out" });
|
|
371
|
+
ws.terminate();
|
|
372
|
+
}, 45000);
|
|
373
|
+
inactivity.unref?.();
|
|
374
|
+
};
|
|
375
|
+
ws.on("open", () => {
|
|
376
|
+
if (signal.aborted) {
|
|
377
|
+
ws.terminate();
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
received();
|
|
381
|
+
stable = setTimeout(() => {
|
|
382
|
+
retryDelay = 1000;
|
|
383
|
+
}, 30000);
|
|
384
|
+
stable.unref?.();
|
|
385
|
+
status({ connected: true, running: true, lastError: null });
|
|
310
386
|
void check();
|
|
311
387
|
});
|
|
312
|
-
|
|
388
|
+
ws.on("ping", received);
|
|
389
|
+
ws.on("message", (data) => {
|
|
390
|
+
received();
|
|
391
|
+
// An authenticated server cancellation bypasses queue capacity and HTTP polling.
|
|
392
|
+
try {
|
|
393
|
+
const event = JSON.parse(data.toString());
|
|
394
|
+
if (event.type === "runs" && Array.isArray(event.runs)) {
|
|
395
|
+
for (const run of event.runs) {
|
|
396
|
+
if (run.status === "cancelling")
|
|
397
|
+
running
|
|
398
|
+
.get(run.id)
|
|
399
|
+
?.controller.abort(new Error("Stopped by the user"));
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
} catch {
|
|
403
|
+
ctx.log?.warn?.("Atlas sent an invalid queue notification");
|
|
404
|
+
}
|
|
313
405
|
void check();
|
|
314
406
|
});
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
407
|
+
ws.on("unexpected-response", (_request, response) => {
|
|
408
|
+
response.resume();
|
|
409
|
+
if ([401, 403].includes(response.statusCode))
|
|
410
|
+
rejectCredentials(
|
|
411
|
+
"Atlas connection rejected. Check or replace this account's token.",
|
|
412
|
+
);
|
|
413
|
+
else
|
|
414
|
+
status({
|
|
415
|
+
lastError: `Atlas gateway rejected the connection (${response.statusCode})`,
|
|
416
|
+
});
|
|
417
|
+
ws.terminate();
|
|
418
|
+
});
|
|
419
|
+
ws.on("error", (error) => {
|
|
420
|
+
if (!signal.aborted)
|
|
421
|
+
status({ connected: false, lastError: error.message });
|
|
422
|
+
});
|
|
423
|
+
ws.on("close", (code) => {
|
|
424
|
+
clearTimeout(inactivity);
|
|
425
|
+
clearTimeout(stable);
|
|
426
|
+
if (code === 1008 && !signal.aborted)
|
|
427
|
+
rejectCredentials(
|
|
428
|
+
"Atlas connection expired or was revoked. Create a new connection.",
|
|
429
|
+
);
|
|
430
|
+
status({ connected: false, running: !signal.aborted });
|
|
431
|
+
if (!signal.aborted) {
|
|
432
|
+
reconnect = setTimeout(
|
|
433
|
+
open,
|
|
434
|
+
retryDelay + Math.random() * retryDelay * 0.2,
|
|
435
|
+
);
|
|
436
|
+
retryDelay = Math.min(retryDelay * 2, 30000);
|
|
437
|
+
}
|
|
323
438
|
});
|
|
324
439
|
};
|
|
440
|
+
if (signal.aborted) return;
|
|
441
|
+
status({ running: true, connected: false, lastError: null });
|
|
325
442
|
open();
|
|
326
443
|
await new Promise((resolve) => {
|
|
327
|
-
if (
|
|
328
|
-
else
|
|
444
|
+
if (signal.aborted) resolve();
|
|
445
|
+
else signal.addEventListener("abort", resolve, { once: true });
|
|
329
446
|
});
|
|
330
447
|
clearTimeout(reconnect);
|
|
448
|
+
const socketClosed =
|
|
449
|
+
socket && socket.readyState !== WebSocket.CLOSED
|
|
450
|
+
? new Promise((resolve) => socket.once("close", resolve))
|
|
451
|
+
: undefined;
|
|
331
452
|
socket?.terminate();
|
|
332
|
-
await
|
|
453
|
+
await socketClosed;
|
|
454
|
+
await checking;
|
|
455
|
+
await Promise.allSettled([...running.values()].map(({ task }) => task));
|
|
456
|
+
status({ connected: false, running: false });
|
|
457
|
+
if (fatal) throw fatal;
|
|
333
458
|
}
|