@arbol-ai/maximus 8.1.0 → 8.4.0

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 (62) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +3 -3
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -2
  5. package/dist/capture/index.d.ts +1 -1
  6. package/dist/capture/index.js +3 -4
  7. package/dist/chunks/{define-app-BxGZdNmS.js → define-app-CQpWqqqE.js} +33 -14
  8. package/dist/chunks/{json-B14evE6-.js → destination-DIkn8W6K.js} +65 -1
  9. package/dist/chunks/{digest-C7UGt760.js → digest-C51F1bhA.js} +1 -2
  10. package/dist/chunks/{errors-CWgE9uvM.js → errors-BoutSmiy.js} +2 -3
  11. package/dist/chunks/{execution-BTiAWA4n.js → execution-Bpq6s4nA.js} +9 -8
  12. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  13. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  14. package/dist/chunks/{http-layout-BvlbD__1.js → http-layout-BcYH4I2w.js} +1 -1
  15. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  16. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  17. package/dist/chunks/{openapi-BF3eCpux.js → openapi-D2rds7vy.js} +27 -116
  18. package/dist/chunks/{openapi-file-RcXoq0AF.js → openapi-file-BK8zET5U.js} +24 -6
  19. package/dist/chunks/{pages-BCksUeRf.js → pages-B7ysoFAM.js} +1 -1
  20. package/dist/chunks/result-CF4OzG9O.js +29 -0
  21. package/dist/chunks/{runtime-D5eR9-Es.js → runtime-CGtS2rOb.js} +132 -7
  22. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  23. package/dist/chunks/{server-B9C8KPwa.js → server-CVhTLNj2.js} +37 -101
  24. package/dist/chunks/{src-C-4z443M.js → src-D67OfW9B.js} +40 -19
  25. package/dist/chunks/tasks-C873C3le.js +100 -0
  26. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  27. package/dist/chunks/{types-Dqo3oGig.d.ts → types-BfGa2aJT.d.ts} +346 -138
  28. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  29. package/dist/chunks/{workers-types-BgjyDtGd.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  30. package/dist/diagnostics.d.ts +1 -1
  31. package/dist/errors.d.ts +1 -1
  32. package/dist/errors.js +1 -1
  33. package/dist/http-paths.d.ts +1 -1
  34. package/dist/http-paths.js +1 -1
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +11 -10
  37. package/dist/internals.d.ts +1 -1
  38. package/dist/internals.js +4 -4
  39. package/dist/mcp/index.d.ts +1 -1
  40. package/dist/mcp/index.js +1 -1
  41. package/dist/mcp/tasks.d.ts +33 -0
  42. package/dist/mcp/tasks.js +3 -0
  43. package/dist/project/config.d.ts +2 -2
  44. package/dist/project/config.js +3 -2
  45. package/dist/project/index.d.ts +2 -2
  46. package/dist/project/index.js +3 -3
  47. package/dist/schemas.d.ts +2 -2
  48. package/dist/schemas.js +3 -3
  49. package/dist/standard-failures.d.ts +1 -1
  50. package/dist/tooling/cli.js +2 -2
  51. package/dist/vite/index.d.ts +1 -1
  52. package/dist/vite/index.js +6 -5
  53. package/dist/webhooks.d.ts +13 -2
  54. package/dist/webhooks.js +38 -1
  55. package/dist/workers/runtime.d.ts +1 -1
  56. package/dist/workers/runtime.js +1 -1
  57. package/package.json +11 -3
  58. package/skills/maximus/SKILL.md +7 -4
  59. package/skills/maximus/references/routes-and-tools.md +9 -1
  60. package/dist/chunks/result-CKgZHrnj.js +0 -56
  61. package/dist/chunks/schemas-BOFxZP1c.js +0 -227
  62. package/dist/chunks/validation-DMu0rkMQ.js +0 -670
@@ -1,46 +1,21 @@
1
- import { C as wireInput } from "./validation-DMu0rkMQ.js";
2
- import { i as standardErrors } from "./errors-CWgE9uvM.js";
3
- import { C as MAX_BODY_BYTES_CEILING, D as mcpOpenWorld, d as canonical, k as operationMatchesScopes, p as standaloneSchema } from "./openapi-BF3eCpux.js";
4
- import { t as sha256Hex } from "./digest-C7UGt760.js";
1
+ import { L as wireInput } from "./schemas-_UJcx_uY.js";
2
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
3
+ import { d as MAX_BODY_BYTES_CEILING, h as mcpOpenWorld, v as operationMatchesScopes } from "./tasks-DYdY-dBI.js";
4
+ import { d as canonical, p as standaloneSchema } from "./openapi-D2rds7vy.js";
5
5
  import { o as reportUnexpected } from "./telemetry-BtxJh69Q.js";
6
6
  import { t as toYaml } from "./yaml-Dk2L24yQ.js";
7
- import { Type } from "@sinclair/typebox";
8
- import { Value } from "@sinclair/typebox/value";
7
+ import { a as mcpTask, n as attachTasks, o as toolResult, r as declaresTasks } from "./tasks-C873C3le.js";
9
8
  import { McpServer, ProtocolError, ProtocolErrorCode, createMcpHandler } from "@modelcontextprotocol/server";
9
+ import { SkillCatalog, memorySkillFiles } from "@modelcontextprotocol/server/ext/skills";
10
10
 
11
11
  // src/mcp/skills.ts
12
- /**
13
- * The MCP Skills extension (SEP-2640): `skills/list` and `skills/get` describe each skill by its
14
- * frontmatter and the manifest of its one file, whose size and SHA-256 digest hosts verify, and
15
- * `resources/read` serves that `SKILL.md`. An optional tool serves the same skills to clients that import
16
- * only tools.
17
- */
18
- /** The official Skills extension (SEP-2640) a server declares in its capabilities. */
19
- const SKILLS_EXTENSION = "io.modelcontextprotocol/skills";
20
12
  /** Skills change only with a deployment and are the same for every caller, so hosts may share them. */
21
13
  const SKILL_CACHE = {
22
14
  ttlMs: 3e5,
23
15
  cacheScope: "public"
24
16
  };
25
- /** Adapts a TypeBox schema to the Standard Schema the SDK validates custom method params with. */
26
- function standardSchema(schema) {
27
- return { "~standard": {
28
- version: 1,
29
- vendor: "maximus",
30
- validate: (value) => Value.Check(schema, value) ? { value } : { issues: [{ message: "Invalid params" }] }
31
- } };
32
- }
33
- /** `skills/list` params: an optional page cursor, which one page of every skill never issues. */
34
- const ListSkillsParams = standardSchema(Type.Object({ cursor: Type.Optional(Type.String()) }));
35
- /** `skills/get` params: the URI of the skill's `SKILL.md`. */
36
- const GetSkillParams = standardSchema(Type.Object({ uri: Type.String() }));
37
- /**
38
- * A skill's `SKILL.md` URI, `skill://<name>/SKILL.md`: the file's directory carries the skill's name, as
39
- * SEP-2640 requires.
40
- */
41
- function skillUri(skill) {
42
- return `skill://${skill.name}/SKILL.md`;
43
- }
17
+ /** Each application's catalog, built on first use: an application's skills never change. */
18
+ const catalogs = /* @__PURE__ */ new WeakMap();
44
19
  /** The served `SKILL.md`: frontmatter generated from the name and description, then the instructions. */
45
20
  function skillDocument(skill) {
46
21
  return `---\n${toYaml({
@@ -48,58 +23,23 @@ function skillDocument(skill) {
48
23
  description: skill.description
49
24
  })}---\n\n${skill.text.trim()}\n`;
50
25
  }
51
- /** A catalog entry. Hosts verify every file they read against its manifest's size and SHA-256 digest. */
52
- async function skillEntry(skill) {
53
- const uri = skillUri(skill);
54
- const bytes = new TextEncoder().encode(skillDocument(skill));
55
- return {
56
- uri,
57
- frontmatter: {
58
- name: skill.name,
59
- description: skill.description
60
- },
61
- resources: [{
62
- uri,
63
- digest: `sha256:${await sha256Hex(bytes)}`,
64
- size: bytes.byteLength
65
- }]
66
- };
67
- }
68
26
  /**
69
- * Serves skills through the Skills extension: `skills/list`, `skills/get`, and `resources/read` of each
70
- * `SKILL.md`, each request answered through `answer`, which reports an unexpected failure without its text.
71
- * Clients without the extension still find the files among the server's resources.
27
+ * The catalog that serves the skills through the Skills extension, each as `skill://<name>/SKILL.md`, every
28
+ * one on a single `skills/list` page, with the public cache hint. Building it checks each skill as hosts do,
29
+ * and throws for one they would refuse.
72
30
  */
73
- function registerSkills(server, skills, answer) {
74
- for (const skill of skills) {
75
- const uri = skillUri(skill);
76
- server.registerResource(skill.name, uri, {
77
- description: skill.description,
78
- mimeType: "text/markdown",
79
- cacheHint: SKILL_CACHE
80
- }, () => answer(() => ({ contents: [{
81
- uri,
82
- mimeType: "text/markdown",
83
- text: skillDocument(skill)
84
- }] })));
31
+ async function skillCatalog(skills) {
32
+ let catalog = catalogs.get(skills);
33
+ if (!catalog) {
34
+ const files = Object.fromEntries(skills.map((skill) => [`${skill.name}/SKILL.md`, skillDocument(skill)]));
35
+ catalog = await SkillCatalog.load(memorySkillFiles(files), {
36
+ cacheHint: SKILL_CACHE,
37
+ pageSize: Number.POSITIVE_INFINITY,
38
+ strict: true
39
+ });
40
+ catalogs.set(skills, catalog);
85
41
  }
86
- server.server.setRequestHandler("skills/list", { params: ListSkillsParams }, (params) => answer(async () => {
87
- if (params.cursor !== void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid skills cursor");
88
- return {
89
- resultType: "complete",
90
- skills: await Promise.all(skills.map(skillEntry)),
91
- ...SKILL_CACHE
92
- };
93
- }));
94
- server.server.setRequestHandler("skills/get", { params: GetSkillParams }, (params) => answer(async () => {
95
- const skill = skills.find((candidate) => skillUri(candidate) === params.uri);
96
- if (!skill) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Unknown skill");
97
- return {
98
- resultType: "complete",
99
- skill: await skillEntry(skill),
100
- ...SKILL_CACHE
101
- };
102
- }));
42
+ return catalog;
103
43
  }
104
44
  /**
105
45
  * The same skills as one read-only tool, for clients that import only tools. Its description names every
@@ -285,7 +225,7 @@ function carriedMessages(body) {
285
225
  * lets a stateless server list the caller's tools, run them through `invoke` and serve the resources,
286
226
  * prompts and skills. A 5xx answer is reported as an unexpected error.
287
227
  */
288
- async function handleMcp({ request, requestId, authenticated, application, operations, contractText, url, invoke, admitCarried, refused, body, bodyLimit }) {
228
+ async function handleMcp({ request, requestId, authenticated, application, operations, contractText, url, invoke, admitCarried, refused, body, bodyLimit, tasks }) {
289
229
  const refusal = await admitCarried(carriedMessages(body) - 1);
290
230
  if (refusal) return refusal;
291
231
  const bodyBytes = new TextEncoder().encode(body).byteLength;
@@ -304,7 +244,7 @@ async function handleMcp({ request, requestId, authenticated, application, opera
304
244
  throw new ProtocolError(ProtocolErrorCode.InternalError, "Internal error");
305
245
  }
306
246
  };
307
- const response = await createMcpHandler(() => {
247
+ const response = await createMcpHandler(async () => {
308
248
  const skills = application.mcp?.skills ?? [];
309
249
  const skillToolName = skills.length ? application.mcp?.skillTool : void 0;
310
250
  const server = new McpServer({
@@ -316,12 +256,11 @@ async function handleMcp({ request, requestId, authenticated, application, opera
316
256
  capabilities: {
317
257
  tools: { listChanged: false },
318
258
  resources: { listChanged: false },
319
- prompts: { listChanged: false },
320
- ...skills.length ? { extensions: { [SKILLS_EXTENSION]: {} } } : {}
259
+ prompts: { listChanged: false }
321
260
  }
322
261
  });
323
262
  const visible = operations.filter((entry) => Boolean(entry[1].mcp) && operationMatchesScopes(entry[1], authenticated.scopes) && (!entry[1].actorKinds || entry[1].actorKinds.includes(authenticated.actorKind)));
324
- server.server.setRequestHandler("tools/call", (call) => answer(async () => {
263
+ server.server.setRequestHandler("tools/call", (call, ctx) => answer(async () => {
325
264
  if (skillToolName && call.params.name === skillToolName) return readSkill(skills, call.params.arguments ?? {});
326
265
  const selected = visible.find(([, op]) => op.mcp.name === call.params.name);
327
266
  if (!selected) {
@@ -341,21 +280,18 @@ async function handleMcp({ request, requestId, authenticated, application, opera
341
280
  }]
342
281
  };
343
282
  }
344
- const result = await invoke(name, op, call.params.arguments ?? {});
345
- return result.ok ? {
346
- content: [{
347
- type: "text",
348
- text: JSON.stringify(result.value)
349
- }],
350
- structuredContent: result.value
351
- } : {
352
- isError: true,
353
- content: [{
354
- type: "text",
355
- text: JSON.stringify(result.error)
356
- }]
283
+ const task = op.task && declaresTasks(ctx.mcpReq.envelope) ? await tasks?.start(name, call.params.arguments ?? {}) : void 0;
284
+ if (task?.status === "working") return {
285
+ ...mcpTask(task),
286
+ resultType: "task"
357
287
  };
288
+ return toolResult(task?.result ?? await invoke(name, op, call.params.arguments ?? {}));
358
289
  }));
290
+ if (tasks && visible.some(([, op]) => op.task)) attachTasks(server, {
291
+ ...tasks,
292
+ get: (id) => answer(() => tasks.get(id)),
293
+ cancel: (id) => answer(() => tasks.cancel(id))
294
+ });
359
295
  server.server.setRequestHandler("tools/list", (listing) => answer(() => {
360
296
  const cursor = listing.params?.cursor;
361
297
  const previous = cursor === void 0 ? -1 : visible.findIndex(([name]) => pageCursor(name) === cursor);
@@ -401,7 +337,7 @@ async function handleMcp({ request, requestId, authenticated, application, opera
401
337
  }
402
338
  }] })));
403
339
  }
404
- if (skills.length) registerSkills(server, skills, answer);
340
+ if (skills.length) (await skillCatalog(skills)).attach(server);
405
341
  return server;
406
342
  }, { maxRequestBodySize: MAX_BODY_BYTES_CEILING }).fetch(request);
407
343
  if (response.status >= 500) reportUnexpected(/* @__PURE__ */ new Error("MCP transport failure"), "mcp", requestId);
@@ -1,16 +1,17 @@
1
- import { i as standardErrors } from "./errors-CWgE9uvM.js";
1
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
2
2
  import { r as readBodyText } from "./body-DOIHwIIl.js";
3
- import { i as binaryBody, n as defineApp, r as attachmentResponse } from "./define-app-BxGZdNmS.js";
4
- import { t as createHttpRouteResolver } from "./http-paths-DMBxwpp6.js";
5
- import { r as ok, t as err } from "./result-CKgZHrnj.js";
6
- import { E as isPublicOperation, S as DEFAULT_MAX_BODY_BYTES, T as composeOperations, c as tokenAudiences, g as isCrossSiteWrite, h as queryKinds, i as createTokenAuthorization, j as operationScopes, k as operationMatchesScopes, l as tokenIssuer, m as queryInput, o as presentedToken, t as createOpenApi } from "./openapi-BF3eCpux.js";
7
- import { t as sha256Hex } from "./digest-C7UGt760.js";
3
+ import { i as binaryBody, n as defineApp, r as attachmentResponse } from "./define-app-CQpWqqqE.js";
4
+ import { t as createHttpRouteResolver } from "./http-paths-D043DkJv.js";
5
+ import { a as taskAccess, b as operationScopes, m as isPublicOperation, o as taskView, p as composeOperations, s as withTaskOperations, u as DEFAULT_MAX_BODY_BYTES, v as operationMatchesScopes } from "./tasks-DYdY-dBI.js";
6
+ import { c as tokenAudiences, g as isCrossSiteWrite, h as queryKinds, i as createTokenAuthorization, l as tokenIssuer, m as queryInput, o as presentedToken, t as createOpenApi } from "./openapi-D2rds7vy.js";
7
+ import { r as ok, t as err } from "./result-CF4OzG9O.js";
8
+ import { t as sha256Hex } from "./digest-C51F1bhA.js";
8
9
  import { a as recordExecution, i as recordAdmission, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
9
- import { n as recordCapture, t as executeOperation } from "./execution-BTiAWA4n.js";
10
- import { a as ownsPrefix, i as nativePaths, n as composition, o as servesCloudflareAccess, r as httpTransports, s as servesOwnBearer, t as VERSIONED_PATH } from "./http-layout-BvlbD__1.js";
11
- import { n as mediaType } from "./json-B14evE6-.js";
10
+ import { n as recordCapture, t as executeOperation } from "./execution-Bpq6s4nA.js";
11
+ import { a as ownsPrefix, i as nativePaths, n as composition, o as servesCloudflareAccess, r as httpTransports, s as servesOwnBearer, t as VERSIONED_PATH } from "./http-layout-BcYH4I2w.js";
12
+ import { r as mediaType } from "./destination-DIkn8W6K.js";
12
13
  import { t as toYaml } from "./yaml-Dk2L24yQ.js";
13
- import { Type as Type$1, Type as t } from "@sinclair/typebox";
14
+ import { Type as Type$1, Type as t } from "typebox";
14
15
 
15
16
  // src/builder.ts
16
17
  /**
@@ -103,7 +104,11 @@ var ApplicationBuilder = class ApplicationBuilder {
103
104
  * the rule; most of the rules about one operation also name that operation.
104
105
  */
105
106
  build() {
106
- return defineApp()(this.definition);
107
+ const { operations, namespace } = this.definition;
108
+ return defineApp()({
109
+ ...this.definition,
110
+ operations: withTaskOperations(operations, namespace)
111
+ });
107
112
  }
108
113
  };
109
114
  /**
@@ -403,6 +408,13 @@ function createHttpHandler(manifest, hooks = {}) {
403
408
  requestId
404
409
  };
405
410
  principal = actor;
411
+ const authority = authenticated.client ? {
412
+ surface: transport ? "mcp" : "http",
413
+ scopes: authenticated.scopes,
414
+ client: authenticated.client,
415
+ ...accessToken ? { token: accessToken } : {}
416
+ } : void 0;
417
+ const tasks = taskAccess(manifest, scopedEnv, actor, authority);
406
418
  if (manifest.capture) {
407
419
  const token = presentedToken(incoming, manifest.tokens);
408
420
  verified = {
@@ -459,12 +471,7 @@ function createHttpHandler(manifest, hooks = {}) {
459
471
  if (telemetryEnabled(manifest.telemetry, scopedEnv)) hooks.annotate?.(name, requestId);
460
472
  const call = userAgent ? { userAgent } : {};
461
473
  const invocationStarted = performance.now();
462
- const output = await executeOperation(manifest, op, scopedEnv, actor, input, authenticated.client ? {
463
- surface: transport ? "mcp" : "http",
464
- scopes: authenticated.scopes,
465
- client: authenticated.client,
466
- ...accessToken ? { token: accessToken } : {}
467
- } : void 0, background, byteOperation ? binaryBody(incoming, op.maxBodyBytes ?? fallbackBodyBytes) : void 0, call);
474
+ const output = await executeOperation(manifest, op, scopedEnv, actor, input, authority, background, byteOperation ? binaryBody(incoming, op.maxBodyBytes ?? fallbackBodyBytes) : void 0, call);
468
475
  recordExecution(manifest, scopedEnv, background, {
469
476
  principal: actor,
470
477
  operation: name,
@@ -508,12 +515,26 @@ function createHttpHandler(manifest, hooks = {}) {
508
515
  captureRefusal(error, name ?? null, scopedEnv);
509
516
  },
510
517
  body: bodyText,
511
- bodyLimit: (op) => op.maxBodyBytes ?? fallbackBodyBytes
518
+ bodyLimit: (op) => op.maxBodyBytes ?? fallbackBodyBytes,
519
+ ...tasks ? { tasks } : {}
512
520
  });
513
521
  if (!operationRoute) return reject(standardErrors.notFound.create());
514
522
  const input = operationInput(operationRoute, incoming, url, bodyText);
515
523
  if (!input.ok) return reject(input.error);
516
- const output = await invoke(operationRoute.definition.name, operationRoute.definition.op, input.value);
524
+ const task = operationRoute.definition.op.task && /\brespond-async\b/i.test(incoming.headers.get("prefer") ?? "") ? await tasks?.start(operationRoute.definition.name, input.value) : void 0;
525
+ if (task?.status === "working") return Response.json({
526
+ success: true,
527
+ data: taskView(task),
528
+ error: null,
529
+ metadata: { requestId }
530
+ }, {
531
+ status: 202,
532
+ headers: {
533
+ "preference-applied": "respond-async",
534
+ location: `${manifest.origin}${paths.mount(`/v1/operation-tasks/${task.taskId}`)}`
535
+ }
536
+ });
537
+ const output = task?.result ?? await invoke(operationRoute.definition.name, operationRoute.definition.op, input.value);
517
538
  if (!output.ok) return failure(output.error, requestId, resolutionContext());
518
539
  const exposure = operationRoute.definition.op.http;
519
540
  if (exposure?.response === "attachment") return attachmentResponse(output.value, exposure.successStatus ?? 200);
@@ -0,0 +1,100 @@
1
+ import { i as TASK_POLL_MS } from "./tasks-DYdY-dBI.js";
2
+ import { ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server";
3
+
4
+ // src/mcp/tasks.ts
5
+ /**
6
+ * The MCP Tasks extension (`io.modelcontextprotocol/tasks`, revision 2026-07-28) on the official SDK, in the
7
+ * wire format `@modelcontextprotocol/ext-tasks` defines: the declared extension, `tasks/get` and `tasks/cancel`,
8
+ * a task as a client reads it, and the checks a relay needs. They are a few lines of their own rather than that
9
+ * package's guards, which load all of zod. `@arbol-ai/maximus/mcp/tasks` exports them, so a gateway serves the
10
+ * same methods for the tasks it relays.
11
+ */
12
+ /** The Tasks extension's id, which a client declares on each request and a server among its capabilities. */
13
+ const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
14
+ /** The value, when it is a plain object. */
15
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
16
+ /**
17
+ * Whether a request's `_meta` declares the Tasks extension: an empty object at
18
+ * `io.modelcontextprotocol/clientCapabilities` › `extensions` › `io.modelcontextprotocol/tasks`, as
19
+ * `@modelcontextprotocol/ext-tasks` reads it.
20
+ */
21
+ function declaresTasks(meta) {
22
+ const capabilities = record(record(meta)?.["io.modelcontextprotocol/clientCapabilities"]);
23
+ const extensions = record(capabilities?.extensions);
24
+ const declared = extensions && Object.hasOwn(extensions, "io.modelcontextprotocol/tasks") ? record(extensions[TASKS_EXTENSION]) : void 0;
25
+ return declared !== void 0 && Object.keys(declared).length === 0;
26
+ }
27
+ /** Whether a `tools/call` result is a task the server created, `resultType: "task"`, rather than the call's result. */
28
+ function isTaskResult(result) {
29
+ const task = record(result);
30
+ return task?.resultType === "task" && typeof task.taskId === "string" && [
31
+ "working",
32
+ "input_required",
33
+ "completed",
34
+ "failed",
35
+ "cancelled"
36
+ ].includes(String(task.status));
37
+ }
38
+ /** A Result as a tool call answers it: the value, or the failure as a tool error the model can read. */
39
+ function toolResult(result) {
40
+ return result.ok ? {
41
+ content: [{
42
+ type: "text",
43
+ text: JSON.stringify(result.value)
44
+ }],
45
+ structuredContent: result.value
46
+ } : {
47
+ isError: true,
48
+ content: [{
49
+ type: "text",
50
+ text: JSON.stringify(result.error)
51
+ }]
52
+ };
53
+ }
54
+ /** A task as an MCP client reads it. A failed operation completes its tool call with a tool error. */
55
+ function mcpTask(task) {
56
+ const state = {
57
+ taskId: task.taskId,
58
+ createdAt: new Date(task.createdAt).toISOString(),
59
+ lastUpdatedAt: new Date(task.lastUpdatedAt).toISOString(),
60
+ ttlMs: task.ttlMs,
61
+ pollIntervalMs: TASK_POLL_MS
62
+ };
63
+ if (task.result) return {
64
+ ...state,
65
+ status: "completed",
66
+ result: toolResult(task.result)
67
+ };
68
+ return {
69
+ ...state,
70
+ status: task.status === "cancelled" ? "cancelled" : "working"
71
+ };
72
+ }
73
+ /** The params of `tasks/get` and `tasks/cancel`: the task's id. */
74
+ const TaskIdParams = { "~standard": {
75
+ version: 1,
76
+ vendor: "maximus",
77
+ validate: (params) => {
78
+ const taskId = record(params)?.taskId;
79
+ return typeof taskId === "string" ? { value: { taskId } } : { issues: [{ message: "taskId is a string" }] };
80
+ }
81
+ } };
82
+ /**
83
+ * Declares the Tasks extension on `server` and serves `tasks/get` and `tasks/cancel` for the caller's tasks. A
84
+ * task id the caller did not start, or one that expired, is invalid params (-32602).
85
+ */
86
+ function attachTasks(server, tasks) {
87
+ server.server.registerCapabilities({ extensions: { [TASKS_EXTENSION]: {} } });
88
+ const find = async (method, taskId) => {
89
+ const task = await tasks[method](taskId);
90
+ if (!task) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Unknown task");
91
+ return task;
92
+ };
93
+ server.server.setRequestHandler("tasks/get", { params: TaskIdParams }, async ({ taskId }) => mcpTask(await find("get", taskId)));
94
+ server.server.setRequestHandler("tasks/cancel", { params: TaskIdParams }, async ({ taskId }) => {
95
+ await find("cancel", taskId);
96
+ return {};
97
+ });
98
+ }
99
+
100
+ export { mcpTask as a, isTaskResult as i, attachTasks as n, toolResult as o, declaresTasks as r, TASKS_EXTENSION as t };
@@ -0,0 +1,267 @@
1
+ import { f as Value } from "./validation-CpzAxj2_.js";
2
+ import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
3
+ import { O as literalUnion, i as UuidSchema } from "./schemas-_UJcx_uY.js";
4
+ import { i as standardErrors, t as FailureSchema } from "./errors-BoutSmiy.js";
5
+ import { r as ok, t as err } from "./result-CF4OzG9O.js";
6
+ import { Type } from "typebox";
7
+
8
+ // src/scopes.ts
9
+ /** `<namespace>:<resource>:<action>`, or deeper, in lowercase kebab-case segments. */
10
+ const SCOPE_NAME = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*){2,}$/;
11
+ /** Whether `scope` is a well-formed scope of the service whose namespace is `namespace`. */
12
+ function isNamespacedScope(scope, namespace) {
13
+ return scope.startsWith(`${namespace}:`) && SCOPE_NAME.test(scope);
14
+ }
15
+ /**
16
+ * Whether granted scopes admit a requirement: any one of the required scopes, or all of them with `all`.
17
+ * An empty requirement admits nobody.
18
+ */
19
+ function matchesScopes(required, granted, match = "any") {
20
+ if (!required.length) return false;
21
+ const has = (scope) => granted.includes(scope);
22
+ return match === "all" ? required.every(has) : match === "any" && required.some(has);
23
+ }
24
+
25
+ // src/manifest.ts
26
+ /** Whether an operation belongs in public contracts: the OpenAPI document and the discovery metadata. */
27
+ function isPublicOperation(declaration) {
28
+ return declaration.visibility !== "internal";
29
+ }
30
+ /** The scopes of an operation as a list. */
31
+ function operationScopes(declaration) {
32
+ return typeof declaration.scope === "string" ? [declaration.scope] : declaration.scope;
33
+ }
34
+ /**
35
+ * Whether granted scopes admit an operation: any one of its scopes, or every one under `scopeMatch: 'all'`.
36
+ * HTTP admission, MCP listing and calls, and execution share it.
37
+ */
38
+ function operationMatchesScopes(declaration, granted) {
39
+ return matchesScopes(operationScopes(declaration), granted, declaration.scopeMatch);
40
+ }
41
+ /**
42
+ * Declares one operation on its own, keeping its literal types. The builder's `.operation()` is the usual way
43
+ * to declare one. As there, `execute` receives the decoded input, `StaticDecode<typeof input>`.
44
+ */
45
+ function operation(definition) {
46
+ return definition;
47
+ }
48
+ /** Where an operation is served, for a refusal that names it: its HTTP route, else its MCP tool. */
49
+ function servedAs(declared) {
50
+ if (declared?.http) return `${declared.http.method} ${declared.http.path}`;
51
+ return declared?.mcp && `the tool ${declared.mcp.name}`;
52
+ }
53
+ /**
54
+ * Merges groups of operations into one, never overwriting: a name two groups declare throws a TypeError,
55
+ * `Duplicate operation: <name>`, which names the route or tool of each when both have one.
56
+ */
57
+ function composeOperations(...groups) {
58
+ const result = {};
59
+ for (const group of groups) for (const [name, op] of Object.entries(group)) {
60
+ if (Object.hasOwn(result, name)) {
61
+ const first = servedAs(result[name]);
62
+ const second = servedAs(op);
63
+ throw new TypeError(first && second ? `Duplicate operation: ${name} names both ${first} and ${second}; give one of them its own operationId.` : `Duplicate operation: ${name}`);
64
+ }
65
+ Object.defineProperty(result, name, {
66
+ value: op,
67
+ enumerable: true
68
+ });
69
+ }
70
+ return result;
71
+ }
72
+ /** The failure codes every operation may answer without declaring them. */
73
+ const STANDARD_CODES = new Set(Object.values(STANDARD_FAILURES).map(({ code }) => code));
74
+ /**
75
+ * The standard failures only routing and admission answer, before an operation runs: an unknown path or
76
+ * method, and a missing or refused token. An operation's context, middleware or handler never answers them.
77
+ */
78
+ const ADMISSION_CODES = /* @__PURE__ */ new Set([
79
+ STANDARD_FAILURES.notFound.code,
80
+ STANDARD_FAILURES.methodNotAllowed.code,
81
+ STANDARD_FAILURES.unauthorized.code
82
+ ]);
83
+ /**
84
+ * The standard failures of reading a request body: admission answers them for a JSON body, and a byte body's
85
+ * `read()` for the operation that reads one.
86
+ */
87
+ const BODY_CODES = /* @__PURE__ */ new Set([STANDARD_FAILURES.tooLarge.code, STANDARD_FAILURES.unsupportedMedia.code]);
88
+ /** Default request body limit when neither the operation nor the application sets one. */
89
+ const DEFAULT_MAX_BODY_BYTES = 32768;
90
+ /** Default output limit when neither the operation nor the application sets one. */
91
+ const DEFAULT_MAX_OUTPUT_BYTES = 262144;
92
+ /** Largest body limit an application or operation may declare: the body is buffered in memory. */
93
+ const MAX_BODY_BYTES_CEILING = 16777216;
94
+ /** The request body limit an operation is held to: its own, else the application's, else the default. */
95
+ function operationBodyLimit(application, declaration) {
96
+ return declaration.maxBodyBytes ?? application.maxBodyBytes ?? 32768;
97
+ }
98
+ /** The output limit an operation is held to: its own, else the application's, else the default. */
99
+ function operationOutputLimit(application, declaration) {
100
+ return declaration.maxOutputBytes ?? application.maxOutputBytes ?? 262144;
101
+ }
102
+ /** Whether an operation's MCP tool reaches outside the service: it does unless it declares otherwise. */
103
+ function mcpOpenWorld(tool) {
104
+ return tool.openWorld ?? true;
105
+ }
106
+
107
+ // src/tasks.ts
108
+ /**
109
+ * Tasks for the operations that declare `task`: a call that outlasts a short wait answers a task, as MCP Tasks
110
+ * (`io.modelcontextprotocol/tasks`) and RFC 7240's `Prefer: respond-async` define it, and the work goes on in
111
+ * the application's task store, the `MAXIMUS_TASKS` Durable Object binding (`createWorker`'s `tasks`), one
112
+ * object per task. Without that binding every call runs as before. A task belongs to the caller that started
113
+ * it, runs at most once and is kept for its `ttlMs`: an hour, unless its operation declares another.
114
+ */
115
+ /** How long a call waits for its task to finish before it answers the task instead. */
116
+ const TASK_WAIT_MS = 1e3;
117
+ /** How long a task and its result are kept after the call, unless its operation declares `task: { ttlMs }`. */
118
+ const TASK_TTL_MS = 36e5;
119
+ /** The longest an operation may keep its tasks: a day. */
120
+ const MAX_TASK_TTL_MS = 864e5;
121
+ /** How often a client should ask for a task that is still working. */
122
+ const TASK_POLL_MS = 2e3;
123
+ /** The group of the task operations, which the framework adds and so describes itself. */
124
+ const TASK_GROUP = "Operation tasks";
125
+ /** What the documents say about that group, unless the service's own `groups` describes it. */
126
+ const TASK_GROUP_DESCRIPTION = "The tasks of operations that answer before they finish: read one you started, or cancel one that has not started running.";
127
+ /** How long an operation keeps its tasks: its `task.ttlMs`, or an hour. */
128
+ function taskTtl(operation) {
129
+ return typeof operation?.task === "object" ? operation.task.ttlMs : TASK_TTL_MS;
130
+ }
131
+ /**
132
+ * The caller's tasks in the store `env` binds as `MAXIMUS_TASKS`, or none without it. Each task has its own
133
+ * object, named by its id, so no task waits for another; an id this application never issues names none.
134
+ */
135
+ function taskAccess(application, env, principal, authority) {
136
+ const binding = env?.MAXIMUS_TASKS;
137
+ if (!binding) return;
138
+ const prefix = `${application.namespace}.`;
139
+ const store = (taskId) => binding.get(binding.idFromName(taskId));
140
+ /** Whether the id is one this application issues: its namespace, a dot and a UUID. */
141
+ const issued = (taskId) => taskId.startsWith(prefix) && Value.Check(UuidSchema, taskId.slice(prefix.length));
142
+ const kept = authority && {
143
+ surface: authority.surface,
144
+ scopes: authority.scopes,
145
+ client: authority.client
146
+ };
147
+ return {
148
+ start: (operation, input) => {
149
+ const now = Date.now();
150
+ const taskId = `${prefix}${crypto.randomUUID()}`;
151
+ const task = {
152
+ taskId,
153
+ operation,
154
+ principal,
155
+ status: "working",
156
+ started: false
157
+ };
158
+ return store(taskId).run({
159
+ ...task,
160
+ ...kept ? { authority: kept } : {},
161
+ createdAt: now,
162
+ lastUpdatedAt: now,
163
+ ttlMs: taskTtl(application.operations[operation])
164
+ }, input, TASK_WAIT_MS);
165
+ },
166
+ get: (taskId) => issued(taskId) ? store(taskId).get(taskId, principal) : Promise.resolve(void 0),
167
+ cancel: (taskId) => issued(taskId) ? store(taskId).cancel(taskId, principal) : Promise.resolve(void 0)
168
+ };
169
+ }
170
+ /** A task as REST answers it: its state, then the operation's value or failure once it has one. */
171
+ const TaskSchema = Type.Object({
172
+ taskId: Type.String(),
173
+ status: literalUnion([
174
+ "working",
175
+ "completed",
176
+ "failed",
177
+ "cancelled"
178
+ ]),
179
+ createdAt: Type.String({ format: "date-time" }),
180
+ lastUpdatedAt: Type.String({ format: "date-time" }),
181
+ ttlMs: Type.Integer(),
182
+ pollIntervalMs: Type.Integer(),
183
+ result: Type.Optional(Type.Unknown({ description: "The operation's value, once completed." })),
184
+ error: Type.Optional(Type.With(FailureSchema, { description: "The operation's failure, once failed." }))
185
+ }, {
186
+ $id: "OperationTask",
187
+ additionalProperties: false,
188
+ description: "A call that goes on after it was answered."
189
+ });
190
+ /** A task as REST answers it. */
191
+ function taskView(task) {
192
+ return {
193
+ taskId: task.taskId,
194
+ status: task.status,
195
+ createdAt: new Date(task.createdAt).toISOString(),
196
+ lastUpdatedAt: new Date(task.lastUpdatedAt).toISOString(),
197
+ ttlMs: task.ttlMs,
198
+ pollIntervalMs: TASK_POLL_MS,
199
+ ...task.result?.ok === true ? { result: task.result.value } : {},
200
+ ...task.result?.ok === false ? { error: task.result.error } : {}
201
+ };
202
+ }
203
+ /**
204
+ * `getOperationTask`, `GET /v1/operation-tasks/{taskId}`, which reads a task the caller started, and
205
+ * `cancelOperationTask`, `POST /v1/operation-tasks/{taskId}/cancel`, which cancels one that has not started
206
+ * running: names and paths no resource of a service uses. Either admits any scope of the task operations;
207
+ * someone else's task, or an unknown or expired one, is `INVALID_INPUT` at `/taskId`, their only failure
208
+ * besides admission's.
209
+ */
210
+ function taskOperations(scope, application) {
211
+ const answer = (method) => async ({ env, principal }, { taskId }) => {
212
+ const task = await taskAccess(application, env, principal)?.[method](taskId);
213
+ return task ? ok(taskView(task)) : err(standardErrors.invalidInput.create({ issues: [{
214
+ path: "/taskId",
215
+ message: "must name a task you started"
216
+ }] }));
217
+ };
218
+ const shared = {
219
+ scope,
220
+ group: TASK_GROUP,
221
+ failures: [],
222
+ input: Type.Object({ taskId: Type.String({
223
+ minLength: 1,
224
+ maxLength: 200
225
+ }) }, { additionalProperties: false }),
226
+ output: TaskSchema,
227
+ pipeline: {
228
+ context: (invocation) => Promise.resolve(ok(invocation)),
229
+ middleware: []
230
+ }
231
+ };
232
+ return {
233
+ getOperationTask: {
234
+ ...shared,
235
+ title: "Read a task",
236
+ description: "Read a task you started: whether it still works, then the operation's value or failure.",
237
+ effect: "read",
238
+ http: {
239
+ method: "GET",
240
+ path: "/v1/operation-tasks/{taskId}"
241
+ },
242
+ execute: answer("get")
243
+ },
244
+ cancelOperationTask: {
245
+ ...shared,
246
+ title: "Cancel a task",
247
+ description: "Cancel a task you started that has not started running; one that has runs to its end.",
248
+ effect: "write",
249
+ http: {
250
+ method: "POST",
251
+ path: "/v1/operation-tasks/{taskId}/cancel"
252
+ },
253
+ execute: answer("cancel")
254
+ }
255
+ };
256
+ }
257
+ /** The application's operations and, when one of them declares `task`, the task operations. */
258
+ function withTaskOperations(operations, namespace) {
259
+ const [first, ...rest] = new Set(Object.values(operations).flatMap((op) => op.task ? operationScopes(op) : []));
260
+ if (first === void 0) return operations;
261
+ return composeOperations(operations, taskOperations([first, ...rest], {
262
+ namespace,
263
+ operations
264
+ }));
265
+ }
266
+
267
+ export { matchesScopes as S, operationBodyLimit as _, taskAccess as a, operationScopes as b, ADMISSION_CODES as c, MAX_BODY_BYTES_CEILING as d, STANDARD_CODES as f, operation as g, mcpOpenWorld as h, TASK_POLL_MS as i, BODY_CODES as l, isPublicOperation as m, TASK_GROUP as n, taskView as o, composeOperations as p, TASK_GROUP_DESCRIPTION as r, withTaskOperations as s, MAX_TASK_TTL_MS as t, DEFAULT_MAX_BODY_BYTES as u, operationMatchesScopes as v, isNamespacedScope as x, operationOutputLimit as y };