@flame0510/project-aether 1.3.0 → 1.4.1

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.
Files changed (78) hide show
  1. package/README.md +1 -0
  2. package/agent-templates/README.md +42 -22
  3. package/agent-templates/base-image/Dockerfile +42 -33
  4. package/agent-templates/base-image/entrypoint.sh +67 -12
  5. package/app/agents/BrowserAccessSection.tsx +510 -0
  6. package/app/agents/ChannelManager.tsx +19 -11
  7. package/app/agents/ImageDownloadBanner.tsx +53 -19
  8. package/app/agents/ModelSection.tsx +4 -1
  9. package/app/agents/PageClient.tsx +629 -167
  10. package/app/agents/UpdateSection.tsx +300 -0
  11. package/app/agents/create/PageClient.tsx +11 -49
  12. package/app/agents/create/page.tsx +14 -28
  13. package/app/api/agents/[id]/backup/route.ts +26 -69
  14. package/app/api/agents/[id]/channels/pairing/route.ts +3 -3
  15. package/app/api/agents/[id]/channels/telegram/route.ts +2 -2
  16. package/app/api/agents/[id]/cold-backup/route.ts +56 -0
  17. package/app/api/agents/[id]/devices/route.ts +126 -0
  18. package/app/api/agents/[id]/invite-link/route.ts +53 -0
  19. package/app/api/agents/[id]/lifecycle/route.ts +3 -0
  20. package/app/api/agents/[id]/open-control-ui/route.ts +58 -0
  21. package/app/api/agents/[id]/recreate/route.ts +33 -163
  22. package/app/api/agents/[id]/restart/route.ts +5 -0
  23. package/app/api/agents/[id]/restore/route.ts +40 -70
  24. package/app/api/agents/[id]/route.ts +38 -150
  25. package/app/api/agents/[id]/update/rollback/route.ts +30 -0
  26. package/app/api/agents/[id]/update/route.ts +50 -0
  27. package/app/api/agents/activity-summary/route.ts +67 -0
  28. package/app/api/agents/create/route.ts +38 -92
  29. package/app/api/agents/devices-summary/route.ts +37 -0
  30. package/app/api/agents/download-image/route.ts +16 -9
  31. package/app/api/agents/image-status/route.ts +31 -111
  32. package/app/api/agents/route.ts +25 -49
  33. package/app/api/agents/token/route.ts +33 -10
  34. package/app/api/assistant/route.ts +2 -2
  35. package/app/api/gateway/agent/route.ts +14 -0
  36. package/app/api/gateway/provider/balance/route.ts +5 -2
  37. package/app/api/gateway/sync.ts +97 -14
  38. package/app/api/setup/agent-image/route.ts +14 -42
  39. package/app/api/version/route.ts +2 -1
  40. package/app/components/DashboardToolbar.tsx +1 -1
  41. package/app/gateway/PageClient.tsx +27 -32
  42. package/bin/rev4a.js +43 -41
  43. package/daemon.js +6 -6
  44. package/docs/ARCHITECTURE.md +107 -9
  45. package/docs/FRONTEND-ARCHITECTURE.md +8 -1
  46. package/docs/REV4A.md +54 -17
  47. package/docs/dev/API-REFERENCE.md +573 -105
  48. package/docs/dev/DATABASE.md +96 -0
  49. package/docs/dev/GATEWAY.md +21 -6
  50. package/docs/rag/DATA-FRESHNESS.md +6 -4
  51. package/docs/rag/GLOSSARY.md +12 -3
  52. package/docs/rag/REV4A-OVERVIEW.md +18 -5
  53. package/docs/rag/WHAT-I-CAN-ANSWER.md +6 -2
  54. package/instrumentation.ts +43 -0
  55. package/lib/agent-busy.ts +21 -0
  56. package/lib/agent-devices.ts +361 -0
  57. package/lib/agent-edit-state.ts +108 -0
  58. package/lib/agent-edit.ts +149 -0
  59. package/lib/agent-images.ts +375 -0
  60. package/lib/agent-ports-server.ts +78 -0
  61. package/lib/agent-ports.ts +91 -0
  62. package/lib/agent-recreate-state.ts +108 -0
  63. package/lib/agent-recreate.ts +359 -0
  64. package/lib/agent-restore-state.ts +107 -0
  65. package/lib/agent-restore.ts +141 -0
  66. package/lib/agent-setup.ts +66 -17
  67. package/lib/agent-update-state.ts +122 -0
  68. package/lib/agent-update.ts +456 -0
  69. package/lib/agent-versions.json +14 -0
  70. package/lib/agent-versions.ts +80 -0
  71. package/lib/buildAgentImage.ts +88 -290
  72. package/lib/channelManager.ts +149 -102
  73. package/lib/cold-backup.ts +354 -0
  74. package/lib/credentials/delivery.ts +3 -3
  75. package/lib/db-bootstrap.mjs +76 -0
  76. package/lib/docker-utils.ts +3 -3
  77. package/lib/provider-balance.ts +33 -12
  78. package/package.json +1 -1
