-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathtasks.ts
More file actions
193 lines (184 loc) · 6.58 KB
/
Copy pathtasks.ts
File metadata and controls
193 lines (184 loc) · 6.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Task gateway methods expose detached task list/get/cancel operations with
// bounded public summaries over the runtime task registry.
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import {
ErrorCodes,
errorShape,
formatValidationErrors,
type TaskSummary,
type TasksListParams,
validateTasksCancelParams,
validateTasksGetParams,
validateTasksListParams,
} from "../../../packages/gateway-protocol/src/index.js";
import { parseAgentSessionKey } from "../../routing/session-key.js";
import { cancelDetachedTaskRunById } from "../../tasks/detached-task-runtime.js";
import { getTaskById, listTaskRecords } from "../../tasks/runtime-internal.js";
import type { TaskRecord, TaskStatus } from "../../tasks/task-registry.types.js";
import { mapTaskSummary, taskUpdatedAt } from "./task-summary.js";
import type { GatewayRequestHandlers } from "./types.js";
const DEFAULT_TASKS_LIST_LIMIT = 100;
const MAX_TASKS_LIST_LIMIT = 500;
type TaskLedgerStatus = TaskSummary["status"];
const LEDGER_STATUS_TO_TASK_STATUSES: Record<TaskLedgerStatus, TaskStatus[]> = {
queued: ["queued"],
running: ["running"],
completed: ["succeeded"],
failed: ["failed", "lost"],
timed_out: ["timed_out"],
cancelled: ["cancelled"],
};
function normalizeTaskStatusFilter(status: TasksListParams["status"]): Set<TaskStatus> | null {
if (!status) {
return null;
}
const statuses = Array.isArray(status) ? status : [status];
return new Set(statuses.flatMap((value) => LEDGER_STATUS_TO_TASK_STATUSES[value] ?? []));
}
// Session filtering needs all ownership keys because detached child runs may be
// queried from the requester, child session, or owner/control-plane view.
function taskMatchesSession(task: TaskRecord, sessionKey: string | undefined): boolean {
const normalized = normalizeOptionalString(sessionKey);
if (!normalized) {
return true;
}
return [task.requesterSessionKey, task.childSessionKey, task.ownerKey].some(
(candidate) => normalizeOptionalString(candidate) === normalized,
);
}
// Explicit `task.agentId` is authoritative: a task that records its own agent
// must not also match other agents through the session-key fallback. Only
// records that predate a direct `agentId` recover the owning agent from
// session-style keys instead of being hidden.
function taskMatchesAgent(task: TaskRecord, agentId: string | undefined): boolean {
const normalized = normalizeOptionalString(agentId);
if (!normalized) {
return true;
}
const explicitAgentId = normalizeOptionalString(task.agentId);
if (explicitAgentId) {
return explicitAgentId === normalized;
}
return [task.requesterSessionKey, task.childSessionKey, task.ownerKey].some(
(candidate) => parseAgentSessionKey(candidate)?.agentId === normalized,
);
}
// Cursor strings are offsets, not opaque tokens; reject malformed values so a
// client cannot silently restart pagination at the first page.
function parseCursor(cursor: string | undefined): number | null {
if (!cursor) {
return 0;
}
if (!/^\d+$/.test(cursor.trim())) {
return null;
}
const parsed = Number(cursor);
return Number.isSafeInteger(parsed) ? parsed : null;
}
// Control UI task methods expose the stable gateway protocol shape; helpers
// above keep runtime registry details out of the wire result.
export const tasksHandlers: GatewayRequestHandlers = {
"tasks.list": ({ params, respond }) => {
if (!validateTasksListParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid tasks.list params: ${formatValidationErrors(validateTasksListParams.errors)}`,
),
);
return;
}
const cursor = parseCursor(params.cursor);
if (cursor === null) {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "invalid tasks.list cursor"),
);
return;
}
const statusFilter = normalizeTaskStatusFilter(params.status);
const limit = Math.min(params.limit ?? DEFAULT_TASKS_LIST_LIMIT, MAX_TASKS_LIST_LIMIT);
// The registry lists newest-created first; the ledger view pages by last
// activity so an old long-running task that just finished still surfaces
// on the first page instead of hiding behind newer-created records.
const filtered = listTaskRecords()
.filter((task) => {
if (statusFilter && !statusFilter.has(task.status)) {
return false;
}
return (
taskMatchesAgent(task, params.agentId) && taskMatchesSession(task, params.sessionKey)
);
})
.toSorted((left, right) => {
const updatedDiff = taskUpdatedAt(right) - taskUpdatedAt(left);
if (updatedDiff !== 0) {
return updatedDiff;
}
return left.taskId < right.taskId ? -1 : left.taskId > right.taskId ? 1 : 0;
});
const page = filtered.slice(cursor, cursor + limit);
const nextOffset = cursor + page.length;
respond(true, {
tasks: page.map((task) => mapTaskSummary(task)),
...(nextOffset < filtered.length ? { nextCursor: String(nextOffset) } : {}),
});
},
"tasks.get": ({ params, respond }) => {
if (!validateTasksGetParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid tasks.get params: ${formatValidationErrors(validateTasksGetParams.errors)}`,
),
);
return;
}
const taskId = params.taskId;
const task = getTaskById(taskId);
if (!task) {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, `task not found: ${taskId}`),
);
return;
}
respond(true, { task: mapTaskSummary(task) });
},
"tasks.cancel": async ({ params, respond, context }) => {
if (!validateTasksCancelParams(params)) {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
`invalid tasks.cancel params: ${formatValidationErrors(validateTasksCancelParams.errors)}`,
),
);
return;
}
const taskId = params.taskId;
const reason = normalizeOptionalString(params.reason);
const result = await cancelDetachedTaskRunById({
cfg: context.getRuntimeConfig(),
taskId,
...(reason ? { reason } : {}),
});
respond(true, {
found: result.found,
cancelled: result.cancelled,
...(result.reason ? { reason: result.reason } : {}),
...(result.task ? { task: mapTaskSummary(result.task) } : {}),
});
},
};
export const testApi = {
mapTaskSummary,
};
export { testApi as __test };