@lushly-dev/afd-server 2.4.0 → 3.0.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 (279) hide show
  1. package/README.md +239 -56
  2. package/dist/admission.d.ts +137 -0
  3. package/dist/admission.d.ts.map +1 -0
  4. package/dist/admission.js +144 -0
  5. package/dist/admission.js.map +1 -0
  6. package/dist/app-call-registry.d.ts +31 -0
  7. package/dist/app-call-registry.d.ts.map +1 -0
  8. package/dist/app-call-registry.js +64 -0
  9. package/dist/app-call-registry.js.map +1 -0
  10. package/dist/approval-admission.d.ts +139 -0
  11. package/dist/approval-admission.d.ts.map +1 -0
  12. package/dist/approval-admission.js +252 -0
  13. package/dist/approval-admission.js.map +1 -0
  14. package/dist/approval-crypto.d.ts +37 -17
  15. package/dist/approval-crypto.d.ts.map +1 -1
  16. package/dist/approval-crypto.js +84 -75
  17. package/dist/approval-crypto.js.map +1 -1
  18. package/dist/approval-process-state.d.ts +21 -0
  19. package/dist/approval-process-state.d.ts.map +1 -0
  20. package/dist/approval-process-state.js +29 -0
  21. package/dist/approval-process-state.js.map +1 -0
  22. package/dist/approval-relay.d.ts +192 -9
  23. package/dist/approval-relay.d.ts.map +1 -1
  24. package/dist/approval-relay.js +45 -9
  25. package/dist/approval-relay.js.map +1 -1
  26. package/dist/approval-up-front.d.ts +40 -0
  27. package/dist/approval-up-front.d.ts.map +1 -0
  28. package/dist/approval-up-front.js +409 -0
  29. package/dist/approval-up-front.js.map +1 -0
  30. package/dist/approval.d.ts +65 -12
  31. package/dist/approval.d.ts.map +1 -1
  32. package/dist/approval.js +311 -47
  33. package/dist/approval.js.map +1 -1
  34. package/dist/approver.d.ts +84 -0
  35. package/dist/approver.d.ts.map +1 -0
  36. package/dist/approver.js +107 -0
  37. package/dist/approver.js.map +1 -0
  38. package/dist/auth-middleware-check.d.ts +23 -0
  39. package/dist/auth-middleware-check.d.ts.map +1 -0
  40. package/dist/auth-middleware-check.js +48 -0
  41. package/dist/auth-middleware-check.js.map +1 -0
  42. package/dist/bootstrap/afd-context.d.ts.map +1 -1
  43. package/dist/bootstrap/afd-context.js +27 -3
  44. package/dist/bootstrap/afd-context.js.map +1 -1
  45. package/dist/bootstrap/afd-docs.d.ts.map +1 -1
  46. package/dist/bootstrap/afd-docs.js +4 -0
  47. package/dist/bootstrap/afd-docs.js.map +1 -1
  48. package/dist/bootstrap/afd-help.d.ts +4 -1
  49. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  50. package/dist/bootstrap/afd-help.js +19 -4
  51. package/dist/bootstrap/afd-help.js.map +1 -1
  52. package/dist/bootstrap/described-command.d.ts +3 -1
  53. package/dist/bootstrap/described-command.d.ts.map +1 -1
  54. package/dist/bootstrap/described-command.js.map +1 -1
  55. package/dist/command-allow.d.ts +4 -4
  56. package/dist/command-allow.d.ts.map +1 -1
  57. package/dist/command-allow.js +10 -15
  58. package/dist/command-allow.js.map +1 -1
  59. package/dist/command-routing.d.ts +56 -8
  60. package/dist/command-routing.d.ts.map +1 -1
  61. package/dist/command-routing.js +82 -16
  62. package/dist/command-routing.js.map +1 -1
  63. package/dist/command-timeout.d.ts +17 -0
  64. package/dist/command-timeout.d.ts.map +1 -0
  65. package/dist/command-timeout.js +99 -0
  66. package/dist/command-timeout.js.map +1 -0
  67. package/dist/confirmation-gate.d.ts +7 -7
  68. package/dist/confirmation-gate.d.ts.map +1 -1
  69. package/dist/confirmation-gate.js +26 -12
  70. package/dist/confirmation-gate.js.map +1 -1
  71. package/dist/confirmations.d.ts +28 -3
  72. package/dist/confirmations.d.ts.map +1 -1
  73. package/dist/confirmations.js +6 -7
  74. package/dist/confirmations.js.map +1 -1
  75. package/dist/context-fields.d.ts +16 -1
  76. package/dist/context-fields.d.ts.map +1 -1
  77. package/dist/context-fields.js +30 -13
  78. package/dist/context-fields.js.map +1 -1
  79. package/dist/context-scope.d.ts +3 -3
  80. package/dist/context-scope.d.ts.map +1 -1
  81. package/dist/context-scope.js +7 -8
  82. package/dist/context-scope.js.map +1 -1
  83. package/dist/define-core.d.ts +63 -1
  84. package/dist/define-core.d.ts.map +1 -1
  85. package/dist/define-core.js +27 -4
  86. package/dist/define-core.js.map +1 -1
  87. package/dist/define.d.ts +4 -3
  88. package/dist/define.d.ts.map +1 -1
  89. package/dist/define.js +1 -1
  90. package/dist/define.js.map +1 -1
  91. package/dist/direct-registry.d.ts +54 -8
  92. package/dist/direct-registry.d.ts.map +1 -1
  93. package/dist/direct-registry.js +64 -8
  94. package/dist/direct-registry.js.map +1 -1
  95. package/dist/direct-tool-surface.d.ts +1 -1
  96. package/dist/direct-tool-surface.d.ts.map +1 -1
  97. package/dist/direct-tool-surface.js +28 -6
  98. package/dist/direct-tool-surface.js.map +1 -1
  99. package/dist/direct.d.ts +6 -2
  100. package/dist/direct.d.ts.map +1 -1
  101. package/dist/direct.js +4 -1
  102. package/dist/direct.js.map +1 -1
  103. package/dist/elicitation-state.d.ts +5 -1
  104. package/dist/elicitation-state.d.ts.map +1 -1
  105. package/dist/elicitation-state.js +4 -1
  106. package/dist/elicitation-state.js.map +1 -1
  107. package/dist/execution.d.ts +52 -6
  108. package/dist/execution.d.ts.map +1 -1
  109. package/dist/execution.js +183 -19
  110. package/dist/execution.js.map +1 -1
  111. package/dist/host-state.d.ts +81 -0
  112. package/dist/host-state.d.ts.map +1 -0
  113. package/dist/host-state.js +62 -0
  114. package/dist/host-state.js.map +1 -0
  115. package/dist/http-handler.d.ts +48 -11
  116. package/dist/http-handler.d.ts.map +1 -1
  117. package/dist/http-handler.js +207 -58
  118. package/dist/http-handler.js.map +1 -1
  119. package/dist/http-security.d.ts +14 -1
  120. package/dist/http-security.d.ts.map +1 -1
  121. package/dist/http-security.js +79 -17
  122. package/dist/http-security.js.map +1 -1
  123. package/dist/http-sessions.d.ts +45 -5
  124. package/dist/http-sessions.d.ts.map +1 -1
  125. package/dist/http-sessions.js +52 -10
  126. package/dist/http-sessions.js.map +1 -1
  127. package/dist/http-sse.d.ts +9 -0
  128. package/dist/http-sse.d.ts.map +1 -1
  129. package/dist/http-sse.js +12 -3
  130. package/dist/http-sse.js.map +1 -1
  131. package/dist/human-relay.d.ts +195 -0
  132. package/dist/human-relay.d.ts.map +1 -0
  133. package/dist/human-relay.js +670 -0
  134. package/dist/human-relay.js.map +1 -0
  135. package/dist/idempotency-step.d.ts +231 -0
  136. package/dist/idempotency-step.d.ts.map +1 -0
  137. package/dist/idempotency-step.js +389 -0
  138. package/dist/idempotency-step.js.map +1 -0
  139. package/dist/idempotency-store.d.ts +107 -0
  140. package/dist/idempotency-store.d.ts.map +1 -0
  141. package/dist/idempotency-store.js +100 -0
  142. package/dist/idempotency-store.js.map +1 -0
  143. package/dist/index.d.ts +18 -8
  144. package/dist/index.d.ts.map +1 -1
  145. package/dist/index.js +15 -4
  146. package/dist/index.js.map +1 -1
  147. package/dist/instance-state.d.ts +53 -0
  148. package/dist/instance-state.d.ts.map +1 -0
  149. package/dist/instance-state.js +94 -0
  150. package/dist/instance-state.js.map +1 -0
  151. package/dist/journal-off-tape.d.ts +52 -0
  152. package/dist/journal-off-tape.d.ts.map +1 -0
  153. package/dist/journal-off-tape.js +150 -0
  154. package/dist/journal-off-tape.js.map +1 -0
  155. package/dist/journal-replay.d.ts.map +1 -1
  156. package/dist/journal-replay.js +48 -3
  157. package/dist/journal-replay.js.map +1 -1
  158. package/dist/journal-view.d.ts +50 -0
  159. package/dist/journal-view.d.ts.map +1 -0
  160. package/dist/journal-view.js +214 -0
  161. package/dist/journal-view.js.map +1 -0
  162. package/dist/journal.d.ts +34 -6
  163. package/dist/journal.d.ts.map +1 -1
  164. package/dist/journal.js +183 -47
  165. package/dist/journal.js.map +1 -1
  166. package/dist/json-rpc.d.ts +3 -2
  167. package/dist/json-rpc.d.ts.map +1 -1
  168. package/dist/json-rpc.js +5 -3
  169. package/dist/json-rpc.js.map +1 -1
  170. package/dist/lazy-tools.d.ts +27 -2
  171. package/dist/lazy-tools.d.ts.map +1 -1
  172. package/dist/lazy-tools.js +22 -4
  173. package/dist/lazy-tools.js.map +1 -1
  174. package/dist/mcp-auth-bearer.d.ts +2 -0
  175. package/dist/mcp-auth-bearer.d.ts.map +1 -1
  176. package/dist/mcp-auth-bearer.js +1 -1
  177. package/dist/mcp-auth-bearer.js.map +1 -1
  178. package/dist/mcp-auth-dispatch.d.ts +38 -0
  179. package/dist/mcp-auth-dispatch.d.ts.map +1 -0
  180. package/dist/mcp-auth-dispatch.js +113 -0
  181. package/dist/mcp-auth-dispatch.js.map +1 -0
  182. package/dist/mcp-auth-jwt.d.ts +3 -2
  183. package/dist/mcp-auth-jwt.d.ts.map +1 -1
  184. package/dist/mcp-auth-jwt.js.map +1 -1
  185. package/dist/mcp-auth-resource.d.ts +6 -2
  186. package/dist/mcp-auth-resource.d.ts.map +1 -1
  187. package/dist/mcp-auth-resource.js +6 -5
  188. package/dist/mcp-auth-resource.js.map +1 -1
  189. package/dist/mcp-auth-scopes.d.ts +84 -0
  190. package/dist/mcp-auth-scopes.d.ts.map +1 -0
  191. package/dist/mcp-auth-scopes.js +125 -0
  192. package/dist/mcp-auth-scopes.js.map +1 -0
  193. package/dist/mcp-auth-view.d.ts +50 -0
  194. package/dist/mcp-auth-view.d.ts.map +1 -0
  195. package/dist/mcp-auth-view.js +179 -0
  196. package/dist/mcp-auth-view.js.map +1 -0
  197. package/dist/mcp-auth.d.ts +94 -3
  198. package/dist/mcp-auth.d.ts.map +1 -1
  199. package/dist/mcp-auth.js +241 -23
  200. package/dist/mcp-auth.js.map +1 -1
  201. package/dist/mcp-modern.d.ts +80 -6
  202. package/dist/mcp-modern.d.ts.map +1 -1
  203. package/dist/mcp-modern.js +378 -91
  204. package/dist/mcp-modern.js.map +1 -1
  205. package/dist/meta-argument.d.ts +9 -8
  206. package/dist/meta-argument.d.ts.map +1 -1
  207. package/dist/meta-argument.js +28 -10
  208. package/dist/meta-argument.js.map +1 -1
  209. package/dist/meta-tools.js +2 -2
  210. package/dist/meta-tools.js.map +1 -1
  211. package/dist/middleware.d.ts +16 -1
  212. package/dist/middleware.d.ts.map +1 -1
  213. package/dist/middleware.js +57 -10
  214. package/dist/middleware.js.map +1 -1
  215. package/dist/output-budget.d.ts +77 -0
  216. package/dist/output-budget.d.ts.map +1 -0
  217. package/dist/output-budget.js +202 -0
  218. package/dist/output-budget.js.map +1 -0
  219. package/dist/principal-binding.js +1 -1
  220. package/dist/principal-binding.js.map +1 -1
  221. package/dist/relay-evidence.d.ts +74 -0
  222. package/dist/relay-evidence.d.ts.map +1 -0
  223. package/dist/relay-evidence.js +143 -0
  224. package/dist/relay-evidence.js.map +1 -0
  225. package/dist/resources.d.ts +35 -10
  226. package/dist/resources.d.ts.map +1 -1
  227. package/dist/resources.js +59 -18
  228. package/dist/resources.js.map +1 -1
  229. package/dist/schema.d.ts +4 -3
  230. package/dist/schema.d.ts.map +1 -1
  231. package/dist/schema.js +3 -3
  232. package/dist/schema.js.map +1 -1
  233. package/dist/scope-view.d.ts +65 -0
  234. package/dist/scope-view.d.ts.map +1 -0
  235. package/dist/scope-view.js +45 -0
  236. package/dist/scope-view.js.map +1 -0
  237. package/dist/server-types.d.ts +182 -27
  238. package/dist/server-types.d.ts.map +1 -1
  239. package/dist/server-types.js.map +1 -1
  240. package/dist/server.d.ts +26 -0
  241. package/dist/server.d.ts.map +1 -1
  242. package/dist/server.js +403 -61
  243. package/dist/server.js.map +1 -1
  244. package/dist/skills.d.ts.map +1 -1
  245. package/dist/skills.js +99 -3
  246. package/dist/skills.js.map +1 -1
  247. package/dist/task-dispatch.d.ts +35 -0
  248. package/dist/task-dispatch.d.ts.map +1 -0
  249. package/dist/task-dispatch.js +25 -0
  250. package/dist/task-dispatch.js.map +1 -0
  251. package/dist/tasks-runtime.d.ts +115 -0
  252. package/dist/tasks-runtime.d.ts.map +1 -0
  253. package/dist/tasks-runtime.js +760 -0
  254. package/dist/tasks-runtime.js.map +1 -0
  255. package/dist/tasks.d.ts +237 -0
  256. package/dist/tasks.d.ts.map +1 -0
  257. package/dist/tasks.js +321 -0
  258. package/dist/tasks.js.map +1 -0
  259. package/dist/tool-router.d.ts +68 -3
  260. package/dist/tool-router.d.ts.map +1 -1
  261. package/dist/tool-router.js +293 -70
  262. package/dist/tool-router.js.map +1 -1
  263. package/dist/tools.d.ts +32 -0
  264. package/dist/tools.d.ts.map +1 -1
  265. package/dist/tools.js +162 -55
  266. package/dist/tools.js.map +1 -1
  267. package/dist/up-front-steps.d.ts +35 -0
  268. package/dist/up-front-steps.d.ts.map +1 -0
  269. package/dist/up-front-steps.js +159 -0
  270. package/dist/up-front-steps.js.map +1 -0
  271. package/dist/validation.d.ts +38 -3
  272. package/dist/validation.d.ts.map +1 -1
  273. package/dist/validation.js +118 -23
  274. package/dist/validation.js.map +1 -1
  275. package/dist/verified-credentials.d.ts +13 -5
  276. package/dist/verified-credentials.d.ts.map +1 -1
  277. package/dist/verified-credentials.js +43 -10
  278. package/dist/verified-credentials.js.map +1 -1
  279. package/package.json +15 -11
