Repository navigation
Expand file tree
/
Copy pathtask-tools.ts
More file actions
289 lines (268 loc) · 10.5 KB
/
Copy pathtask-tools.ts
File metadata and controls
289 lines (268 loc) · 10.5 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { TASK_STATUSES, type TaskStatus } from "../../db/schema";
import { getRunForOrg } from "../../runs/repo";
import {
createTask,
getTaskForOrg,
listTasksForOrg,
updateTask,
type TaskRecord,
} from "../../tasks/repo";
import type { ToolTokenClaims } from "./token";
import type { ToolCallResult } from "./tools";
// ---------------------------------------------------------------------------
// Durable task gateway (Tier-2). An agent mid-run creates and updates ORG-SCOPED
// tasks that OUTLIVE the session - the durability win over an in-sandbox / MCP
// task server whose state dies with the process. Identity, org, and the default
// project are derived SERVER-side from the run-scoped token (never a tool
// argument): a tampered token fails closed upstream, and every read/write is
// pinned to the token's org. `project` defaults to the run's primary repo.
// ---------------------------------------------------------------------------
export const TASK_TOOLS = [
{
name: "task_create",
description:
"Create a durable task in this organization's task board. The task persists after this run ends " +
"(it outlives the session), so use it to record follow-up work, a plan item, or a TODO the team " +
"should see later. The project defaults to this run's repository; pass `project` to file it elsewhere.",
inputSchema: {
type: "object",
properties: {
title: { type: "string", description: "Short task title (required)." },
body: { type: "string", description: "Optional longer description / notes." },
status: {
type: "string",
enum: [...TASK_STATUSES],
description: "Initial column. Defaults to 'todo'.",
},
priority: { type: "integer", description: "Optional priority (higher = more urgent)." },
project: {
type: "string",
description:
"Project key to file under - a repo full name ('owner/name') or a free label. " +
"Defaults to this run's primary repository.",
},
},
required: ["title"],
additionalProperties: false,
},
},
{
name: "task_list",
description:
"List this organization's durable tasks. By default lists this run's project; pass `project` " +
"to list another, pass an empty `project` for unfiled tasks, or set `all_projects` true for an " +
"explicit bounded cross-project list. Optionally filter by `status`.",
inputSchema: {
type: "object",
properties: {
all_projects: {
type: "boolean",
description: "Set true to list across every project. Defaults to this run's project.",
},
project: {
type: "string",
description:
"Project key to list. Defaults to this run's primary repository; pass an explicit value to " +
"list another project.",
},
status: {
type: "string",
enum: [...TASK_STATUSES],
description: "Optional status filter.",
},
limit: {
type: "integer",
minimum: 1,
maximum: 100,
description: "Maximum tasks to return. Defaults to 50.",
},
},
additionalProperties: false,
},
},
{
name: "task_update",
description:
"Update one durable task by id (from task_list) - transition its status, edit the title/body, or " +
"change its priority. Org-scoped: a task from another organization is not found.",
inputSchema: {
type: "object",
properties: {
taskId: { type: "string", description: "Exact task id returned by task_list." },
status: {
type: "string",
enum: [...TASK_STATUSES],
description: "New column, e.g. 'in_progress' or 'done'.",
},
title: { type: "string", description: "New title." },
body: { type: "string", description: "New description / notes." },
priority: { type: "integer", description: "New priority." },
},
required: ["taskId"],
additionalProperties: false,
},
},
] as const;
export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set(TASK_TOOLS.map((tool) => tool.name));
function error(text: string): ToolCallResult {
return { content: [{ type: "text", text }], isError: true };
}
function summarizeTask(t: TaskRecord): Record<string, unknown> {
return {
id: t.id,
projectId: t.projectId,
project: t.projectKey,
title: t.title,
body: t.body,
status: t.status,
priority: t.priority,
};
}
/** The run's primary repository ("owner/name"), or null - the default project a
* mid-run task is filed under when the agent passes no explicit `project`. */
async function runPrimaryProject(
claims: ToolTokenClaims,
): Promise<{ id: string | null; key: string | null }> {
const run = await getRunForOrg(claims.orgId, claims.runId);
return { id: run?.projectId ?? null, key: run?.repo ?? null };
}
/** Resolve the effective project: an explicit non-empty arg wins; an explicit
* empty string means "unfiled"; an absent arg falls back to the run's repo. */
function resolveProject(
arg: unknown,
fallback: string | null,
): { value: string | null; explicit: boolean } {
if (typeof arg === "string") {
const trimmed = arg.trim();
return { value: trimmed ? trimmed : null, explicit: true };
}
return { value: fallback, explicit: false };
}
function coerceStatus(arg: unknown): TaskStatus | null | undefined {
if (arg === undefined) return undefined;
return typeof arg === "string" && (TASK_STATUSES as readonly string[]).includes(arg)
? (arg as TaskStatus)
: null;
}
async function createTaskTool(
claims: ToolTokenClaims,
args: Record<string, unknown>,
): Promise<ToolCallResult> {
const title = typeof args.title === "string" ? args.title.trim() : "";
if (!title) return error("task_create requires a non-empty `title`.");
const status = coerceStatus(args.status);
if (status === null) {
return error(`task_create: status must be one of: ${TASK_STATUSES.join(", ")}.`);
}
const runProject = await runPrimaryProject(claims);
const { value: project, explicit } = resolveProject(args.project, runProject.key);
const created = await createTask({
orgId: claims.orgId,
projectId: explicit ? null : runProject.id,
projectKey: project,
title,
body: typeof args.body === "string" ? args.body : null,
status: status ?? undefined,
priority: typeof args.priority === "number" ? args.priority : undefined,
createdByUserId: claims.userId || null,
// Provenance: the run that created this durable task.
sourceRunId: claims.runId,
});
return {
content: [
{
type: "text",
text: `Created durable task "${created.title}" (${created.status}) in project ${created.projectKey ?? "(none)"}. Task id: ${created.id}.`,
},
],
structuredContent: { task: summarizeTask(created) },
};
}
async function listTasksTool(
claims: ToolTokenClaims,
args: Record<string, unknown>,
): Promise<ToolCallResult> {
const statusFilter = coerceStatus(args.status);
if (statusFilter === null) {
return error(`task_list: status must be one of: ${TASK_STATUSES.join(", ")}.`);
}
if (args.all_projects !== undefined && typeof args.all_projects !== "boolean") {
return error("task_list: `all_projects` must be a boolean.");
}
const rawLimit = typeof args.limit === "number" ? Math.trunc(args.limit) : 50;
if (rawLimit < 1 || rawLimit > 100) {
return error("task_list: `limit` must be between 1 and 100.");
}
const runProject = await runPrimaryProject(claims);
const { value: project, explicit } = resolveProject(args.project, runProject.key);
const selection =
args.all_projects === true
? ({ scope: "all" } as const)
: explicit
? ({ projectKey: project } as const)
: runProject.id
? ({ projectId: runProject.id } as const)
: ({ projectKey: null } as const);
const rows = await listTasksForOrg(claims.orgId, selection, rawLimit);
const filtered = statusFilter ? rows.filter((t) => t.status === statusFilter) : rows;
const tasks = filtered.map(summarizeTask);
let header = "Unfiled tasks";
if (args.all_projects === true) header = "Tasks (all projects)";
else if (project) header = `Tasks for project ${project}`;
const lines = filtered.length
? filtered.map((t) => `- [${t.status}] ${t.title} (id ${t.id})`).join("\n")
: "(no tasks)";
return {
content: [{ type: "text", text: `${header}:\n${lines}` }],
structuredContent: { tasks },
};
}
async function updateTaskTool(
claims: ToolTokenClaims,
args: Record<string, unknown>,
): Promise<ToolCallResult> {
const taskId = typeof args.taskId === "string" ? args.taskId.trim() : "";
if (!taskId) return error("task_update requires an exact `taskId` from task_list.");
const status = coerceStatus(args.status);
if (status === null) {
return error(`task_update: status must be one of: ${TASK_STATUSES.join(", ")}.`);
}
const patch: {
title?: string;
body?: string | null;
status?: TaskStatus;
priority?: number;
} = {};
if (typeof args.title === "string" && args.title.trim()) patch.title = args.title.trim();
if (typeof args.body === "string") patch.body = args.body;
if (status !== undefined) patch.status = status;
if (typeof args.priority === "number") patch.priority = args.priority;
if (Object.keys(patch).length === 0) {
// Nothing to change: confirm the task exists (org-scoped) so the agent gets
// a not-found signal rather than a silent no-op on a stale id.
const current = await getTaskForOrg(claims.orgId, taskId);
if (!current) return error("That task is not available to this organization.");
return {
content: [{ type: "text", text: `No changes provided for task ${taskId}.` }],
structuredContent: { task: summarizeTask(current) },
};
}
const updated = await updateTask(claims.orgId, taskId, patch);
if (!updated) return error("That task is not available to this organization.");
return {
content: [
{ type: "text", text: `Updated task "${updated.title}" - now ${updated.status}.` },
],
structuredContent: { task: summarizeTask(updated) },
};
}
export async function executeTaskTool(
claims: ToolTokenClaims,
name: string,
args: Record<string, unknown>,
): Promise<ToolCallResult> {
if (name === "task_create") return createTaskTool(claims, args);
if (name === "task_list") return listTasksTool(claims, args);
if (name === "task_update") return updateTaskTool(claims, args);
return error(`Unknown tool: ${name}`);
}