@catamorphic/fastify-plugin 0.1.0-alpha.39 → 0.1.0-alpha.42
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/NOTICE.txt +7 -0
- package/dist/app.d.ts +2 -0
- package/dist/app.d.ts.map +1 -1
- package/dist/chunk-jytcc42y.js +592 -0
- package/dist/chunk-jytcc42y.js.map +11 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1673 -411
- package/dist/index.js.map +29 -25
- package/dist/mcp-scopes.d.ts +12 -0
- package/dist/mcp-scopes.d.ts.map +1 -0
- package/dist/mcp-server.d.ts +158 -0
- package/dist/mcp-server.d.ts.map +1 -0
- package/dist/mcp-shared.d.ts +3 -50
- package/dist/mcp-shared.d.ts.map +1 -1
- package/dist/mcp.d.ts +4 -2
- package/dist/mcp.d.ts.map +1 -1
- package/dist/mcp.js +6 -4
- package/dist/mcp.js.map +1 -1
- package/dist/plugin.d.ts +26 -2
- package/dist/plugin.d.ts.map +1 -1
- package/dist/project-capabilities.d.ts.map +1 -1
- package/dist/project-mcp-surface.d.ts +3 -4
- package/dist/project-mcp-surface.d.ts.map +1 -1
- package/dist/routes/agent.d.ts.map +1 -1
- package/dist/routes/apps-mcp.d.ts.map +1 -1
- package/dist/routes/client-runners.d.ts.map +1 -1
- package/dist/routes/connection-mcp.d.ts.map +1 -1
- package/dist/routes/documents.d.ts.map +1 -1
- package/dist/routes/environments.d.ts.map +1 -1
- package/dist/routes/project-mcp.d.ts.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/publications.d.ts.map +1 -1
- package/dist/routes/run-errors.d.ts.map +1 -1
- package/dist/routes/runs.d.ts.map +1 -1
- package/dist/routes/server-mcp.d.ts +17 -0
- package/dist/routes/server-mcp.d.ts.map +1 -0
- package/dist/routes/session-mailboxes.d.ts.map +1 -1
- package/dist/routes/triggers.d.ts.map +1 -1
- package/dist/routes/watchers.d.ts.map +1 -1
- package/dist/routes/workflow-enablements.d.ts.map +1 -1
- package/dist/routes/workflows.d.ts.map +1 -1
- package/dist/schemas.d.ts +3684 -28
- package/dist/schemas.d.ts.map +1 -1
- package/dist/session-mcp.d.ts +54 -0
- package/dist/session-mcp.d.ts.map +1 -0
- package/dist/session-tools.d.ts +49 -0
- package/dist/session-tools.d.ts.map +1 -0
- package/package.json +12 -12
- package/src/app.ts +3 -0
- package/src/index.ts +1 -0
- package/src/mcp-scopes.ts +69 -0
- package/src/mcp-server.ts +827 -0
- package/src/mcp-shared.ts +3 -151
- package/src/mcp.ts +6 -5
- package/src/plugin.ts +73 -2
- package/src/project-capabilities.ts +5 -3
- package/src/project-mcp-program.ts +2 -2
- package/src/project-mcp-surface.ts +18 -239
- package/src/routes/agent.ts +384 -41
- package/src/routes/apps-mcp.ts +84 -82
- package/src/routes/client-runners.ts +3 -1
- package/src/routes/connection-mcp.ts +6 -13
- package/src/routes/documents.ts +4 -0
- package/src/routes/environments.ts +49 -1
- package/src/routes/project-mcp.ts +176 -154
- package/src/routes/projects.ts +6 -0
- package/src/routes/publications.ts +2 -0
- package/src/routes/run-errors.ts +5 -1
- package/src/routes/runs.ts +4 -0
- package/src/routes/server-mcp.ts +151 -0
- package/src/routes/session-mailboxes.ts +1 -0
- package/src/routes/triggers.ts +6 -1
- package/src/routes/watchers.ts +1 -0
- package/src/routes/workflow-enablements.ts +132 -1
- package/src/routes/workflows.ts +4 -0
- package/src/schemas.ts +347 -5
- package/src/session-mcp.ts +696 -0
- package/src/session-tools.ts +169 -0
- package/dist/chunk-baagvvm3.js +0 -164
- package/dist/chunk-baagvvm3.js.map +0 -10
|
@@ -0,0 +1,696 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
type CatamorphicCore,
|
|
4
|
+
hasTokenScope,
|
|
5
|
+
type Identity,
|
|
6
|
+
parseWaitCursor,
|
|
7
|
+
SESSION_OPERATIONS,
|
|
8
|
+
type SessionState,
|
|
9
|
+
SessionStateSchema,
|
|
10
|
+
type SessionWait,
|
|
11
|
+
sessionOperationError,
|
|
12
|
+
} from "@catamorphic/core";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import {
|
|
15
|
+
declaresElicitation,
|
|
16
|
+
declaresTasks,
|
|
17
|
+
MCP_ERROR,
|
|
18
|
+
type McpCallContext,
|
|
19
|
+
McpError,
|
|
20
|
+
type McpResources,
|
|
21
|
+
type McpTasks,
|
|
22
|
+
type McpTool,
|
|
23
|
+
type McpToolResult,
|
|
24
|
+
type McpWatch,
|
|
25
|
+
} from "./mcp-server.js";
|
|
26
|
+
import {
|
|
27
|
+
ATTENTION_RESOURCE_URI,
|
|
28
|
+
sessionResourceUri,
|
|
29
|
+
sessionToolAuthor,
|
|
30
|
+
sessionToolError,
|
|
31
|
+
sessionToolResult,
|
|
32
|
+
sessionTools,
|
|
33
|
+
} from "./session-tools.js";
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* What the current protocol adds to the session tools (ADR 0347): a chat
|
|
37
|
+
* as a resource a client can read and listen to, a wait as a durable task,
|
|
38
|
+
* and an agent's question asked of the client's person in the same call.
|
|
39
|
+
* All three are conveniences over the plain tools, which every client can
|
|
40
|
+
* use: nothing here is the only way to do anything.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/** How long a client may take to answer what a wait asked it. */
|
|
44
|
+
const REQUEST_STATE_TTL_MS = 30 * 60_000;
|
|
45
|
+
/** How often a client should look at a task again. */
|
|
46
|
+
const TASK_POLL_INTERVAL_MS = 2_000;
|
|
47
|
+
/** A task is answered inline when its wait ends within this. */
|
|
48
|
+
const TASK_INLINE_WAIT_SECONDS = 2;
|
|
49
|
+
|
|
50
|
+
type Request = SessionState["requests"][number];
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A request as the form a client shows its person, or nothing when it
|
|
54
|
+
* cannot be asked that way (an approval without the scope, a URL).
|
|
55
|
+
*/
|
|
56
|
+
export function elicitationFor(
|
|
57
|
+
request: Request,
|
|
58
|
+
options: { mayApprove: boolean },
|
|
59
|
+
): Record<string, unknown> | undefined {
|
|
60
|
+
const form = (message: string, requestedSchema: Record<string, unknown>) => ({
|
|
61
|
+
method: "elicitation/create",
|
|
62
|
+
params: { mode: "form", message, requestedSchema },
|
|
63
|
+
});
|
|
64
|
+
if (request.kind === "question" && request.questions?.length) {
|
|
65
|
+
const properties: Record<string, unknown> = {};
|
|
66
|
+
request.questions.forEach((question, index) => {
|
|
67
|
+
const labels = question.options.map((option) => option.label);
|
|
68
|
+
const described = {
|
|
69
|
+
title: question.header || `Question ${index + 1}`,
|
|
70
|
+
description: question.question,
|
|
71
|
+
};
|
|
72
|
+
properties[`answer${index + 1}`] =
|
|
73
|
+
labels.length === 0
|
|
74
|
+
? { type: "string", ...described }
|
|
75
|
+
: question.multiSelect
|
|
76
|
+
? {
|
|
77
|
+
type: "array",
|
|
78
|
+
...described,
|
|
79
|
+
minItems: 1,
|
|
80
|
+
items: { type: "string", enum: labels },
|
|
81
|
+
}
|
|
82
|
+
: { type: "string", ...described, enum: labels };
|
|
83
|
+
});
|
|
84
|
+
return form(request.title || "The agent has a question", {
|
|
85
|
+
type: "object",
|
|
86
|
+
properties,
|
|
87
|
+
required: Object.keys(properties),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
if (request.kind === "approval" && request.approval && options.mayApprove)
|
|
91
|
+
return form(
|
|
92
|
+
[request.title, request.approval.action, request.approval.details]
|
|
93
|
+
.filter(Boolean)
|
|
94
|
+
.join("\n"),
|
|
95
|
+
{
|
|
96
|
+
type: "object",
|
|
97
|
+
properties: {
|
|
98
|
+
decision: {
|
|
99
|
+
type: "string",
|
|
100
|
+
title: "Decision",
|
|
101
|
+
description:
|
|
102
|
+
"always: approve, and allow this tool from now on without asking",
|
|
103
|
+
enum: ["approve", "deny", "always"],
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
required: ["decision"],
|
|
107
|
+
},
|
|
108
|
+
);
|
|
109
|
+
if (request.kind === "elicitation" && request.elicitation?.schema)
|
|
110
|
+
return form(request.elicitation.message, request.elicitation.schema);
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const Elicited = z.looseObject({
|
|
115
|
+
action: z.enum(["accept", "decline", "cancel"]),
|
|
116
|
+
content: z.record(z.string(), z.unknown()).optional(),
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A person's answer to a form as the response the chat's request takes,
|
|
121
|
+
* or nothing when they declined: the request stays open in the chat.
|
|
122
|
+
*/
|
|
123
|
+
export function responseFor(
|
|
124
|
+
request: Request,
|
|
125
|
+
answer: unknown,
|
|
126
|
+
): Record<string, unknown> | undefined {
|
|
127
|
+
const elicited = Elicited.safeParse(answer);
|
|
128
|
+
if (!elicited.success) return undefined;
|
|
129
|
+
const content = elicited.data.content ?? {};
|
|
130
|
+
if (request.kind === "elicitation")
|
|
131
|
+
return {
|
|
132
|
+
kind: "elicitation",
|
|
133
|
+
action: elicited.data.action,
|
|
134
|
+
...(elicited.data.action === "accept" ? { content } : {}),
|
|
135
|
+
};
|
|
136
|
+
if (elicited.data.action !== "accept") return undefined;
|
|
137
|
+
if (request.kind === "approval") {
|
|
138
|
+
const decision = content.decision;
|
|
139
|
+
if (decision !== "approve" && decision !== "deny" && decision !== "always")
|
|
140
|
+
return undefined;
|
|
141
|
+
return {
|
|
142
|
+
kind: "approval",
|
|
143
|
+
decision: decision === "deny" ? "denied" : "approved",
|
|
144
|
+
...(decision === "always" ? { remember: "always" } : {}),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const answers = (request.questions ?? []).map((_question, index) => {
|
|
148
|
+
const value = content[`answer${index + 1}`];
|
|
149
|
+
return Array.isArray(value) ? value.map(String).join(", ") : value;
|
|
150
|
+
});
|
|
151
|
+
if (answers.some((value) => typeof value !== "string" || value === ""))
|
|
152
|
+
return undefined;
|
|
153
|
+
return { kind: "question", answers };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const RequestState = z.object({
|
|
157
|
+
/** The member the state was handed to. */
|
|
158
|
+
sub: z.string(),
|
|
159
|
+
tool: z.literal("session_wait"),
|
|
160
|
+
sessions: z.array(z.string()),
|
|
161
|
+
requests: z.array(z.string()),
|
|
162
|
+
exp: z.number(),
|
|
163
|
+
});
|
|
164
|
+
type RequestStatePayload = z.infer<typeof RequestState>;
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The state a wait hands out with what it asks (MRTR): who was asked, for
|
|
168
|
+
* which chats and requests, and until when, under an HMAC. A client only
|
|
169
|
+
* echoes it; anything else fails here.
|
|
170
|
+
*/
|
|
171
|
+
export function signRequestState(
|
|
172
|
+
payload: RequestStatePayload,
|
|
173
|
+
secret: string,
|
|
174
|
+
): string {
|
|
175
|
+
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
176
|
+
const mac = createHmac("sha256", secret).update(body).digest("base64url");
|
|
177
|
+
return `${body}.${mac}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function verifyRequestState(
|
|
181
|
+
state: string,
|
|
182
|
+
expected: { sub: string; sessions: readonly string[]; secret: string },
|
|
183
|
+
): RequestStatePayload {
|
|
184
|
+
const refuse = () =>
|
|
185
|
+
new McpError(
|
|
186
|
+
MCP_ERROR.invalidParams,
|
|
187
|
+
"Invalid or expired requestState: call session_wait again without it.",
|
|
188
|
+
{ status: 400 },
|
|
189
|
+
);
|
|
190
|
+
const [body, mac, ...rest] = state.split(".");
|
|
191
|
+
if (!body || !mac || rest.length > 0) throw refuse();
|
|
192
|
+
const wanted = createHmac("sha256", expected.secret).update(body).digest();
|
|
193
|
+
const given = Buffer.from(mac, "base64url");
|
|
194
|
+
if (given.length !== wanted.length || !timingSafeEqual(given, wanted))
|
|
195
|
+
throw refuse();
|
|
196
|
+
let payload: RequestStatePayload;
|
|
197
|
+
try {
|
|
198
|
+
payload = RequestState.parse(
|
|
199
|
+
JSON.parse(Buffer.from(body, "base64url").toString("utf8")),
|
|
200
|
+
);
|
|
201
|
+
} catch {
|
|
202
|
+
throw refuse();
|
|
203
|
+
}
|
|
204
|
+
if (
|
|
205
|
+
payload.sub !== expected.sub ||
|
|
206
|
+
payload.exp <= Date.now() ||
|
|
207
|
+
[...payload.sessions].sort().join() !== [...expected.sessions].sort().join()
|
|
208
|
+
)
|
|
209
|
+
throw refuse();
|
|
210
|
+
return payload;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const WaitArgs = SESSION_OPERATIONS.session_wait.input;
|
|
214
|
+
const WaitResult = SESSION_OPERATIONS.session_wait.output;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The session tools with what the current protocol adds, the chats as
|
|
218
|
+
* resources, and waits as tasks, for one caller. `projectId` binds them
|
|
219
|
+
* to a project; without it they serve every project the caller may use.
|
|
220
|
+
*/
|
|
221
|
+
export function sessionMcp(args: {
|
|
222
|
+
core: CatamorphicCore;
|
|
223
|
+
identity: Identity;
|
|
224
|
+
projectId?: string;
|
|
225
|
+
currentSessionId?: string;
|
|
226
|
+
/** Signs the state a wait hands out; the same on every replica. */
|
|
227
|
+
stateSecret: string;
|
|
228
|
+
}): { tools: McpTool[]; resources: McpResources; tasks: McpTasks } | undefined {
|
|
229
|
+
const { core, identity } = args;
|
|
230
|
+
const operations = core.sessionOperations;
|
|
231
|
+
const sessions = core.agentSessions;
|
|
232
|
+
if (!operations || !sessions) return undefined;
|
|
233
|
+
const principal = `${identity.tenantId}:${identity.externalUserId}`;
|
|
234
|
+
const mayApprove = hasTokenScope(identity, "sessions:approve");
|
|
235
|
+
const projectOf = async (sessionId: string) =>
|
|
236
|
+
args.projectId ??
|
|
237
|
+
(await sessions.projectOfSession({ identity, sessionId }));
|
|
238
|
+
|
|
239
|
+
const run = async (
|
|
240
|
+
operation: "session_wait" | "session_answer",
|
|
241
|
+
input: unknown,
|
|
242
|
+
signal?: AbortSignal,
|
|
243
|
+
) =>
|
|
244
|
+
operations.execute({
|
|
245
|
+
identity,
|
|
246
|
+
...(args.projectId ? { projectId: args.projectId } : {}),
|
|
247
|
+
operation,
|
|
248
|
+
args: input,
|
|
249
|
+
...(await sessionToolAuthor({
|
|
250
|
+
core,
|
|
251
|
+
identity,
|
|
252
|
+
projectId: args.projectId,
|
|
253
|
+
currentSessionId: args.currentSessionId,
|
|
254
|
+
})),
|
|
255
|
+
...(signal ? { signal } : {}),
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
/** The forms for what these chats ask, by request id. */
|
|
259
|
+
const asks = (states: readonly SessionState[]) => {
|
|
260
|
+
const inputRequests: Record<string, unknown> = {};
|
|
261
|
+
for (const state of states)
|
|
262
|
+
for (const request of state.requests) {
|
|
263
|
+
const form = request.blocking
|
|
264
|
+
? elicitationFor(request, { mayApprove })
|
|
265
|
+
: undefined;
|
|
266
|
+
if (form) inputRequests[request.requestId] = form;
|
|
267
|
+
}
|
|
268
|
+
return inputRequests;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/** Answer the chats' requests a client's person filled in. */
|
|
272
|
+
const answer = async (
|
|
273
|
+
states: readonly SessionState[],
|
|
274
|
+
inputResponses: Record<string, unknown>,
|
|
275
|
+
salt: string,
|
|
276
|
+
) => {
|
|
277
|
+
for (const state of states)
|
|
278
|
+
for (const request of state.requests) {
|
|
279
|
+
if (!(request.requestId in inputResponses)) continue;
|
|
280
|
+
const response = responseFor(
|
|
281
|
+
request,
|
|
282
|
+
inputResponses[request.requestId],
|
|
283
|
+
);
|
|
284
|
+
if (!response) continue;
|
|
285
|
+
await run("session_answer", {
|
|
286
|
+
sessionId: state.sessionId,
|
|
287
|
+
requestId: request.requestId,
|
|
288
|
+
response,
|
|
289
|
+
idempotencyKey: `${salt}:${request.requestId}`,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
const statesOf = async (sessionIds: readonly string[]) => {
|
|
295
|
+
const chats = [];
|
|
296
|
+
for (const sessionId of sessionIds)
|
|
297
|
+
chats.push({ projectId: await projectOf(sessionId), sessionId });
|
|
298
|
+
return sessions.states(identity, { sessions: chats, detail: true });
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
/** The wait tool's answer, as plain tools give it. */
|
|
302
|
+
const waited = (value: unknown): McpToolResult => {
|
|
303
|
+
const shaped = WaitResult.safeParse(value);
|
|
304
|
+
const result = sessionToolResult(shaped.success ? shaped.data : value);
|
|
305
|
+
// A failed turn is a result the caller reads, flagged as an error.
|
|
306
|
+
return shaped.success && shaped.data.state === "failed"
|
|
307
|
+
? { ...result, isError: true }
|
|
308
|
+
: result;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
const base = sessionTools(args);
|
|
312
|
+
const tools = base.map((tool): McpTool => {
|
|
313
|
+
if (tool.definition.name !== "session_wait") return tool;
|
|
314
|
+
return {
|
|
315
|
+
...tool,
|
|
316
|
+
call: async (input, context?: McpCallContext) => {
|
|
317
|
+
const parsed = WaitArgs.safeParse(input);
|
|
318
|
+
if (!parsed.success) return sessionToolError(parsed.error);
|
|
319
|
+
let wait = parsed.data;
|
|
320
|
+
try {
|
|
321
|
+
if (context?.requestState !== undefined) {
|
|
322
|
+
const state = verifyRequestState(context.requestState, {
|
|
323
|
+
sub: principal,
|
|
324
|
+
sessions: wait.sessionIds,
|
|
325
|
+
secret: args.stateSecret,
|
|
326
|
+
});
|
|
327
|
+
await answer(
|
|
328
|
+
(await statesOf(wait.sessionIds)).map((chat) => ({
|
|
329
|
+
...chat,
|
|
330
|
+
requests: chat.requests.filter((request) =>
|
|
331
|
+
state.requests.includes(request.requestId),
|
|
332
|
+
),
|
|
333
|
+
})),
|
|
334
|
+
context.inputResponses ?? {},
|
|
335
|
+
`mrtr:${state.exp}`,
|
|
336
|
+
);
|
|
337
|
+
// What was asked is answered or declined: wait for what is next.
|
|
338
|
+
wait = {
|
|
339
|
+
...wait,
|
|
340
|
+
cursor: undefined,
|
|
341
|
+
...(Object.keys(context.inputResponses ?? {}).length === 0
|
|
342
|
+
? { onInput: "return" as const }
|
|
343
|
+
: {}),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
if (declaresTasks(context)) {
|
|
347
|
+
const quick = SessionStateSchema.extend({
|
|
348
|
+
changed: z.boolean(),
|
|
349
|
+
}).parse(
|
|
350
|
+
await run(
|
|
351
|
+
"session_wait",
|
|
352
|
+
{ ...wait, timeoutSeconds: TASK_INLINE_WAIT_SECONDS },
|
|
353
|
+
context?.signal,
|
|
354
|
+
),
|
|
355
|
+
);
|
|
356
|
+
if (quick.changed && quick.state !== "needs_input")
|
|
357
|
+
return waited(quick);
|
|
358
|
+
const after = parseWaitCursor(quick.cursor, wait.sessionIds);
|
|
359
|
+
const watched = [];
|
|
360
|
+
for (const sessionId of new Set(wait.sessionIds))
|
|
361
|
+
watched.push({
|
|
362
|
+
projectId: await projectOf(sessionId),
|
|
363
|
+
sessionId,
|
|
364
|
+
// A chat that asks now is the task's first thing to say.
|
|
365
|
+
...(quick.state === "needs_input"
|
|
366
|
+
? {}
|
|
367
|
+
: { after: after.get(sessionId) ?? 0 }),
|
|
368
|
+
});
|
|
369
|
+
return taskOf(
|
|
370
|
+
await core.sessionWaits.create({ identity, sessions: watched }),
|
|
371
|
+
{ status: "working", resultType: "task" },
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
const value = SessionStateSchema.extend({
|
|
375
|
+
changed: z.boolean(),
|
|
376
|
+
}).parse(await run("session_wait", wait, context?.signal));
|
|
377
|
+
if (
|
|
378
|
+
value.state === "needs_input" &&
|
|
379
|
+
wait.onInput === "ask" &&
|
|
380
|
+
declaresElicitation(context)
|
|
381
|
+
) {
|
|
382
|
+
const states = await statesOf(wait.sessionIds);
|
|
383
|
+
const inputRequests = asks(states);
|
|
384
|
+
if (Object.keys(inputRequests).length > 0)
|
|
385
|
+
return {
|
|
386
|
+
resultType: "input_required",
|
|
387
|
+
inputRequests,
|
|
388
|
+
requestState: signRequestState(
|
|
389
|
+
{
|
|
390
|
+
sub: principal,
|
|
391
|
+
tool: "session_wait",
|
|
392
|
+
sessions: [...wait.sessionIds],
|
|
393
|
+
requests: Object.keys(inputRequests),
|
|
394
|
+
exp: Date.now() + REQUEST_STATE_TTL_MS,
|
|
395
|
+
},
|
|
396
|
+
args.stateSecret,
|
|
397
|
+
),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
return waited(value);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
if (error instanceof McpError) throw error;
|
|
403
|
+
return sessionToolError(error);
|
|
404
|
+
}
|
|
405
|
+
},
|
|
406
|
+
};
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
const taskOf = (
|
|
410
|
+
wait: SessionWait,
|
|
411
|
+
fields: Record<string, unknown>,
|
|
412
|
+
): Record<string, unknown> => ({
|
|
413
|
+
taskId: wait.id,
|
|
414
|
+
createdAt: wait.createdAt,
|
|
415
|
+
lastUpdatedAt: wait.updatedAt,
|
|
416
|
+
ttlMs: Date.parse(wait.expiresAt) - Date.parse(wait.createdAt),
|
|
417
|
+
pollIntervalMs: TASK_POLL_INTERVAL_MS,
|
|
418
|
+
...fields,
|
|
419
|
+
});
|
|
420
|
+
const unknownTask = () =>
|
|
421
|
+
new McpError(MCP_ERROR.invalidParams, "Unknown task", { status: 404 });
|
|
422
|
+
|
|
423
|
+
/** A task as it stands now: what its wait came to, or what it asks. */
|
|
424
|
+
const task = async (taskId: string): Promise<Record<string, unknown>> => {
|
|
425
|
+
const wait = await core.sessionWaits.get({ identity, id: taskId });
|
|
426
|
+
if (!wait) throw unknownTask();
|
|
427
|
+
if (wait.status === "cancelled")
|
|
428
|
+
return taskOf(wait, { status: "cancelled" });
|
|
429
|
+
if (wait.status === "completed")
|
|
430
|
+
return taskOf(wait, { status: "completed", result: wait.outcome });
|
|
431
|
+
try {
|
|
432
|
+
const hit = await sessions.waitFor(identity, {
|
|
433
|
+
sessions: wait.sessions,
|
|
434
|
+
timeoutMs: 0,
|
|
435
|
+
});
|
|
436
|
+
const states = await sessions.states(identity, {
|
|
437
|
+
sessions: wait.sessions,
|
|
438
|
+
detail: true,
|
|
439
|
+
});
|
|
440
|
+
const asking = states.filter((state) => state.state === "needs_input");
|
|
441
|
+
const inputRequests = asks(asking);
|
|
442
|
+
if (Object.keys(inputRequests).length > 0)
|
|
443
|
+
return taskOf(wait, {
|
|
444
|
+
status: "input_required",
|
|
445
|
+
statusMessage: "An agent is waiting for an answer",
|
|
446
|
+
inputRequests,
|
|
447
|
+
});
|
|
448
|
+
const first = states.find((state) => state.sessionId === hit);
|
|
449
|
+
if (!first)
|
|
450
|
+
return taskOf(wait, {
|
|
451
|
+
status: "working",
|
|
452
|
+
statusMessage:
|
|
453
|
+
states
|
|
454
|
+
.map((state) => state.waiting?.message ?? state.turn?.activity)
|
|
455
|
+
.find((line) => typeof line === "string" && line !== "") ??
|
|
456
|
+
"Working",
|
|
457
|
+
});
|
|
458
|
+
const others = states.filter((state) => state !== first);
|
|
459
|
+
const outcome = waited({
|
|
460
|
+
...first,
|
|
461
|
+
changed: true,
|
|
462
|
+
cursor:
|
|
463
|
+
states.length === 1
|
|
464
|
+
? first.cursor
|
|
465
|
+
: states
|
|
466
|
+
.map((state) => `${state.sessionId}:${state.cursor}`)
|
|
467
|
+
.join(","),
|
|
468
|
+
...(others.length
|
|
469
|
+
? {
|
|
470
|
+
others: others.map((state) => ({
|
|
471
|
+
sessionId: state.sessionId,
|
|
472
|
+
state: state.state,
|
|
473
|
+
cursor: state.cursor,
|
|
474
|
+
})),
|
|
475
|
+
}
|
|
476
|
+
: {}),
|
|
477
|
+
});
|
|
478
|
+
const done = await core.sessionWaits.complete({
|
|
479
|
+
identity,
|
|
480
|
+
id: wait.id,
|
|
481
|
+
outcome,
|
|
482
|
+
});
|
|
483
|
+
// Whoever recorded the outcome first is what everyone reads.
|
|
484
|
+
return done?.status === "completed"
|
|
485
|
+
? taskOf(done, { status: "completed", result: done.outcome })
|
|
486
|
+
: done
|
|
487
|
+
? taskOf(done, { status: done.status })
|
|
488
|
+
: taskOf(wait, { status: "completed", result: outcome });
|
|
489
|
+
} catch (error) {
|
|
490
|
+
// What the chats can no longer say (closed to the caller, gone) is
|
|
491
|
+
// the task's own result, as a failed tool call is.
|
|
492
|
+
const outcome = sessionToolError(error);
|
|
493
|
+
const done = await core.sessionWaits.complete({
|
|
494
|
+
identity,
|
|
495
|
+
id: wait.id,
|
|
496
|
+
outcome,
|
|
497
|
+
});
|
|
498
|
+
return taskOf(done ?? wait, {
|
|
499
|
+
status: "completed",
|
|
500
|
+
result: done?.outcome ?? outcome,
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
const tasks: McpTasks = {
|
|
506
|
+
get: task,
|
|
507
|
+
update: async (taskId, inputResponses) => {
|
|
508
|
+
const wait = await core.sessionWaits.get({ identity, id: taskId });
|
|
509
|
+
if (!wait) throw unknownTask();
|
|
510
|
+
if (wait.status !== "working") return;
|
|
511
|
+
await answer(
|
|
512
|
+
await sessions.states(identity, {
|
|
513
|
+
sessions: wait.sessions,
|
|
514
|
+
detail: true,
|
|
515
|
+
}),
|
|
516
|
+
inputResponses,
|
|
517
|
+
`task:${wait.id}`,
|
|
518
|
+
).catch((error: unknown) => {
|
|
519
|
+
throw new McpError(
|
|
520
|
+
MCP_ERROR.invalidParams,
|
|
521
|
+
sessionOperationError(error).message,
|
|
522
|
+
);
|
|
523
|
+
});
|
|
524
|
+
},
|
|
525
|
+
// Only the watching ends: the agent works on, and its chat is there
|
|
526
|
+
// to wait on again.
|
|
527
|
+
cancel: async (taskId) => {
|
|
528
|
+
if (!(await core.sessionWaits.cancel({ identity, id: taskId })))
|
|
529
|
+
throw unknownTask();
|
|
530
|
+
},
|
|
531
|
+
watch: async (taskIds, changed) => {
|
|
532
|
+
const seen = new Map<string, string>();
|
|
533
|
+
const accepted: string[] = [];
|
|
534
|
+
for (const taskId of taskIds)
|
|
535
|
+
if (await core.sessionWaits.get({ identity, id: taskId }))
|
|
536
|
+
accepted.push(taskId);
|
|
537
|
+
let stopped = false;
|
|
538
|
+
const look = async () => {
|
|
539
|
+
for (const taskId of accepted) {
|
|
540
|
+
if (stopped) return;
|
|
541
|
+
const state = await task(taskId).catch(() => undefined);
|
|
542
|
+
if (!state) continue;
|
|
543
|
+
const print = JSON.stringify([
|
|
544
|
+
state.status,
|
|
545
|
+
Object.keys(
|
|
546
|
+
typeof state.inputRequests === "object" && state.inputRequests
|
|
547
|
+
? state.inputRequests
|
|
548
|
+
: {},
|
|
549
|
+
),
|
|
550
|
+
]);
|
|
551
|
+
if (seen.get(taskId) === print) continue;
|
|
552
|
+
const first = !seen.has(taskId);
|
|
553
|
+
seen.set(taskId, print);
|
|
554
|
+
// A listener hears what changes after it started listening.
|
|
555
|
+
if (!first || state.status !== "working") changed(state);
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
await look();
|
|
559
|
+
const timer = setInterval(() => void look(), TASK_POLL_INTERVAL_MS);
|
|
560
|
+
timer.unref?.();
|
|
561
|
+
return {
|
|
562
|
+
accepted,
|
|
563
|
+
stop: () => {
|
|
564
|
+
stopped = true;
|
|
565
|
+
clearInterval(timer);
|
|
566
|
+
},
|
|
567
|
+
};
|
|
568
|
+
},
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
const attention = async () => {
|
|
572
|
+
const waiting = (await sessions.attention({ identity })).filter(
|
|
573
|
+
(session) => !args.projectId || session.projectId === args.projectId,
|
|
574
|
+
);
|
|
575
|
+
return sessions.states(identity, {
|
|
576
|
+
sessions: waiting.map((session) => ({
|
|
577
|
+
projectId: session.projectId,
|
|
578
|
+
sessionId: session.id,
|
|
579
|
+
})),
|
|
580
|
+
detail: false,
|
|
581
|
+
listed: true,
|
|
582
|
+
});
|
|
583
|
+
};
|
|
584
|
+
const sessionIdOf = (uri: string) =>
|
|
585
|
+
/^work:\/\/sessions\/([0-9a-f-]{36})$/i.exec(uri)?.[1];
|
|
586
|
+
const notFound = (uri: string) =>
|
|
587
|
+
new McpError(MCP_ERROR.invalidParams, `Resource not found: ${uri}`, {
|
|
588
|
+
data: { uri },
|
|
589
|
+
});
|
|
590
|
+
const json = (uri: string, value: unknown) => [
|
|
591
|
+
{ uri, mimeType: "application/json", text: JSON.stringify(value) },
|
|
592
|
+
];
|
|
593
|
+
|
|
594
|
+
const resources: McpResources = {
|
|
595
|
+
list: async () => [
|
|
596
|
+
{
|
|
597
|
+
uri: ATTENTION_RESOURCE_URI,
|
|
598
|
+
name: "attention",
|
|
599
|
+
title: "Chats that need you",
|
|
600
|
+
description:
|
|
601
|
+
"The chats waiting on you: an agent asked something, or a turn failed. Listen to it to hear when one does.",
|
|
602
|
+
mimeType: "application/json",
|
|
603
|
+
},
|
|
604
|
+
],
|
|
605
|
+
templates: async () => [
|
|
606
|
+
{
|
|
607
|
+
uriTemplate: sessionResourceUri("{sessionId}"),
|
|
608
|
+
name: "session",
|
|
609
|
+
title: "A chat's state",
|
|
610
|
+
description:
|
|
611
|
+
"One chat as session_read returns it. Listen to it to hear when it changes.",
|
|
612
|
+
mimeType: "application/json",
|
|
613
|
+
},
|
|
614
|
+
],
|
|
615
|
+
read: async (uri) => {
|
|
616
|
+
if (uri === ATTENTION_RESOURCE_URI)
|
|
617
|
+
return json(uri, { sessions: await attention() });
|
|
618
|
+
const sessionId = sessionIdOf(uri);
|
|
619
|
+
if (!sessionId) throw notFound(uri);
|
|
620
|
+
const [state] = await statesOf([sessionId]).catch(() => []);
|
|
621
|
+
if (!state) throw notFound(uri);
|
|
622
|
+
return json(uri, state);
|
|
623
|
+
},
|
|
624
|
+
watch: async (uris, changed, ended) => {
|
|
625
|
+
const stops: Array<() => void> = [];
|
|
626
|
+
const accepted: string[] = [];
|
|
627
|
+
const timers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
628
|
+
// A burst of events is one change to whoever listens.
|
|
629
|
+
const soon = (uri: string) => {
|
|
630
|
+
if (timers.has(uri)) return;
|
|
631
|
+
timers.set(
|
|
632
|
+
uri,
|
|
633
|
+
setTimeout(() => {
|
|
634
|
+
timers.delete(uri);
|
|
635
|
+
changed(uri);
|
|
636
|
+
}, 250),
|
|
637
|
+
);
|
|
638
|
+
};
|
|
639
|
+
for (const uri of new Set(uris)) {
|
|
640
|
+
if (uri === ATTENTION_RESOURCE_URI) {
|
|
641
|
+
const print = async () =>
|
|
642
|
+
JSON.stringify(
|
|
643
|
+
(await sessions.attention({ identity }))
|
|
644
|
+
.filter(
|
|
645
|
+
(session) =>
|
|
646
|
+
!args.projectId || session.projectId === args.projectId,
|
|
647
|
+
)
|
|
648
|
+
.map((session) => [session.id, session.attentionRevision]),
|
|
649
|
+
);
|
|
650
|
+
let last = await print();
|
|
651
|
+
const timer = setInterval(() => {
|
|
652
|
+
void print()
|
|
653
|
+
.then((next) => {
|
|
654
|
+
if (next === last) return;
|
|
655
|
+
last = next;
|
|
656
|
+
changed(uri);
|
|
657
|
+
})
|
|
658
|
+
.catch(() => {});
|
|
659
|
+
}, 2_000);
|
|
660
|
+
timer.unref?.();
|
|
661
|
+
stops.push(() => clearInterval(timer));
|
|
662
|
+
accepted.push(uri);
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
const sessionId = sessionIdOf(uri);
|
|
666
|
+
const [state] = sessionId
|
|
667
|
+
? await statesOf([sessionId]).catch(() => [])
|
|
668
|
+
: [];
|
|
669
|
+
if (!sessionId || !state) continue;
|
|
670
|
+
stops.push(
|
|
671
|
+
await sessions.subscribe(identity, state.projectId, sessionId, {
|
|
672
|
+
after: Number(state.cursor),
|
|
673
|
+
send: () => {
|
|
674
|
+
soon(uri);
|
|
675
|
+
return true;
|
|
676
|
+
},
|
|
677
|
+
// The caller may no longer read it, or the server is stopping.
|
|
678
|
+
onClose: ended,
|
|
679
|
+
}),
|
|
680
|
+
);
|
|
681
|
+
accepted.push(uri);
|
|
682
|
+
}
|
|
683
|
+
const watch: McpWatch = {
|
|
684
|
+
accepted,
|
|
685
|
+
stop: () => {
|
|
686
|
+
for (const stop of stops) stop();
|
|
687
|
+
for (const timer of timers.values()) clearTimeout(timer);
|
|
688
|
+
timers.clear();
|
|
689
|
+
},
|
|
690
|
+
};
|
|
691
|
+
return watch;
|
|
692
|
+
},
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
return { tools, resources, tasks };
|
|
696
|
+
}
|