@@ -1,81 +1,51 @@
1
- import { NextResponse } from 'next/server';
2
- import { execSync } from 'child_process';
3
- import { resolveAgentedContainer, isValidAgentId } from '@/lib/container';
4
- import { requireAuthJWT } from '@/lib/rev4a-auth';
5
-
6
- export const dynamic = 'force-dynamic';
7
-
8
- const BACKUP_VOLUME = 'rev4a-backups';
9
-
10
1
  /**
11
- * POST /api/agents/[id]/restore?file=agent-xxx-2026-07-11_2115.tar.gz
12
- * Restore an agent's persistent volume from a backup.
13
- * Stops the container, restores the volume, then restarts.
2
+ * Restore one agent's volume from a backup archive (lib/agent-restore.ts).
3
+ *
4
+ * POST ?file=… start: the container is stopped, the volume cleared and the archive
5
+ * extracted (up to 30 minutes), then the container is started again even
6
+ * when the extract failed. 202 once the job has started; the steps
7
+ * continue in the background and are recorded in `agent_restores`.
8
+ * GET `{ restore }`: the running or last job; null when none.
9
+ *
10
+ * While it runs, anything else that would touch the agent answers 409 (lib/agent-busy.ts).
14
11
  */
15
- export async function POST(request: Request,
16
- { params }: { params: Promise<{ id: string }> },
17
- ): Promise<NextResponse> {
18
- const denied = await requireAuthJWT(request); if (denied) return denied as any;
19
- try {
20
- const { id } = await params;
21
- if (!id) return NextResponse.json({ error: 'Agent name required' }, { status: 400 });
22
- if (!isValidAgentId(id)) return NextResponse.json({ error: 'Invalid agent id' }, { status: 400 });
23
-
24
- const url = new URL(request.url);
25
- const file = url.searchParams.get('file');
26
- if (!file) return NextResponse.json({ error: 'file query param required' }, { status: 400 });
27
-
28
- // Safety: only allow restoring agent-specific files, reject path traversal
29
- if (!file.startsWith(`agent-${id}-`) || !file.endsWith('.tar.gz') || file.includes('/') || file.includes('..')) {
30
- return NextResponse.json({ error: 'Invalid backup file name' }, { status: 400 });
31
- }
12
+ import { NextResponse, type NextRequest } from 'next/server';
13
+ import { requireAuthJWT } from '@/lib/rev4a-auth';
14
+ import { isValidAgentId } from '@/lib/container';
15
+ import { agentRestoreView, RestoreRefusedError, startAgentRestore } from '@/lib/agent-restore';
32
16
 
33
- const volume = `agent-${id}-data`;
17
+ export const dynamic = 'force-dynamic';
34
18
 
35
- // Resolve the actual container name via AGENT_ID label
36
- const containerName = resolveAgentedContainer(id);
19
+ type Ctx = { params: Promise<{ id: string }> };
37
20
 
38
- // Check backup exists
39
- const check = execSync(
40
- `docker run --rm -v ${BACKUP_VOLUME}:/backup alpine sh -c 'test -f /backup/${file} && echo ok || true'`,
41
- { timeout: 10000, encoding: 'utf-8' },
42
- ).trim();
43
- if (check !== 'ok') {
44
- return NextResponse.json({ error: `Backup file '${file}' not found` }, { status: 404 });
45
- }
21
+ async function agentId(ctx: Ctx): Promise<string | NextResponse> {
22
+ const { id } = await ctx.params;
23
+ return isValidAgentId(id) ? id : NextResponse.json({ error: 'Invalid agent id' }, { status: 400 });
24
+ }
46
25
 
47
- // Stop the container if running
48
- if (containerName) {
49
- execSync(`docker stop ${containerName} 2>/dev/null; exit 0`, { timeout: 15000 });
50
- }
26
+ export async function POST(request: NextRequest, ctx: Ctx): Promise<NextResponse> {
27
+ const denied = await requireAuthJWT(request); if (denied) return denied as NextResponse;
28
+ const id = await agentId(ctx);
29
+ if (id instanceof NextResponse) return id;
51
30
 
52
- // Clear the volume and restore from backup.
53
- // Run a temporary container with the volume, delete ALL contents (including
54
- // dotfiles/dotdirs like .openclaw, .config, .local — the .[!.]* glob is
55
- // required, otherwise the restore only merges on top of stale state), then
56
- // extract the backup. Always restart the container afterwards, even on failure.
57
- try {
58
- execSync(
59
- `docker run --rm ` +
60
- `-v ${volume}:/target ` +
61
- `-v ${BACKUP_VOLUME}:/backup ` +
62
- `alpine sh -c 'rm -rf /target/* /target/.[!.]* /target/..?* 2>/dev/null; tar xzf /backup/${file} -C /target'`,
63
- { timeout: 30000, stdio: 'pipe' },
64
- );
65
- } finally {
66
- // Restart the container regardless of extract outcome so it never stays down.
67
- if (containerName) {
68
- try {
69
- execSync(`docker start ${containerName}`, { timeout: 15000, stdio: 'pipe' });
70
- } catch {
71
- // container start failure is surfaced separately; nothing else to do here
72
- }
73
- }
74
- }
31
+ const file = new URL(request.url).searchParams.get('file');
32
+ if (!file) return NextResponse.json({ error: 'file query param required' }, { status: 400 });
75
33
 
76
- return NextResponse.json({ success: true, container: containerName || id });
77
- } catch (e: unknown) {
78
- return NextResponse.json({ error: (e as Error).message }, { status: 500 });
34
+ try {
35
+ const rowId = await startAgentRestore(id, file);
36
+ return NextResponse.json({ started: true, id: rowId }, { status: 202 });
37
+ } catch (e) {
38
+ const message = (e as Error).message;
39
+ const status = e instanceof RestoreRefusedError
40
+ ? (/Invalid backup file name|Invalid agent id/.test(message) ? 400 : /not found/.test(message) ? 404 : 409)
41
+ : 500;
42
+ return NextResponse.json({ error: (e as Error).message }, { status });
79
43
  }
80
44
  }
81
45
 
46
+ export async function GET(request: NextRequest, ctx: Ctx): Promise<NextResponse> {
47
+ const denied = await requireAuthJWT(request); if (denied) return denied as NextResponse;
48
+ const id = await agentId(ctx);
49
+ if (id instanceof NextResponse) return id;
50
+ return NextResponse.json({ restore: agentRestoreView(id) }, { headers: { 'Cache-Control': 'no-store' } });
51
+ }
@@ -3,11 +3,10 @@ import { execSync } from 'child_process';
3
3
  import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
  import { resolveAgentedContainer, isValidAgentId } from '@/lib/container';
6
- import { patchRev4aProvider } from '@/app/api/gateway/sync';
7
- import { getMountFlags, applyRuntimeConfig } from '@/lib/agent-setup';
6
+ import { agentBusyReason } from '@/lib/agent-busy';
7
+ import { agentEditView, EditRefusedError, startAgentEdit } from '@/lib/agent-edit';
8
8
  import { DB_FILE } from '@/lib/rev4a-paths';
9
9
  import { requireAuthJWT } from '@/lib/rev4a-auth';
10
- import { waitForGatewayReady } from '@/lib/agent-readiness';
11
10
 
12
11
  const BACKUP_VOLUME = 'rev4a-backups';
13
12
 
@@ -30,6 +29,9 @@ export async function DELETE(request: Request,
30
29
  return NextResponse.json({ success: false, error: 'Invalid agent id' }, { status: 400 });
31
30
  }
32
31
 
32
+ const busy = await agentBusyReason(id);
33
+ if (busy) return NextResponse.json({ error: busy }, { status: 409 });
34
+
33
35
  // Only allow deletion of containers that have a matching AGENT_ID label
34
36
  const containerName = resolveAgentedContainer(id);
35
37
  if (!containerName) {
@@ -87,16 +89,14 @@ export async function DELETE(request: Request,
87
89
  }
88
90
  }
89
91
 
90
- function shellQuote(value: string): string {
91
- return `'${value.replace(/'/g, `'\\''`)}'`;
92
- }
93
-
94
92
  /**
95
93
  * PATCH /api/agents/[id]
96
94
  *
97
- * Update agent settings (display name, ports — future).
98
- * Recreates the container with updated env vars while preserving the
99
- * persistent volume, workspace, sessions, and all data.
95
+ * Edit an agent's display name and/or port range. The container is rebuilt on the image
96
+ * it already runs — **no backup**, the persistent volume is never touched — and the job
97
+ * runs in the background (`lib/agent-edit.ts`): `202` once it has started, then
98
+ * `GET /api/agents/[id]` reports the running or last edit so the panel can resume.
99
+ * While it runs, anything else that would touch the agent answers `409`.
100
100
  */
101
101
  export async function PATCH(
102
102
  request: Request,
@@ -115,149 +115,37 @@ export async function PATCH(
115
115
  return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
116
116
  }
117
117
 
118
- const { displayName, portRange } = body;
119
- if (!displayName && !portRange) {
120
- return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
121
- }
122
-
123
- if (displayName !== undefined && (!displayName || displayName.trim().length < 1)) {
124
- return NextResponse.json({ error: 'Display name must not be empty' }, { status: 400 });
125
- }
126
-
127
- // Resolve the container
128
- const containerName = resolveAgentedContainer(id);
129
- if (!containerName) {
130
- return NextResponse.json({ error: `No container found with AGENT_ID '${id}'` }, { status: 404 });
131
- }
132
-
133
- // Inspect existing container
134
- let inspect: string;
135
- try {
136
- inspect = execSync(`docker inspect ${containerName}`, { timeout: 10000, encoding: 'utf-8' }).trim();
137
- } catch {
138
- return NextResponse.json({ error: `Container '${containerName}' not found` }, { status: 404 });
139
- }
140
-
141
- const info = JSON.parse(inspect);
142
- const [container] = info;
143
- const image = container.Config?.Image || 'openclaw-agent-base:latest';
144
- const currentEnv: string[] = container.Config?.Env || [];
145
-
146
- // Update AGENT_NAME in env vars
147
- let env = [...currentEnv];
148
- if (displayName) {
149
- const idx = env.findIndex((e: string) => e.startsWith('AGENT_NAME='));
150
- const newEntry = `AGENT_NAME=${displayName.trim()}`;
151
- if (idx >= 0) {
152
- env[idx] = newEntry;
153
- } else {
154
- env.push(newEntry);
155
- }
156
- }
157
-
158
- // Keep only relevant env vars
159
- const keepPrefixes = ['AGENT_', 'MODEL_', 'OPENCLAW_', 'TZ='];
160
- const envOpts = env
161
- .filter((e: string) => keepPrefixes.some((p) => e.startsWith(p)))
162
- .map((e: string) => `-e ${shellQuote(e)}`)
163
- .join(' ');
164
-
165
- // Labels
166
- const labels = container.Config?.Labels || {};
167
- const keepLabelKeys = ['AGENT_ID', 'traefik.', 'description', 'maintainer'];
168
- const labelOpts = Object.entries(labels)
169
- .filter(([k]) => keepLabelKeys.some((p) => k === p || k.startsWith(p)))
170
- .map(([k, v]) => `-l ${shellQuote(`${k}=${v}`)}`)
171
- .join(' ');
172
-
173
- // Network
174
- const networks = container.NetworkSettings?.Networks || {};
175
- const network = Object.keys(networks)[0];
176
- if (!network) {
177
- return NextResponse.json({ error: 'Cannot determine network' }, { status: 500 });
178
- }
179
-
180
- // Port mappings
181
- const portBindings = (container.HostConfig?.PortBindings || {}) as Record<string, { HostPort: string }[]>;
182
- let portOpts = Object.entries(portBindings)
183
- .map(([containerPort, bindings]) => {
184
- const hostPort = bindings[0]?.HostPort;
185
- if (!hostPort) return '';
186
- const proto = containerPort.includes('/udp') ? '/udp' : '';
187
- return `-p ${hostPort}:${containerPort.replace(/\/.*$/, '')}${proto}`;
188
- })
189
- .filter(Boolean)
190
- .join(' ');
191
-
192
- // If portRange is provided, replace the port mapping
193
- if (portRange) {
194
- const parts = portRange.trim().split('-');
195
- const start = parseInt(parts[0], 10);
196
- const end = parts[1] ? parseInt(parts[1], 10) : start;
197
- if (isNaN(start) || isNaN(end) || start < 1 || end > 65535 || end < start) {
198
- return NextResponse.json({ error: 'Invalid port range' }, { status: 400 });
199
- }
200
- if (end === start) {
201
- portOpts = `-p ${start}:3000`;
202
- } else {
203
- portOpts = `-p ${start}-${end}:3000-${3000 + (end - start)}`;
204
- }
205
- }
206
-
207
- const volumeName = `agent-${id}-data`;
208
-
209
- // Stop & remove old container (keep volume)
210
- try {
211
- execSync(`docker rm -f ${containerName}`, { timeout: 15000 });
212
- } catch (rmErr) {
213
- return NextResponse.json(
214
- { error: `Failed to remove old container: ${(rmErr as Error).message}` },
215
- { status: 500 },
216
- );
217
- }
218
-
219
- // Run new container with same volume
220
- const cmd = [
221
- `docker run -d`,
222
- `--name "${id}"`,
223
- `--network "${network}"`,
224
- `--restart unless-stopped`,
225
- `--add-host host.docker.internal:host-gateway`,
226
- `-v ${volumeName}:/root`,
227
- ...getMountFlags(),
228
- labelOpts,
229
- envOpts,
230
- portOpts,
231
- `"${image}"`,
232
- ].filter(Boolean).join(' \\\n ');
233
-
234
- execSync(cmd, { timeout: 60000, encoding: 'utf-8' });
235
-
236
- // Wait for startup to complete — /startupz, not /health
237
- const ready = await waitForGatewayReady(id);
238
- if (!ready) {
239
- return NextResponse.json(
240
- { error: 'Container started but its gateway did not finish starting within 60s.' },
241
- { status: 500 },
242
- );
243
- }
244
-
245
- // Apply runtime config
246
- try {
247
- applyRuntimeConfig(id);
248
- patchRev4aProvider(id);
249
- } catch (e) {
250
- // non-fatal, but a skipped patch must show up in the log
251
- console.error('[agent:update] runtime config patch failed:', (e as Error).message);
252
- }
253
-
254
- return NextResponse.json({
255
- success: true,
256
- displayName: displayName?.trim() || null,
257
- });
118
+ const rowId = await startAgentEdit(id, { displayName: body.displayName, portRange: body.portRange });
119
+ return NextResponse.json({ started: true, id: rowId }, { status: 202 });
258
120
  } catch (e: unknown) {
121
+ if (e instanceof EditRefusedError) {
122
+ const message = e.message;
123
+ // The shared port validator's messages (lib/agent-ports.ts) are validation errors:
124
+ // they answer 400, like the create route. Everything else is a busy refusal (409).
125
+ const status = /Invalid agent id|Display name must not be empty|No fields to update|Invalid format|Ports must be between|End port must be greater|reserved for Rev4a|already in use|Use a number/.test(message)
126
+ ? 400
127
+ : 409;
128
+ return NextResponse.json({ error: message }, { status });
129
+ }
259
130
  return NextResponse.json({ error: (e as Error).message }, { status: 500 });
260
131
  }
261
132
  }
262
133
 
134
+ /**
135
+ * GET /api/agents/[id]
136
+ *
137
+ * The running or last edit of an agent (`null` when it was never edited): what the edit
138
+ * panel polls to resume after a reload.
139
+ */
140
+ export async function GET(
141
+ request: Request,
142
+ { params }: { params: Promise<{ id: string }> },
143
+ ): Promise<NextResponse> {
144
+ const denied = await requireAuthJWT(request); if (denied) return denied as any;
145
+ const { id } = await params;
146
+ if (!isValidAgentId(id)) return NextResponse.json({ error: 'Invalid agent id' }, { status: 400 });
147
+ return NextResponse.json({ edit: agentEditView(id) }, { headers: { 'Cache-Control': 'no-store' } });
148
+ }
149
+
150
+
263
151
 
@@ -0,0 +1,30 @@
1
+ /**
2
+ * POST /api/agents/[id]/update/rollback
3
+ *
4
+ * Roll back the agent's latest update (lib/agent-update.ts): its pre-update backup is
5
+ * restored and the container recreated on the version it ran before. Everything the
6
+ * agent did after that backup is lost. 202 with the update; the steps continue in the
7
+ * background, `GET /api/agents/[id]/update` follows them.
8
+ */
9
+ import { NextResponse, type NextRequest } from 'next/server';
10
+ import { requireAuthJWT } from '@/lib/rev4a-auth';
11
+ import { isValidAgentId } from '@/lib/container';
12
+ import { UpdateRefusedError, agentUpdateView, startAgentRollback } from '@/lib/agent-update';
13
+
14
+ export const dynamic = 'force-dynamic';
15
+
16
+ export async function POST(
17
+ request: NextRequest,
18
+ { params }: { params: Promise<{ id: string }> },
19
+ ): Promise<NextResponse> {
20
+ const denied = await requireAuthJWT(request); if (denied) return denied as NextResponse;
21
+ const { id } = await params;
22
+ if (!isValidAgentId(id)) return NextResponse.json({ error: 'Invalid agent id' }, { status: 400 });
23
+ try {
24
+ await startAgentRollback(id);
25
+ return NextResponse.json({ update: await agentUpdateView(id) }, { status: 202 });
26
+ } catch (e) {
27
+ const status = e instanceof UpdateRefusedError ? 409 : 500;
28
+ return NextResponse.json({ error: (e as Error).message }, { status });
29
+ }
30
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Update one agent to a newer supported OpenClaw version (lib/agent-update.ts).
3
+ *
4
+ * GET `{ currentVersion, candidate, update }`: the version the agent runs, the
5
+ * `{ fromVersion, toVersion }` an update would do (null when none is newer),
6
+ * and the latest update with its status and live backup progress.
7
+ * POST `{ version? }` — start an update, by default to the newest supported version
8
+ * downloaded. 202 with the new update; the steps continue in the background.
9
+ */
10
+ import { NextResponse, type NextRequest } from 'next/server';
11
+ import { requireAuthJWT } from '@/lib/rev4a-auth';
12
+ import { isValidAgentId } from '@/lib/container';
13
+ import { isSupportedVersion } from '@/lib/agent-versions';
14
+ import { UpdateRefusedError, agentUpdateView, startAgentUpdate, updateCandidate } from '@/lib/agent-update';
15
+
16
+ export const dynamic = 'force-dynamic';
17
+
18
+ type Ctx = { params: Promise<{ id: string }> };
19
+
20
+ export async function GET(request: NextRequest, { params }: Ctx): Promise<NextResponse> {
21
+ const denied = await requireAuthJWT(request); if (denied) return denied as NextResponse;
22
+ const { id } = await params;
23
+ if (!isValidAgentId(id)) return NextResponse.json({ error: 'Invalid agent id' }, { status: 400 });
24
+ try {
25
+ const { currentVersion, candidate } = await updateCandidate(id);
26
+ return NextResponse.json(
27
+ { currentVersion, candidate, update: await agentUpdateView(id) },
28
+ { headers: { 'Cache-Control': 'no-store' } },
29
+ );
30
+ } catch (e) {
31
+ return NextResponse.json({ error: (e as Error).message }, { status: 503 });
32
+ }
33
+ }
34
+
35
+ export async function POST(request: NextRequest, { params }: Ctx): Promise<NextResponse> {
36
+ const denied = await requireAuthJWT(request); if (denied) return denied as NextResponse;
37
+ const { id } = await params;
38
+ if (!isValidAgentId(id)) return NextResponse.json({ error: 'Invalid agent id' }, { status: 400 });
39
+ const body = (await request.json().catch(() => null)) as { version?: unknown } | null;
40
+ if (body?.version !== undefined && body.version !== null && !isSupportedVersion(body.version)) {
41
+ return NextResponse.json({ error: 'version must be an OpenClaw version this Rev4a supports' }, { status: 400 });
42
+ }
43
+ try {
44
+ await startAgentUpdate(id, (body?.version as string | undefined) ?? undefined);
45
+ return NextResponse.json({ update: await agentUpdateView(id) }, { status: 202 });
46
+ } catch (e) {
47
+ const status = e instanceof UpdateRefusedError ? 409 : 500;
48
+ return NextResponse.json({ error: (e as Error).message }, { status });
49
+ }
50
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * GET /api/agents/activity-summary
3
+ *
4
+ * The long operation each agent is in the middle of, if any — the chip on the agent
5
+ * cards: `BACKUP nn%`, `RESTORING`, `RECREATING`, `UPDATING`.
6
+ *
7
+ * One Docker list call plus, per running cold backup, its status read. Idle agents are
8
+ * not listed at all, so an idle system costs one call.
9
+ */
10
+ import { NextResponse, type NextRequest } from 'next/server';
11
+ import { requireAuthJWT } from '@/lib/rev4a-auth';
12
+ import { coldBackupStatus, listRunningColdBackups } from '@/lib/cold-backup';
13
+ import { activeRestoreAgentIds, latestRestore } from '@/lib/agent-restore-state';
14
+ import { activeRecreateAgentIds, latestRecreate } from '@/lib/agent-recreate-state';
15
+ import { activeUpdateAgentIds, latestUpdate } from '@/lib/agent-update-state';
16
+ import { activeEditAgentIds, latestEdit } from '@/lib/agent-edit-state';
17
+
18
+ export const dynamic = 'force-dynamic';
19
+
20
+ export type AgentActivityKind = 'backup' | 'restore' | 'recreate' | 'update' | 'edit';
21
+
22
+ interface AgentActivity {
23
+ agentId: string;
24
+ kind: AgentActivityKind;
25
+ file?: string | null;
26
+ version?: string | null;
27
+ percent?: number | null;
28
+ }
29
+
30
+ export async function GET(request: NextRequest): Promise<NextResponse> {
31
+ const denied = await requireAuthJWT(request); if (denied) return denied as NextResponse;
32
+
33
+ const byAgent = new Map<string, AgentActivity>();
34
+
35
+ // Update and recreate first: a running cold backup then overrides them, because while
36
+ // its helper archives the volume that is the phase actually in progress.
37
+ for (const agentId of activeUpdateAgentIds()) {
38
+ const row = latestUpdate(agentId);
39
+ if (row && (row.status === 'migrating' || row.status === 'verifying' || row.status === 'rolling_back')) {
40
+ byAgent.set(agentId, { agentId, kind: 'update', version: row.to_version });
41
+ }
42
+ }
43
+ for (const agentId of activeRecreateAgentIds()) {
44
+ const row = latestRecreate(agentId);
45
+ if (row && row.status === 'recreating') {
46
+ byAgent.set(agentId, { agentId, kind: 'recreate', version: row.image });
47
+ }
48
+ }
49
+ for (const agentId of activeRestoreAgentIds()) {
50
+ byAgent.set(agentId, { agentId, kind: 'restore', file: latestRestore(agentId)?.file ?? null });
51
+ }
52
+ for (const agentId of activeEditAgentIds()) {
53
+ const row = latestEdit(agentId);
54
+ if (row && row.status === 'rebuilding') {
55
+ byAgent.set(agentId, { agentId, kind: 'edit', file: row.display_name });
56
+ }
57
+ }
58
+
59
+ const backupIds = await listRunningColdBackups().catch(() => []);
60
+ await Promise.all(backupIds.map(async (agentId) => {
61
+ const job = await coldBackupStatus(agentId).catch(() => null);
62
+ if (!job || job.status !== 'running') return;
63
+ byAgent.set(agentId, { agentId, kind: 'backup', file: job.file, percent: job.percent });
64
+ }));
65
+
66
+ return NextResponse.json({ agents: [...byAgent.values()] }, { headers: { 'Cache-Control': 'no-store' } });
67
+ }