@@ -0,0 +1,760 @@
1
+ /**
2
+ * @fileoverview MCP Tasks runtime: creation, background execution, cancellation, deadlines and
3
+ * `tasks/get`, `tasks/update`, `tasks/cancel` handlers (`spec/tasks.md`;
4
+ * SEP-2663).
5
+ */
6
+ import { randomBytes } from 'node:crypto';
7
+ import { ErrorCodes, failure, systemClock, truncateName } from '@lushly-dev/afd-core';
8
+ import { CLIENT_CAPABILITIES_META_KEY, ProtocolError, ProtocolErrorCode, } from '@modelcontextprotocol/server';
9
+ import { z } from 'zod';
10
+ import { bindContextState, resolveContextState } from './context-scope.js';
11
+ import { withHostState } from './host-state.js';
12
+ import { JsonRpcError } from './json-rpc.js';
13
+ import { bindOutputBudgetAsk, OUTPUT_BUDGET_ASK } from './output-budget.js';
14
+ import { principalBinding } from './principal-binding.js';
15
+ import { bindScopeView, scopeViewOf } from './scope-view.js';
16
+ import { finishedTaskTtlFor, InMemoryTaskStore, isTaskExpired, isTerminalTaskStatus, resolveTaskOptions, TASKS_EXTENSION_ID, TaskStoreError, taskOwnerMatches, taskTtlFor, } from './tasks.js';
17
+ import { resultContent } from './tool-router.js';
18
+ import { cloneVerifiedCredentials, unbrandVerifiedCredentials } from './verified-credentials.js';
19
+ /**
20
+ * Thrown by the task dispatch inside `tools/call` so the patched `Server._wrapHandler` returns a
21
+ * `CreateTaskResult` without running the SDK's `CallToolResultSchema` check over it.
22
+ */
23
+ export class CreateTaskSignal {
24
+ result;
25
+ constructor(result) {
26
+ this.result = result;
27
+ }
28
+ }
29
+ /**
30
+ * Patch `server._wrapHandler` so a {@link CreateTaskSignal} thrown from `tools/call` returns its
31
+ * `CreateTaskResult` straight to `Protocol._onrequest` (preserving request validation, input
32
+ * required handling and response encoding).
33
+ */
34
+ export function patchToolsCallForTasks(server) {
35
+ const sdk = server;
36
+ if (typeof sdk._wrapHandler !== 'function') {
37
+ throw new Error('@modelcontextprotocol/server Server._wrapHandler is missing; MCP Tasks dispatch requires it (#1744)');
38
+ }
39
+ const originalWrap = sdk._wrapHandler.bind(server);
40
+ sdk._wrapHandler = (method, handler) => {
41
+ if (method !== 'tools/call')
42
+ return originalWrap(method, handler);
43
+ const wrapped = originalWrap(method, handler);
44
+ return async (request, extra) => {
45
+ try {
46
+ return await wrapped(request, extra);
47
+ }
48
+ catch (error) {
49
+ if (error instanceof CreateTaskSignal)
50
+ return error.result;
51
+ throw error;
52
+ }
53
+ };
54
+ };
55
+ }
56
+ // ═══════════════════════════════════════════════════════════════════════════════
57
+ // IDS & WIRE HELPERS
58
+ // ═══════════════════════════════════════════════════════════════════════════════
59
+ const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567';
60
+ const TASK_ID_LENGTH = 26;
61
+ const TASK_ID_RE = /^[a-z2-7]{26}$/;
62
+ const MAX_TIMEOUT_MS = 2_147_483_647;
63
+ const utf8 = new TextEncoder();
64
+ /** Generate a 128-bit cryptographic random task id in unpadded lowercase RFC 4648 base32. */
65
+ export function newTaskId() {
66
+ const bytes = randomBytes(16);
67
+ let id = '';
68
+ let buffer = 0;
69
+ let bits = 0;
70
+ for (const byte of bytes) {
71
+ buffer = (buffer << 8) | byte;
72
+ bits += 8;
73
+ while (bits >= 5) {
74
+ bits -= 5;
75
+ id += BASE32[(buffer >>> bits) & 31];
76
+ }
77
+ }
78
+ if (bits > 0) {
79
+ id += BASE32[(buffer << (5 - bits)) & 31];
80
+ }
81
+ return id;
82
+ }
83
+ /** Whether `id` could be a task id issued by this server. */
84
+ export function isTaskId(id) {
85
+ return id.length === TASK_ID_LENGTH && TASK_ID_RE.test(id);
86
+ }
87
+ function isoTimestamp(ms) {
88
+ return new Date(ms).toISOString();
89
+ }
90
+ function wireCreateTask(record) {
91
+ return {
92
+ resultType: 'task',
93
+ taskId: record.id,
94
+ status: 'working',
95
+ ...(record.statusMessage !== undefined && { statusMessage: record.statusMessage }),
96
+ createdAt: isoTimestamp(record.createdAt),
97
+ lastUpdatedAt: isoTimestamp(record.lastUpdatedAt),
98
+ ttlMs: record.ttlMs,
99
+ pollIntervalMs: record.pollIntervalMs,
100
+ };
101
+ }
102
+ function wireDetailedTask(record) {
103
+ const base = {
104
+ taskId: record.id,
105
+ status: record.status,
106
+ ...(record.statusMessage !== undefined && { statusMessage: record.statusMessage }),
107
+ createdAt: isoTimestamp(record.createdAt),
108
+ lastUpdatedAt: isoTimestamp(record.lastUpdatedAt),
109
+ ttlMs: record.ttlMs,
110
+ pollIntervalMs: record.pollIntervalMs,
111
+ };
112
+ if (record.status === 'completed') {
113
+ base.result = record.result ?? { content: [], isError: false };
114
+ }
115
+ else if (record.status === 'failed') {
116
+ base.error = record.error ?? internalErrorObject();
117
+ }
118
+ return base;
119
+ }
120
+ function isRecord(value) {
121
+ return !!value && typeof value === 'object' && !Array.isArray(value);
122
+ }
123
+ /**
124
+ * Whether `ctx` is an MCP 2026-07-28 request whose envelope client capabilities declare the Tasks
125
+ * extension. A 2025-era request never does.
126
+ */
127
+ export function requestDeclaresTasks(era, ctx) {
128
+ if (era !== 'modern')
129
+ return false;
130
+ const envelope = ctx.mcpReq.envelope;
131
+ const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
132
+ if (!isRecord(capabilities))
133
+ return false;
134
+ const extensions = capabilities.extensions;
135
+ if (!isRecord(extensions))
136
+ return false;
137
+ return isRecord(extensions[TASKS_EXTENSION_ID]);
138
+ }
139
+ function missingTasksCapability() {
140
+ return new ProtocolError(ProtocolErrorCode.MissingRequiredClientCapability, `Client does not declare required capability: ${TASKS_EXTENSION_ID}`, {
141
+ requiredCapabilities: {
142
+ extensions: { [TASKS_EXTENSION_ID]: {} },
143
+ },
144
+ });
145
+ }
146
+ /**
147
+ * A request-local copy of the actor: its declared fields (`kind`, `id`, `label`, `onBehalfOf`) and
148
+ * every other enumerable field a host put on it (a workspace id, say), each read exactly once. A
149
+ * spread alone would drop a field a class exposes through a getter, and so change the principal
150
+ * binding the copy is made for (#3011). Declared fields left undefined are left out.
151
+ */
152
+ function snapshotActor(actor) {
153
+ // One destructuring: each field, a getter's included, is read once, and the rest are kept.
154
+ const { kind, id, label, onBehalfOf, ...extra } = actor;
155
+ return {
156
+ ...extra,
157
+ kind,
158
+ ...(id !== undefined ? { id } : {}),
159
+ ...(label !== undefined ? { label } : {}),
160
+ ...(onBehalfOf !== undefined ? { onBehalfOf } : {}),
161
+ };
162
+ }
163
+ function taskNotFound() {
164
+ return new ProtocolError(ProtocolErrorCode.InvalidParams, 'Task not found');
165
+ }
166
+ function internalRpcError() {
167
+ return new ProtocolError(ProtocolErrorCode.InternalError, 'Internal error');
168
+ }
169
+ function internalErrorObject() {
170
+ return { code: -32603, message: 'Internal error' };
171
+ }
172
+ function taskLimitError() {
173
+ return {
174
+ code: ErrorCodes.RATE_LIMITED,
175
+ message: 'The task could not start: a task limit was reached, so nothing ran',
176
+ suggestion: 'Wait for one of your tasks to finish or expire, then call again.',
177
+ retryable: true,
178
+ recovery: { kind: 'retry' },
179
+ };
180
+ }
181
+ function compositeTaskError(tool, commandName) {
182
+ return {
183
+ code: tool === 'afd-batch' ? 'INVALID_BATCH_REQUEST' : 'INVALID_PIPELINE_REQUEST',
184
+ message: `Command '${truncateName(commandName)}' requires MCP Tasks and cannot run inside ${tool}`,
185
+ suggestion: `Call '${truncateName(commandName)}' directly or through afd-call on an MCP 2026-07-28 client declaring ${TASKS_EXTENSION_ID}`,
186
+ retryable: false,
187
+ };
188
+ }
189
+ function unidentifiedCallersError(command) {
190
+ return {
191
+ code: ErrorCodes.UNAUTHORIZED,
192
+ message: `Command '${truncateName(command)}' runs only as a task, and this server cannot tell its callers apart, so it starts no task`,
193
+ suggestion: "Nothing ran. The server's operator must configure authorization, or declare that the server's context hook identifies every caller; calling again will not help until then.",
194
+ retryable: false,
195
+ recovery: { kind: 'external' },
196
+ };
197
+ }
198
+ function createRunningTask() {
199
+ const controller = new AbortController();
200
+ const running = {
201
+ controller,
202
+ reason: undefined,
203
+ stop(reason) {
204
+ if (running.reason === undefined) {
205
+ running.reason = reason;
206
+ }
207
+ if (!controller.signal.aborted) {
208
+ controller.abort();
209
+ }
210
+ },
211
+ };
212
+ return running;
213
+ }
214
+ /** What deadline is due at `nowMs`: token expiry first, then TTL, then optional run budget. */
215
+ export function dueTaskStop(tokenDeadlineMs, ttlDeadlineMs, nowMs, runDeadlineMs) {
216
+ if (tokenDeadlineMs !== undefined && nowMs >= tokenDeadlineMs)
217
+ return 'token-expired';
218
+ if (nowMs >= ttlDeadlineMs)
219
+ return 'ttl-ended';
220
+ if (runDeadlineMs !== undefined && nowMs >= runDeadlineMs)
221
+ return 'run-timeout';
222
+ return undefined;
223
+ }
224
+ /** Build `TIMEOUT` for a task whose run budget elapsed, retryable unless a mutation may have run. */
225
+ export function taskRunTimeoutError(stage, mutation) {
226
+ if (stage === 'not-started') {
227
+ return {
228
+ code: ErrorCodes.TIMEOUT,
229
+ message: 'The task did not start before its run budget elapsed',
230
+ suggestion: 'Nothing ran. Increase the task run budget or simplify the request and start it again.',
231
+ retryable: true,
232
+ recovery: { kind: 'retry' },
233
+ };
234
+ }
235
+ return {
236
+ code: ErrorCodes.TIMEOUT,
237
+ message: 'The task stopped because its run budget elapsed',
238
+ suggestion: mutation
239
+ ? 'The command may have made part of its change before it stopped: check its effect before starting it again.'
240
+ : 'Simplify or narrow the request, or increase the task run budget, and start it again.',
241
+ retryable: !mutation,
242
+ recovery: { kind: 'external' },
243
+ };
244
+ }
245
+ /** Build `TASK_TOKEN_EXPIRED`, retryable unless a mutation may have started. */
246
+ export function tokenExpiredError(stage, mutation) {
247
+ let message;
248
+ let suggestion;
249
+ if (stage === 'not-started') {
250
+ message = 'The task did not start: the access token that started it had expired';
251
+ suggestion = 'Nothing ran. Obtain a new access token and start the task again.';
252
+ }
253
+ else if (stage === 'running') {
254
+ message = 'The task stopped because the access token that started it expired';
255
+ suggestion = mutation
256
+ ? 'The command may have made part of its change before it stopped: check its effect, then start it again with a new access token if it is still needed.'
257
+ : 'Obtain a new access token and start the task again.';
258
+ }
259
+ else {
260
+ message =
261
+ 'The task finished after the access token that started it expired, so its result is not delivered';
262
+ suggestion = mutation
263
+ ? 'The command ran to the end and made its change: check its effect before starting it again with a new access token.'
264
+ : 'Obtain a new access token and start the task again.';
265
+ }
266
+ return {
267
+ code: ErrorCodes.TASK_TOKEN_EXPIRED,
268
+ message,
269
+ suggestion,
270
+ retryable: stage === 'not-started' || !mutation,
271
+ recovery: { kind: 'external' },
272
+ };
273
+ }
274
+ function completionChange(result, maxResultBytes, at, ttlMs) {
275
+ // A result JSON cannot hold (a BigInt, a cycle) throws in resultContent too: the task fails
276
+ // with an internal error instead of staying `working`.
277
+ let toolResult;
278
+ let serialized;
279
+ try {
280
+ toolResult = resultContent(result, !result.success);
281
+ serialized = JSON.stringify(toolResult);
282
+ }
283
+ catch {
284
+ return { kind: 'failed', error: internalErrorObject(), at, ttlMs };
285
+ }
286
+ const size = utf8.encode(serialized).byteLength;
287
+ if (size <= maxResultBytes) {
288
+ return { kind: 'completed', result: toolResult, at, ttlMs };
289
+ }
290
+ const tooLarge = {
291
+ code: ErrorCodes.INTERNAL_ERROR,
292
+ message: 'The command ran, but its result is larger than this server keeps for a task',
293
+ suggestion: 'The command ran: check its effect before running it again. For a read, ask for less (narrow the request or set an output budget).',
294
+ details: { limitBytes: maxResultBytes, actualBytes: size },
295
+ retryable: false,
296
+ };
297
+ return { kind: 'completed', result: resultContent(failure(tooLarge), true), at, ttlMs };
298
+ }
299
+ /** Copy string-keyed properties and only the safe symbols (`scopeView`, `contextState`). */
300
+ function cloneTaskContext(context, signal, reportProgress) {
301
+ const copy = {};
302
+ for (const key of Object.keys(context)) {
303
+ copy[key] = context[key];
304
+ }
305
+ // MCP Tasks are bounded by their own run budget (default 1 h), TTL and cancellation signal
306
+ // rather than the inline server defaultTimeoutMs; keep an explicit per-request timeout if set.
307
+ if (copy.timeout === undefined) {
308
+ copy.timeout = 0;
309
+ }
310
+ let taskContext = {
311
+ ...copy,
312
+ signal,
313
+ reportProgress,
314
+ };
315
+ const view = scopeViewOf(context);
316
+ if (view) {
317
+ // Routing decides the view first today; this keeps a future route from asking after the answer.
318
+ view.settle();
319
+ taskContext = bindScopeView(taskContext, view);
320
+ }
321
+ const state = resolveContextState(context, undefined);
322
+ if (state !== undefined)
323
+ taskContext = bindContextState(taskContext, state);
324
+ if (Object.hasOwn(context, OUTPUT_BUDGET_ASK)) {
325
+ taskContext = bindOutputBudgetAsk(taskContext, context[OUTPUT_BUDGET_ASK]);
326
+ }
327
+ // The idempotency step never acts on a task run, and the retry middleware counts it as carrying
328
+ // no key (spec/idempotency.md, S11).
329
+ return withHostState(taskContext, { taskRun: true });
330
+ }
331
+ const taskIdParamsSchema = z.object({ taskId: z.string() });
332
+ const updateTaskParamsSchema = z.object({
333
+ taskId: z.string(),
334
+ inputResponses: z.record(z.string(), z.unknown()).optional(),
335
+ });
336
+ export class TaskRuntime {
337
+ store;
338
+ options;
339
+ servesTasks;
340
+ clock;
341
+ hasAuth;
342
+ hasContextHook;
343
+ actor;
344
+ executeCommand;
345
+ running = new Map();
346
+ constructor(deps) {
347
+ this.store = deps.store ?? new InMemoryTaskStore();
348
+ this.options = resolveTaskOptions(deps.options);
349
+ this.clock = deps.clock ?? systemClock;
350
+ this.hasAuth = deps.hasAuth;
351
+ this.hasContextHook = deps.hasContextHook;
352
+ this.actor = deps.actor;
353
+ this.executeCommand = deps.executeCommand;
354
+ this.servesTasks = deps.commands.some((cmd) => cmd.task === 'optional' || cmd.task === 'required');
355
+ }
356
+ get hookIdentifiesCallers() {
357
+ return this.options.callersIdentifiedByHook && this.hasContextHook;
358
+ }
359
+ /** Whether HTTP configuration identifies callers well enough to serve MCP Tasks. */
360
+ get identifiesHttpCallers() {
361
+ return this.hasAuth || this.hookIdentifiesCallers;
362
+ }
363
+ /** Whether this server declares the Tasks extension on this transport (`isHttp`). */
364
+ declaresTasksTo(isHttp) {
365
+ return this.servesTasks && (!isHttp || this.identifiesHttpCallers);
366
+ }
367
+ /** Whether a task may be created for a request on this transport with `credentials`. */
368
+ identifiesCaller(isHttp, credentials) {
369
+ return !isHttp || (this.hasAuth && credentials !== undefined) || this.hookIdentifiesCallers;
370
+ }
371
+ /** Build the {@link TaskDispatch} for one modern/stdio `tools/call`. */
372
+ dispatchFor(era, isHttp, ctx, credentials) {
373
+ return {
374
+ dispatch: async (command, input, context) => {
375
+ if (command.task !== 'optional' && command.task !== 'required')
376
+ return undefined;
377
+ if (!this.identifiesCaller(isHttp, credentials)) {
378
+ if (command.task === 'required') {
379
+ return resultContent(failure(unidentifiedCallersError(command.name)), true);
380
+ }
381
+ return undefined;
382
+ }
383
+ if (!requestDeclaresTasks(era, ctx)) {
384
+ if (command.task === 'required')
385
+ throw missingTasksCapability();
386
+ return undefined;
387
+ }
388
+ return this.startTask(command, input, context);
389
+ },
390
+ refuseComposite: compositeTaskError,
391
+ };
392
+ }
393
+ /** Build the {@link TaskDispatch} for the 2025-era `/message` HTTP lane. */
394
+ legacyHttpDispatchFor(credentials) {
395
+ return {
396
+ dispatch: async (command) => {
397
+ if (command.task !== 'required')
398
+ return undefined;
399
+ if (!this.identifiesCaller(true, credentials)) {
400
+ return resultContent(failure(unidentifiedCallersError(command.name)), true);
401
+ }
402
+ throw new JsonRpcError(ProtocolErrorCode.MissingRequiredClientCapability, `Client does not declare required capability: ${TASKS_EXTENSION_ID}`, `Call '${truncateName(command.name)}' over MCP 2026-07-28 declaring the ${TASKS_EXTENSION_ID} extension`, { requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } } });
403
+ },
404
+ refuseComposite: compositeTaskError,
405
+ };
406
+ }
407
+ /** Abort all locally running tasks without overwriting shared store state (server stop/dispose). */
408
+ dispose() {
409
+ for (const running of this.running.values()) {
410
+ running.stop('lost');
411
+ }
412
+ this.running.clear();
413
+ }
414
+ /** Install `tasks/get`, `tasks/update` and `tasks/cancel` handlers on `server`. */
415
+ installHandlers(server, opts) {
416
+ if (!this.declaresTasksTo(opts.isHttp))
417
+ return;
418
+ const resolveCaller = async (ctx) => {
419
+ if (!requestDeclaresTasks(opts.era, ctx)) {
420
+ throw missingTasksCapability();
421
+ }
422
+ const view = opts.requestView?.();
423
+ const reqDecision = view?.decideRequest();
424
+ if (view && reqDecision && reqDecision !== 'proceed') {
425
+ const error = view.insufficientScope(reqDecision.forbidden);
426
+ throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
427
+ code: error.code,
428
+ suggestion: error.suggestion,
429
+ scopes: reqDecision.forbidden,
430
+ });
431
+ }
432
+ let values;
433
+ try {
434
+ values = opts.requestValues ? await opts.requestValues() : {};
435
+ }
436
+ catch (error) {
437
+ throw opts.internalError(error);
438
+ }
439
+ // A request-local copy, taken before the binding: the store's `getFor` then sees the
440
+ // actor the binding was made from, whatever later happens to a shared one.
441
+ const shared = (values.actor ?? this.actor);
442
+ const actor = shared ? snapshotActor(shared) : undefined;
443
+ const credentials = (view?.credentials ?? values.credentials);
444
+ let owner;
445
+ try {
446
+ owner = principalBinding(actor, credentials);
447
+ }
448
+ catch {
449
+ throw internalRpcError();
450
+ }
451
+ // The context the caller's request runs with, which the store's `getFor` receives.
452
+ const context = { ...values, actor, credentials };
453
+ return { owner, view, context };
454
+ };
455
+ const findTask = async (caller, taskId, needsCommand) => {
456
+ if (!isTaskId(taskId))
457
+ throw taskNotFound();
458
+ let record;
459
+ try {
460
+ record = this.store.getFor
461
+ ? await this.store.getFor(taskId, caller.owner, caller.context)
462
+ : await this.store.get(taskId, caller.owner);
463
+ }
464
+ catch {
465
+ throw internalRpcError();
466
+ }
467
+ const now = this.clock.now();
468
+ if (!record ||
469
+ record.id !== taskId ||
470
+ !taskOwnerMatches(record.owner, caller.owner) ||
471
+ isTaskExpired(record, now)) {
472
+ throw taskNotFound();
473
+ }
474
+ if (caller.view && !caller.view.known(record.command)) {
475
+ throw taskNotFound();
476
+ }
477
+ if (needsCommand && caller.view) {
478
+ const decision = caller.view.decideTask(record.command);
479
+ if (decision !== 'proceed') {
480
+ const error = caller.view.insufficientScope(decision.forbidden);
481
+ throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
482
+ code: error.code,
483
+ suggestion: error.suggestion,
484
+ scopes: decision.forbidden,
485
+ });
486
+ }
487
+ }
488
+ return record;
489
+ };
490
+ server.setRequestHandler('tasks/get', { params: taskIdParamsSchema }, async (params, ctx) => {
491
+ const caller = await resolveCaller(ctx);
492
+ const record = await findTask(caller, params.taskId, true);
493
+ return wireDetailedTask(record);
494
+ });
495
+ server.setRequestHandler('tasks/update', { params: updateTaskParamsSchema }, async (params, ctx) => {
496
+ const caller = await resolveCaller(ctx);
497
+ await findTask(caller, params.taskId, true);
498
+ return {};
499
+ });
500
+ server.setRequestHandler('tasks/cancel', { params: taskIdParamsSchema }, async (params, ctx) => {
501
+ const caller = await resolveCaller(ctx);
502
+ const record = await findTask(caller, params.taskId, false);
503
+ if (isTerminalTaskStatus(record.status)) {
504
+ this.running.get(record.id)?.stop('lost');
505
+ return {};
506
+ }
507
+ try {
508
+ await this.store.update(record.id, caller.owner, { kind: 'cancel-requested' });
509
+ }
510
+ catch {
511
+ throw internalRpcError();
512
+ }
513
+ this.running.get(record.id)?.stop('cancelled');
514
+ return {};
515
+ });
516
+ }
517
+ async startTask(command, input, context) {
518
+ const actor = (context.actor ?? this.actor);
519
+ const credentials = context.credentials;
520
+ let owner;
521
+ try {
522
+ owner = principalBinding(actor, credentials);
523
+ }
524
+ catch {
525
+ throw internalRpcError();
526
+ }
527
+ const id = newTaskId();
528
+ const now = this.clock.now();
529
+ await this.store.expire(now).catch(() => { });
530
+ const expiresAtSeconds = typeof credentials?.expiresAt === 'number' ? credentials.expiresAt : undefined;
531
+ const ttlMs = taskTtlFor(this.options, now, expiresAtSeconds);
532
+ const record = {
533
+ id,
534
+ owner,
535
+ command: command.name,
536
+ status: 'working',
537
+ createdAt: now,
538
+ lastUpdatedAt: now,
539
+ ttlMs,
540
+ pollIntervalMs: this.options.pollIntervalMs,
541
+ cancelRequested: false,
542
+ };
543
+ if (this.running.size >= this.options.maxRunning) {
544
+ return resultContent(failure(taskLimitError()), true);
545
+ }
546
+ const running = createRunningTask();
547
+ this.running.set(id, running);
548
+ try {
549
+ await this.store.create(record, { command, input, context });
550
+ }
551
+ catch (error) {
552
+ this.running.delete(id);
553
+ if (error instanceof TaskStoreError &&
554
+ (error.kind === 'owner-limit' || error.kind === 'total-limit')) {
555
+ return resultContent(failure(taskLimitError()), true);
556
+ }
557
+ return resultContent(failure({
558
+ code: ErrorCodes.INTERNAL_ERROR,
559
+ message: 'The task could not be recorded, so nothing ran',
560
+ suggestion: 'Retry later.',
561
+ retryable: true,
562
+ }), true);
563
+ }
564
+ let latestProgress;
565
+ let hasProgress = false;
566
+ const verifiedCredentials = context.credentials && typeof context.credentials === 'object'
567
+ ? cloneVerifiedCredentials(context.credentials)
568
+ : undefined;
569
+ const taskContext = cloneTaskContext(verifiedCredentials ? { ...context, credentials: verifiedCredentials } : context, running.controller.signal, (message) => {
570
+ if (typeof message === 'string') {
571
+ latestProgress = message;
572
+ hasProgress = true;
573
+ }
574
+ });
575
+ const takeProgress = () => {
576
+ if (!hasProgress)
577
+ return undefined;
578
+ hasProgress = false;
579
+ const msg = latestProgress;
580
+ latestProgress = undefined;
581
+ return msg;
582
+ };
583
+ const tokenDeadlineMs = expiresAtSeconds !== undefined ? expiresAtSeconds * 1000 : undefined;
584
+ const ttlDeadlineMs = record.createdAt + record.ttlMs;
585
+ const runDeadlineMs = Math.min(Number.MAX_SAFE_INTEGER, record.createdAt + this.options.maxRunMs);
586
+ void this.runTask({
587
+ id,
588
+ owner,
589
+ commandName: command.name,
590
+ mutation: command.mutation === true,
591
+ createdAt: record.createdAt,
592
+ expiresAtSeconds,
593
+ input,
594
+ context: taskContext,
595
+ running,
596
+ takeProgress,
597
+ tokenDeadlineMs,
598
+ ttlDeadlineMs,
599
+ runDeadlineMs,
600
+ verifiedCredentials,
601
+ });
602
+ throw new CreateTaskSignal(wireCreateTask(record));
603
+ }
604
+ async runTask(job) {
605
+ let outcome;
606
+ try {
607
+ outcome = await this.driveTask(job);
608
+ }
609
+ catch {
610
+ outcome = { kind: 'internal' };
611
+ }
612
+ finally {
613
+ this.running.delete(job.id);
614
+ if (job.verifiedCredentials) {
615
+ unbrandVerifiedCredentials(job.verifiedCredentials);
616
+ }
617
+ }
618
+ const now = this.clock.now();
619
+ const finalTtlMs = finishedTaskTtlFor(this.options, job.createdAt, now, job.expiresAtSeconds);
620
+ let change;
621
+ if (outcome.kind === 'finished') {
622
+ change = completionChange(outcome.result, this.options.maxResultBytes, now, finalTtlMs);
623
+ }
624
+ else if (outcome.kind === 'internal') {
625
+ change = { kind: 'failed', error: internalErrorObject(), at: now, ttlMs: finalTtlMs };
626
+ }
627
+ else if (outcome.stop === 'cancelled') {
628
+ change = { kind: 'cancelled', at: now, ttlMs: finalTtlMs };
629
+ }
630
+ else if (outcome.stop === 'token-expired') {
631
+ change = completionChange(failure(tokenExpiredError(outcome.stage, job.mutation)), Number.MAX_SAFE_INTEGER, now, finalTtlMs);
632
+ }
633
+ else if (outcome.stop === 'run-timeout') {
634
+ change = completionChange(failure(taskRunTimeoutError(outcome.stage, job.mutation)), Number.MAX_SAFE_INTEGER, now, finalTtlMs);
635
+ }
636
+ else if (outcome.stop === 'ttl-ended') {
637
+ await this.store.expire(now).catch(() => { });
638
+ return;
639
+ }
640
+ else {
641
+ // 'lost': another process or server shutdown ended it; write nothing.
642
+ return;
643
+ }
644
+ for (let attempt = 0; attempt < 3; attempt++) {
645
+ try {
646
+ await this.store.update(job.id, job.owner, change);
647
+ break;
648
+ }
649
+ catch {
650
+ if (attempt < 2) {
651
+ await new Promise((resolve) => setTimeout(resolve, Math.min(this.options.checkIntervalMs, MAX_TIMEOUT_MS)));
652
+ }
653
+ }
654
+ }
655
+ }
656
+ async driveTask(job) {
657
+ const initialStop = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now(), job.runDeadlineMs) ??
658
+ job.running.reason;
659
+ if (initialStop !== undefined) {
660
+ return { kind: 'stopped', stop: initialStop, stage: 'not-started' };
661
+ }
662
+ let execSettled = false;
663
+ let execResult;
664
+ let execFailed = false;
665
+ const execPromise = Promise.resolve()
666
+ .then(() => this.executeCommand(job.commandName, job.input, job.context))
667
+ .then((result) => {
668
+ execSettled = true;
669
+ execResult = result;
670
+ return 'exec';
671
+ }, () => {
672
+ execSettled = true;
673
+ execFailed = true;
674
+ return 'exec';
675
+ });
676
+ const stoppedPromise = new Promise((resolve) => {
677
+ if (job.running.controller.signal.aborted) {
678
+ resolve('stopped');
679
+ }
680
+ else {
681
+ job.running.controller.signal.addEventListener('abort', () => resolve('stopped'), {
682
+ once: true,
683
+ });
684
+ }
685
+ });
686
+ const stopReason = () => job.running.reason;
687
+ for (;;) {
688
+ if (stopReason() === 'lost') {
689
+ return { kind: 'stopped', stop: 'lost', stage: 'running' };
690
+ }
691
+ if (execSettled) {
692
+ if (execFailed || !execResult)
693
+ return { kind: 'internal' };
694
+ // A handler that already returned keeps its result unless the token or TTL expired.
695
+ const due = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now());
696
+ return due !== undefined
697
+ ? { kind: 'stopped', stop: due, stage: 'finished' }
698
+ : { kind: 'finished', result: execResult };
699
+ }
700
+ const now = this.clock.now();
701
+ const due = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, now, job.runDeadlineMs);
702
+ if (due !== undefined) {
703
+ job.running.stop(due);
704
+ }
705
+ if (stopReason() === undefined) {
706
+ const message = job.takeProgress();
707
+ if (message !== undefined) {
708
+ await this.store
709
+ .update(job.id, job.owner, { kind: 'progress', message, at: now })
710
+ .catch(() => { });
711
+ }
712
+ if (this.store.heartbeat) {
713
+ await this.store.heartbeat(job.id, job.owner, now).catch(() => { });
714
+ }
715
+ try {
716
+ const current = await this.store.get(job.id, job.owner);
717
+ if (!current || isTaskExpired(current, now)) {
718
+ job.running.stop('ttl-ended');
719
+ }
720
+ else if (isTerminalTaskStatus(current.status)) {
721
+ job.running.stop('lost');
722
+ }
723
+ else if (current.cancelRequested) {
724
+ job.running.stop('cancelled');
725
+ }
726
+ }
727
+ catch {
728
+ // Transient store read failure: try again on the next check.
729
+ }
730
+ }
731
+ const reason = stopReason();
732
+ if (reason === 'lost' || reason === 'ttl-ended') {
733
+ return { kind: 'stopped', stop: reason, stage: 'running' };
734
+ }
735
+ if (execSettled)
736
+ continue;
737
+ if (reason !== undefined) {
738
+ return { kind: 'stopped', stop: reason, stage: 'running' };
739
+ }
740
+ const hardDeadline = Math.min(job.ttlDeadlineMs, job.runDeadlineMs);
741
+ const nearest = job.tokenDeadlineMs !== undefined
742
+ ? Math.min(job.tokenDeadlineMs, hardDeadline)
743
+ : hardDeadline;
744
+ const until = Math.max(1, nearest - now);
745
+ const waitMs = Math.min(this.options.checkIntervalMs, until, MAX_TIMEOUT_MS);
746
+ let timer;
747
+ const tickPromise = new Promise((resolve) => {
748
+ timer = setTimeout(() => resolve('tick'), waitMs);
749
+ });
750
+ try {
751
+ await Promise.race([execPromise, stoppedPromise, tickPromise]);
752
+ }
753
+ finally {
754
+ if (timer !== undefined)
755
+ clearTimeout(timer);
756
+ }
757
+ }
758
+ }
759
+ }
760
+ //# sourceMappingURL=tasks-runtime.js.map