@lushly-dev/afd-server 2.5.0 → 3.1.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.
- package/README.md +100 -21
- package/dist/admission.d.ts +137 -0
- package/dist/admission.d.ts.map +1 -0
- package/dist/admission.js +144 -0
- package/dist/admission.js.map +1 -0
- package/dist/app-call-registry.d.ts +2 -2
- package/dist/app-call-registry.d.ts.map +1 -1
- package/dist/app-call-registry.js +12 -4
- package/dist/app-call-registry.js.map +1 -1
- package/dist/approval-admission.d.ts +47 -1
- package/dist/approval-admission.d.ts.map +1 -1
- package/dist/approval-admission.js +87 -0
- package/dist/approval-admission.js.map +1 -1
- package/dist/approval-crypto.d.ts +16 -2
- package/dist/approval-crypto.d.ts.map +1 -1
- package/dist/approval-crypto.js +45 -11
- package/dist/approval-crypto.js.map +1 -1
- package/dist/approval-process-state.d.ts +3 -0
- package/dist/approval-process-state.d.ts.map +1 -1
- package/dist/approval-process-state.js +2 -0
- package/dist/approval-process-state.js.map +1 -1
- package/dist/approval-relay.d.ts +41 -5
- package/dist/approval-relay.d.ts.map +1 -1
- package/dist/approval-relay.js +8 -11
- package/dist/approval-relay.js.map +1 -1
- package/dist/approval-up-front.d.ts.map +1 -1
- package/dist/approval-up-front.js +62 -13
- package/dist/approval-up-front.js.map +1 -1
- package/dist/approval.d.ts +55 -3
- package/dist/approval.d.ts.map +1 -1
- package/dist/approval.js +208 -54
- package/dist/approval.js.map +1 -1
- package/dist/approver.d.ts +2 -2
- package/dist/approver.d.ts.map +1 -1
- package/dist/approver.js +6 -6
- package/dist/approver.js.map +1 -1
- package/dist/auth-middleware-check.d.ts +23 -0
- package/dist/auth-middleware-check.d.ts.map +1 -0
- package/dist/auth-middleware-check.js +48 -0
- package/dist/auth-middleware-check.js.map +1 -0
- package/dist/bootstrap/afd-context.d.ts.map +1 -1
- package/dist/bootstrap/afd-context.js +27 -3
- package/dist/bootstrap/afd-context.js.map +1 -1
- package/dist/bootstrap/afd-help.d.ts +3 -1
- package/dist/bootstrap/afd-help.d.ts.map +1 -1
- package/dist/bootstrap/afd-help.js +2 -0
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/described-command.d.ts +2 -1
- package/dist/bootstrap/described-command.d.ts.map +1 -1
- package/dist/bootstrap/described-command.js.map +1 -1
- package/dist/command-allow.d.ts +4 -4
- package/dist/command-allow.d.ts.map +1 -1
- package/dist/command-allow.js +10 -15
- package/dist/command-allow.js.map +1 -1
- package/dist/command-routing.d.ts +56 -8
- package/dist/command-routing.d.ts.map +1 -1
- package/dist/command-routing.js +82 -16
- package/dist/command-routing.js.map +1 -1
- package/dist/command-timeout.d.ts.map +1 -1
- package/dist/command-timeout.js +8 -1
- package/dist/command-timeout.js.map +1 -1
- package/dist/confirmation-gate.d.ts +7 -7
- package/dist/confirmation-gate.d.ts.map +1 -1
- package/dist/confirmation-gate.js +44 -26
- package/dist/confirmation-gate.js.map +1 -1
- package/dist/confirmations.d.ts +46 -3
- package/dist/confirmations.d.ts.map +1 -1
- package/dist/confirmations.js +6 -7
- package/dist/confirmations.js.map +1 -1
- package/dist/context-fields.d.ts +16 -1
- package/dist/context-fields.d.ts.map +1 -1
- package/dist/context-fields.js +21 -4
- package/dist/context-fields.js.map +1 -1
- package/dist/context-scope.d.ts +3 -3
- package/dist/context-scope.d.ts.map +1 -1
- package/dist/context-scope.js +7 -8
- package/dist/context-scope.js.map +1 -1
- package/dist/define-core.d.ts +39 -3
- package/dist/define-core.d.ts.map +1 -1
- package/dist/define-core.js +20 -4
- package/dist/define-core.js.map +1 -1
- package/dist/define.d.ts +2 -2
- package/dist/define.d.ts.map +1 -1
- package/dist/define.js.map +1 -1
- package/dist/direct-registry.d.ts +30 -8
- package/dist/direct-registry.d.ts.map +1 -1
- package/dist/direct-registry.js +26 -5
- package/dist/direct-registry.js.map +1 -1
- package/dist/direct-tool-surface.d.ts +3 -1
- package/dist/direct-tool-surface.d.ts.map +1 -1
- package/dist/direct-tool-surface.js +22 -5
- package/dist/direct-tool-surface.js.map +1 -1
- package/dist/direct.d.ts +4 -2
- package/dist/direct.d.ts.map +1 -1
- package/dist/direct.js +2 -0
- package/dist/direct.js.map +1 -1
- package/dist/execution.d.ts +35 -6
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +108 -15
- package/dist/execution.js.map +1 -1
- package/dist/frontmatter.js +16 -13
- package/dist/frontmatter.js.map +1 -1
- package/dist/host-state.d.ts +96 -0
- package/dist/host-state.d.ts.map +1 -0
- package/dist/host-state.js +62 -0
- package/dist/host-state.js.map +1 -0
- package/dist/http-handler.d.ts +31 -12
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +138 -102
- package/dist/http-handler.js.map +1 -1
- package/dist/http-security.js +2 -2
- package/dist/http-security.js.map +1 -1
- package/dist/http-sessions.d.ts +10 -0
- package/dist/http-sessions.d.ts.map +1 -1
- package/dist/http-sessions.js +12 -2
- package/dist/http-sessions.js.map +1 -1
- package/dist/http-sse.d.ts +9 -0
- package/dist/http-sse.d.ts.map +1 -1
- package/dist/http-sse.js +12 -3
- package/dist/http-sse.js.map +1 -1
- package/dist/human-relay.d.ts +195 -0
- package/dist/human-relay.d.ts.map +1 -0
- package/dist/human-relay.js +697 -0
- package/dist/human-relay.js.map +1 -0
- package/dist/idempotency-step.d.ts +243 -0
- package/dist/idempotency-step.d.ts.map +1 -0
- package/dist/idempotency-step.js +419 -0
- package/dist/idempotency-step.js.map +1 -0
- package/dist/idempotency-store.d.ts +107 -0
- package/dist/idempotency-store.d.ts.map +1 -0
- package/dist/idempotency-store.js +100 -0
- package/dist/idempotency-store.js.map +1 -0
- package/dist/index.d.ts +10 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -5
- package/dist/index.js.map +1 -1
- package/dist/instance-state.d.ts +7 -0
- package/dist/instance-state.d.ts.map +1 -1
- package/dist/instance-state.js +5 -2
- package/dist/instance-state.js.map +1 -1
- package/dist/journal-off-tape.d.ts +52 -0
- package/dist/journal-off-tape.d.ts.map +1 -0
- package/dist/journal-off-tape.js +150 -0
- package/dist/journal-off-tape.js.map +1 -0
- package/dist/journal-replay.d.ts.map +1 -1
- package/dist/journal-replay.js +7 -0
- package/dist/journal-replay.js.map +1 -1
- package/dist/journal-view.d.ts +50 -0
- package/dist/journal-view.d.ts.map +1 -0
- package/dist/journal-view.js +214 -0
- package/dist/journal-view.js.map +1 -0
- package/dist/journal.d.ts +24 -5
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +91 -40
- package/dist/journal.js.map +1 -1
- package/dist/lazy-tools.d.ts +13 -3
- package/dist/lazy-tools.d.ts.map +1 -1
- package/dist/lazy-tools.js +9 -2
- package/dist/lazy-tools.js.map +1 -1
- package/dist/mcp-auth-dispatch.d.ts +1 -1
- package/dist/mcp-auth-dispatch.d.ts.map +1 -1
- package/dist/mcp-auth-dispatch.js +2 -1
- package/dist/mcp-auth-dispatch.js.map +1 -1
- package/dist/mcp-auth-jwt.d.ts +11 -4
- package/dist/mcp-auth-jwt.d.ts.map +1 -1
- package/dist/mcp-auth-jwt.js +11 -9
- package/dist/mcp-auth-jwt.js.map +1 -1
- package/dist/mcp-auth-resource.d.ts +27 -3
- package/dist/mcp-auth-resource.d.ts.map +1 -1
- package/dist/mcp-auth-resource.js +37 -10
- package/dist/mcp-auth-resource.js.map +1 -1
- package/dist/mcp-auth-rules.d.ts +97 -18
- package/dist/mcp-auth-rules.d.ts.map +1 -1
- package/dist/mcp-auth-rules.js +194 -37
- package/dist/mcp-auth-rules.js.map +1 -1
- package/dist/mcp-auth-view.d.ts +3 -3
- package/dist/mcp-auth-view.d.ts.map +1 -1
- package/dist/mcp-auth-view.js +62 -25
- package/dist/mcp-auth-view.js.map +1 -1
- package/dist/mcp-auth.d.ts +27 -4
- package/dist/mcp-auth.d.ts.map +1 -1
- package/dist/mcp-auth.js +55 -14
- package/dist/mcp-auth.js.map +1 -1
- package/dist/mcp-modern.d.ts +70 -7
- package/dist/mcp-modern.d.ts.map +1 -1
- package/dist/mcp-modern.js +225 -111
- package/dist/mcp-modern.js.map +1 -1
- package/dist/meta-argument.d.ts +2 -1
- package/dist/meta-argument.d.ts.map +1 -1
- package/dist/meta-argument.js +13 -2
- package/dist/meta-argument.js.map +1 -1
- package/dist/meta-tools.js +2 -2
- package/dist/meta-tools.js.map +1 -1
- package/dist/middleware.d.ts +18 -3
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +53 -7
- package/dist/middleware.js.map +1 -1
- package/dist/output-budget.d.ts.map +1 -1
- package/dist/output-budget.js +2 -0
- package/dist/output-budget.js.map +1 -1
- package/dist/principal-binding.js +1 -1
- package/dist/principal-binding.js.map +1 -1
- package/dist/relay-evidence.d.ts +74 -0
- package/dist/relay-evidence.d.ts.map +1 -0
- package/dist/relay-evidence.js +143 -0
- package/dist/relay-evidence.js.map +1 -0
- package/dist/request-context.d.ts +4 -0
- package/dist/request-context.d.ts.map +1 -1
- package/dist/request-context.js +12 -2
- package/dist/request-context.js.map +1 -1
- package/dist/resources.js +1 -1
- package/dist/resources.js.map +1 -1
- package/dist/schema.d.ts +4 -3
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +3 -3
- package/dist/schema.js.map +1 -1
- package/dist/scope-view.d.ts +18 -5
- package/dist/scope-view.d.ts.map +1 -1
- package/dist/scope-view.js +9 -8
- package/dist/scope-view.js.map +1 -1
- package/dist/server-types.d.ts +44 -16
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts +26 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +359 -89
- package/dist/server.js.map +1 -1
- package/dist/task-dispatch.d.ts +12 -6
- package/dist/task-dispatch.d.ts.map +1 -1
- package/dist/task-dispatch.js +11 -12
- package/dist/task-dispatch.js.map +1 -1
- package/dist/task-input.d.ts +29 -0
- package/dist/task-input.d.ts.map +1 -0
- package/dist/task-input.js +75 -0
- package/dist/task-input.js.map +1 -0
- package/dist/tasks-input-gate.d.ts +61 -0
- package/dist/tasks-input-gate.d.ts.map +1 -0
- package/dist/tasks-input-gate.js +325 -0
- package/dist/tasks-input-gate.js.map +1 -0
- package/dist/tasks-input-runner.d.ts +125 -0
- package/dist/tasks-input-runner.d.ts.map +1 -0
- package/dist/tasks-input-runner.js +1017 -0
- package/dist/tasks-input-runner.js.map +1 -0
- package/dist/tasks-runtime.d.ts +34 -7
- package/dist/tasks-runtime.d.ts.map +1 -1
- package/dist/tasks-runtime.js +545 -94
- package/dist/tasks-runtime.js.map +1 -1
- package/dist/tasks.d.ts +196 -25
- package/dist/tasks.d.ts.map +1 -1
- package/dist/tasks.js +188 -26
- package/dist/tasks.js.map +1 -1
- package/dist/tool-router.d.ts +62 -3
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +251 -101
- package/dist/tool-router.js.map +1 -1
- package/dist/tools.d.ts +32 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +154 -40
- package/dist/tools.js.map +1 -1
- package/dist/up-front-steps.d.ts +8 -0
- package/dist/up-front-steps.d.ts.map +1 -1
- package/dist/up-front-steps.js +50 -1
- package/dist/up-front-steps.js.map +1 -1
- package/dist/validation.d.ts +14 -0
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +62 -17
- package/dist/validation.js.map +1 -1
- package/package.json +15 -11
package/dist/tasks-runtime.js
CHANGED
|
@@ -1,18 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @fileoverview MCP Tasks runtime: creation, background execution, cancellation, deadlines and
|
|
3
|
-
* `tasks/get`, `tasks/update`, `tasks/cancel` handlers (`spec/
|
|
3
|
+
* `tasks/get`, `tasks/update`, `tasks/cancel` handlers (`spec/tasks.md`;
|
|
4
4
|
* SEP-2663).
|
|
5
5
|
*/
|
|
6
6
|
import { randomBytes } from 'node:crypto';
|
|
7
7
|
import { ErrorCodes, failure, systemClock, truncateName } from '@lushly-dev/afd-core';
|
|
8
8
|
import { CLIENT_CAPABILITIES_META_KEY, ProtocolError, ProtocolErrorCode, } from '@modelcontextprotocol/server';
|
|
9
9
|
import { z } from 'zod';
|
|
10
|
+
import { canonicalJson, canonicalOrUndefined } from './approval-crypto.js';
|
|
11
|
+
import { approvalRelay, bindApprovalRelay, withoutApprovalRelay, } from './approval-relay.js';
|
|
12
|
+
import { approverCall, bindApprover, } from './approver.js';
|
|
13
|
+
import { confirmationBinding } from './confirmation-gate.js';
|
|
14
|
+
import { confirmationChannel, } from './confirmations.js';
|
|
10
15
|
import { bindContextState, resolveContextState } from './context-scope.js';
|
|
16
|
+
import { withHostState } from './host-state.js';
|
|
11
17
|
import { JsonRpcError } from './json-rpc.js';
|
|
12
18
|
import { bindOutputBudgetAsk, OUTPUT_BUDGET_ASK } from './output-budget.js';
|
|
13
19
|
import { principalBinding } from './principal-binding.js';
|
|
20
|
+
import { attachRelayDispatchAdmission, attachRelayEvidence, attachRelayValidatedInput, } from './relay-evidence.js';
|
|
14
21
|
import { bindScopeView, scopeViewOf } from './scope-view.js';
|
|
15
|
-
import { InMemoryTaskStore, isTaskExpired, isTerminalTaskStatus, resolveTaskOptions, TASKS_EXTENSION_ID, TaskStoreError, taskOwnerMatches, taskTtlFor, } from './tasks.js';
|
|
22
|
+
import { DEFAULT_TASK_FORM_TIMEOUT_MS, finishedTaskTtlFor, InMemoryTaskStore, isTaskExpired, isTerminalTaskStatus, resolveTaskOptions, TASKS_EXTENSION_ID, TaskStoreError, taskOwnerMatches, taskTtlFor, } from './tasks.js';
|
|
23
|
+
import { allowsRequestElicitationMode, confirmDeclinedError, confirmInputNotCanonicalError, confirmRequiredError, confirmUnansweredError, hasApprovalTokenInResult, missingElicitationCapability, stripApprovalTokenFromResult, validateTaskInputResponse, } from './tasks-input-gate.js';
|
|
24
|
+
import { TaskInputRunner, } from './tasks-input-runner.js';
|
|
16
25
|
import { resultContent } from './tool-router.js';
|
|
17
26
|
import { cloneVerifiedCredentials, unbrandVerifiedCredentials } from './verified-credentials.js';
|
|
18
27
|
/**
|
|
@@ -32,6 +41,9 @@ export class CreateTaskSignal {
|
|
|
32
41
|
*/
|
|
33
42
|
export function patchToolsCallForTasks(server) {
|
|
34
43
|
const sdk = server;
|
|
44
|
+
if (typeof sdk._wrapHandler !== 'function') {
|
|
45
|
+
throw new Error('@modelcontextprotocol/server Server._wrapHandler is missing; MCP Tasks dispatch requires it (#1744)');
|
|
46
|
+
}
|
|
35
47
|
const originalWrap = sdk._wrapHandler.bind(server);
|
|
36
48
|
sdk._wrapHandler = (method, handler) => {
|
|
37
49
|
if (method !== 'tools/call')
|
|
@@ -105,7 +117,10 @@ function wireDetailedTask(record) {
|
|
|
105
117
|
ttlMs: record.ttlMs,
|
|
106
118
|
pollIntervalMs: record.pollIntervalMs,
|
|
107
119
|
};
|
|
108
|
-
if (record.status === '
|
|
120
|
+
if (record.status === 'input_required' && record.pendingInput) {
|
|
121
|
+
base.inputRequests = { [record.pendingInput.key]: record.pendingInput.request };
|
|
122
|
+
}
|
|
123
|
+
else if (record.status === 'completed') {
|
|
109
124
|
base.result = record.result ?? { content: [], isError: false };
|
|
110
125
|
}
|
|
111
126
|
else if (record.status === 'failed') {
|
|
@@ -139,6 +154,23 @@ function missingTasksCapability() {
|
|
|
139
154
|
},
|
|
140
155
|
});
|
|
141
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* A request-local copy of the actor: its declared fields (`kind`, `id`, `label`, `onBehalfOf`) and
|
|
159
|
+
* every other enumerable field a host put on it (a workspace id, say), each read exactly once. A
|
|
160
|
+
* spread alone would drop a field a class exposes through a getter, and so change the principal
|
|
161
|
+
* binding the copy is made for (#3011). Declared fields left undefined are left out.
|
|
162
|
+
*/
|
|
163
|
+
function snapshotActor(actor) {
|
|
164
|
+
// One destructuring: each field, a getter's included, is read once, and the rest are kept.
|
|
165
|
+
const { kind, id, label, onBehalfOf, ...extra } = actor;
|
|
166
|
+
return {
|
|
167
|
+
...extra,
|
|
168
|
+
kind,
|
|
169
|
+
...(id !== undefined ? { id } : {}),
|
|
170
|
+
...(label !== undefined ? { label } : {}),
|
|
171
|
+
...(onBehalfOf !== undefined ? { onBehalfOf } : {}),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
142
174
|
function taskNotFound() {
|
|
143
175
|
return new ProtocolError(ProtocolErrorCode.InvalidParams, 'Task not found');
|
|
144
176
|
}
|
|
@@ -154,6 +186,7 @@ function taskLimitError() {
|
|
|
154
186
|
message: 'The task could not start: a task limit was reached, so nothing ran',
|
|
155
187
|
suggestion: 'Wait for one of your tasks to finish or expire, then call again.',
|
|
156
188
|
retryable: true,
|
|
189
|
+
recovery: { kind: 'retry' },
|
|
157
190
|
};
|
|
158
191
|
}
|
|
159
192
|
function compositeTaskError(tool, commandName) {
|
|
@@ -170,10 +203,15 @@ function unidentifiedCallersError(command) {
|
|
|
170
203
|
message: `Command '${truncateName(command)}' runs only as a task, and this server cannot tell its callers apart, so it starts no task`,
|
|
171
204
|
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.",
|
|
172
205
|
retryable: false,
|
|
206
|
+
recovery: { kind: 'external' },
|
|
173
207
|
};
|
|
174
208
|
}
|
|
209
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
210
|
+
// RUNNER STATE & DEADLINE HELPERS
|
|
211
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
175
212
|
function createRunningTask() {
|
|
176
213
|
const controller = new AbortController();
|
|
214
|
+
const inputListeners = new Set();
|
|
177
215
|
const running = {
|
|
178
216
|
controller,
|
|
179
217
|
reason: undefined,
|
|
@@ -184,18 +222,53 @@ function createRunningTask() {
|
|
|
184
222
|
if (!controller.signal.aborted) {
|
|
185
223
|
controller.abort();
|
|
186
224
|
}
|
|
225
|
+
for (const listener of inputListeners)
|
|
226
|
+
listener();
|
|
227
|
+
},
|
|
228
|
+
notifyInput() {
|
|
229
|
+
for (const listener of inputListeners)
|
|
230
|
+
listener();
|
|
231
|
+
},
|
|
232
|
+
onInput(listener) {
|
|
233
|
+
inputListeners.add(listener);
|
|
234
|
+
return () => {
|
|
235
|
+
inputListeners.delete(listener);
|
|
236
|
+
};
|
|
187
237
|
},
|
|
188
238
|
};
|
|
189
239
|
return running;
|
|
190
240
|
}
|
|
191
|
-
/** What deadline is due at `nowMs`: token expiry first, then TTL. */
|
|
192
|
-
export function dueTaskStop(tokenDeadlineMs, ttlDeadlineMs, nowMs) {
|
|
241
|
+
/** What deadline is due at `nowMs`: token expiry first, then TTL, then optional run budget. */
|
|
242
|
+
export function dueTaskStop(tokenDeadlineMs, ttlDeadlineMs, nowMs, runDeadlineMs) {
|
|
193
243
|
if (tokenDeadlineMs !== undefined && nowMs >= tokenDeadlineMs)
|
|
194
244
|
return 'token-expired';
|
|
195
245
|
if (nowMs >= ttlDeadlineMs)
|
|
196
246
|
return 'ttl-ended';
|
|
247
|
+
if (runDeadlineMs !== undefined && nowMs >= runDeadlineMs)
|
|
248
|
+
return 'run-timeout';
|
|
197
249
|
return undefined;
|
|
198
250
|
}
|
|
251
|
+
/** Build `TIMEOUT` for a task whose run budget elapsed, retryable unless a mutation may have run. */
|
|
252
|
+
export function taskRunTimeoutError(stage, mutation) {
|
|
253
|
+
if (stage === 'not-started') {
|
|
254
|
+
return {
|
|
255
|
+
code: ErrorCodes.TIMEOUT,
|
|
256
|
+
message: 'The task did not start before its run budget elapsed',
|
|
257
|
+
suggestion: 'Nothing ran. Increase the task run budget or simplify the request and start it again.',
|
|
258
|
+
retryable: true,
|
|
259
|
+
recovery: { kind: 'retry' },
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
code: ErrorCodes.TIMEOUT,
|
|
264
|
+
message: 'The task stopped because its run budget elapsed',
|
|
265
|
+
suggestion: mutation
|
|
266
|
+
? 'The command may have made part of its change before it stopped: check its effect before starting it again.'
|
|
267
|
+
: 'Simplify or narrow the request, or increase the task run budget, and start it again.',
|
|
268
|
+
retryable: !mutation,
|
|
269
|
+
recovery: { kind: 'external' },
|
|
270
|
+
};
|
|
271
|
+
}
|
|
199
272
|
/** Build `TASK_TOKEN_EXPIRED`, retryable unless a mutation may have started. */
|
|
200
273
|
export function tokenExpiredError(stage, mutation) {
|
|
201
274
|
let message;
|
|
@@ -222,20 +295,30 @@ export function tokenExpiredError(stage, mutation) {
|
|
|
222
295
|
message,
|
|
223
296
|
suggestion,
|
|
224
297
|
retryable: stage === 'not-started' || !mutation,
|
|
298
|
+
recovery: { kind: 'external' },
|
|
225
299
|
};
|
|
226
300
|
}
|
|
227
|
-
function completionChange(result, maxResultBytes, at) {
|
|
228
|
-
|
|
301
|
+
function completionChange(result, maxResultBytes, at, ttlMs, approvalRefusal = false) {
|
|
302
|
+
// A result JSON cannot hold (a BigInt, a cycle) throws in resultContent too: the task fails
|
|
303
|
+
// with an internal error instead of staying `working`.
|
|
304
|
+
let toolResult;
|
|
229
305
|
let serialized;
|
|
230
306
|
try {
|
|
307
|
+
toolResult = resultContent(result, !result.success);
|
|
231
308
|
serialized = JSON.stringify(toolResult);
|
|
232
309
|
}
|
|
233
310
|
catch {
|
|
234
|
-
return { kind: 'failed', error: internalErrorObject(), at };
|
|
311
|
+
return { kind: 'failed', error: internalErrorObject(), at, ttlMs };
|
|
235
312
|
}
|
|
236
313
|
const size = utf8.encode(serialized).byteLength;
|
|
237
314
|
if (size <= maxResultBytes) {
|
|
238
|
-
return {
|
|
315
|
+
return {
|
|
316
|
+
kind: 'completed',
|
|
317
|
+
result: toolResult,
|
|
318
|
+
at,
|
|
319
|
+
ttlMs,
|
|
320
|
+
...(approvalRefusal && { approvalRefusal: true }),
|
|
321
|
+
};
|
|
239
322
|
}
|
|
240
323
|
const tooLarge = {
|
|
241
324
|
code: ErrorCodes.INTERNAL_ERROR,
|
|
@@ -244,16 +327,16 @@ function completionChange(result, maxResultBytes, at) {
|
|
|
244
327
|
details: { limitBytes: maxResultBytes, actualBytes: size },
|
|
245
328
|
retryable: false,
|
|
246
329
|
};
|
|
247
|
-
return { kind: 'completed', result: resultContent(failure(tooLarge), true), at };
|
|
330
|
+
return { kind: 'completed', result: resultContent(failure(tooLarge), true), at, ttlMs };
|
|
248
331
|
}
|
|
249
|
-
/** Copy string-keyed properties and only the safe symbols (`scopeView`, `contextState`). */
|
|
250
|
-
function cloneTaskContext(context, signal, reportProgress) {
|
|
332
|
+
/** Copy string-keyed properties and only the safe symbols (`scopeView`, `contextState`, `approver`). */
|
|
333
|
+
function cloneTaskContext(context, signal, reportProgress, approver) {
|
|
251
334
|
const copy = {};
|
|
252
335
|
for (const key of Object.keys(context)) {
|
|
253
336
|
copy[key] = context[key];
|
|
254
337
|
}
|
|
255
|
-
// MCP Tasks are bounded by their own
|
|
256
|
-
// the inline server defaultTimeoutMs; keep an explicit per-request timeout if
|
|
338
|
+
// MCP Tasks are bounded by their own run budget (default 1 h), TTL and cancellation signal
|
|
339
|
+
// rather than the inline server defaultTimeoutMs; keep an explicit per-request timeout if set.
|
|
257
340
|
if (copy.timeout === undefined) {
|
|
258
341
|
copy.timeout = 0;
|
|
259
342
|
}
|
|
@@ -263,15 +346,23 @@ function cloneTaskContext(context, signal, reportProgress) {
|
|
|
263
346
|
reportProgress,
|
|
264
347
|
};
|
|
265
348
|
const view = scopeViewOf(context);
|
|
266
|
-
if (view)
|
|
349
|
+
if (view) {
|
|
350
|
+
// Routing decides the view first today; this keeps a future route from asking after the answer.
|
|
351
|
+
view.settle();
|
|
267
352
|
taskContext = bindScopeView(taskContext, view);
|
|
353
|
+
}
|
|
268
354
|
const state = resolveContextState(context, undefined);
|
|
269
355
|
if (state !== undefined)
|
|
270
356
|
taskContext = bindContextState(taskContext, state);
|
|
271
357
|
if (Object.hasOwn(context, OUTPUT_BUDGET_ASK)) {
|
|
272
358
|
taskContext = bindOutputBudgetAsk(taskContext, context[OUTPUT_BUDGET_ASK]);
|
|
273
359
|
}
|
|
274
|
-
|
|
360
|
+
if (approver) {
|
|
361
|
+
taskContext = bindApprover(taskContext, approver);
|
|
362
|
+
}
|
|
363
|
+
// The idempotency step never acts on a task run, and the retry middleware counts it as carrying
|
|
364
|
+
// no key (spec/idempotency.md, S11).
|
|
365
|
+
return withHostState(taskContext, { taskRun: true });
|
|
275
366
|
}
|
|
276
367
|
const taskIdParamsSchema = z.object({ taskId: z.string() });
|
|
277
368
|
const updateTaskParamsSchema = z.object({
|
|
@@ -286,18 +377,48 @@ export class TaskRuntime {
|
|
|
286
377
|
hasAuth;
|
|
287
378
|
hasContextHook;
|
|
288
379
|
actor;
|
|
380
|
+
confirmations;
|
|
381
|
+
approver;
|
|
382
|
+
commandNames;
|
|
383
|
+
humanRelayGate;
|
|
384
|
+
listedApprovalCommands;
|
|
289
385
|
executeCommand;
|
|
386
|
+
validateCommand;
|
|
387
|
+
inputRunner;
|
|
290
388
|
running = new Map();
|
|
291
389
|
constructor(deps) {
|
|
292
390
|
this.store = deps.store ?? new InMemoryTaskStore();
|
|
293
|
-
this.options = resolveTaskOptions(deps.options);
|
|
391
|
+
this.options = resolveTaskOptions(deps.options, deps.store);
|
|
294
392
|
this.clock = deps.clock ?? systemClock;
|
|
295
393
|
this.hasAuth = deps.hasAuth;
|
|
296
394
|
this.hasContextHook = deps.hasContextHook;
|
|
297
395
|
this.actor = deps.actor;
|
|
396
|
+
this.confirmations = deps.confirmations ?? 'off';
|
|
397
|
+
this.approver = deps.approver;
|
|
398
|
+
this.commandNames = new Set(deps.commands.map((cmd) => cmd.name));
|
|
399
|
+
this.humanRelayGate = deps.humanRelayGate;
|
|
400
|
+
this.listedApprovalCommands = deps.listedApprovalCommands ?? new Set();
|
|
298
401
|
this.executeCommand = deps.executeCommand;
|
|
402
|
+
this.validateCommand = deps.validateCommand;
|
|
403
|
+
this.inputRunner = new TaskInputRunner({
|
|
404
|
+
store: this.store,
|
|
405
|
+
options: this.options,
|
|
406
|
+
clock: this.clock,
|
|
407
|
+
humanRelay: deps.humanRelay,
|
|
408
|
+
humanRelayGate: deps.humanRelayGate,
|
|
409
|
+
contextFields: deps.contextFields,
|
|
410
|
+
devMode: deps.devMode === true,
|
|
411
|
+
onError: deps.onError,
|
|
412
|
+
dueTaskStop,
|
|
413
|
+
});
|
|
299
414
|
this.servesTasks = deps.commands.some((cmd) => cmd.task === 'optional' || cmd.task === 'required');
|
|
300
415
|
}
|
|
416
|
+
isGatedTaskCommand(command) {
|
|
417
|
+
return (command.confirmationMode === 'host-verified' ||
|
|
418
|
+
(this.confirmations !== 'off' && command.confirmPrompt !== undefined) ||
|
|
419
|
+
(command.approval !== undefined && command.approval !== 'not-required') ||
|
|
420
|
+
this.listedApprovalCommands.has(command.name));
|
|
421
|
+
}
|
|
301
422
|
get hookIdentifiesCallers() {
|
|
302
423
|
return this.options.callersIdentifiedByHook && this.hasContextHook;
|
|
303
424
|
}
|
|
@@ -316,7 +437,7 @@ export class TaskRuntime {
|
|
|
316
437
|
/** Build the {@link TaskDispatch} for one modern/stdio `tools/call`. */
|
|
317
438
|
dispatchFor(era, isHttp, ctx, credentials) {
|
|
318
439
|
return {
|
|
319
|
-
dispatch: async (command, input, context) => {
|
|
440
|
+
dispatch: async (command, input, context, meta) => {
|
|
320
441
|
if (command.task !== 'optional' && command.task !== 'required')
|
|
321
442
|
return undefined;
|
|
322
443
|
if (!this.identifiesCaller(isHttp, credentials)) {
|
|
@@ -330,7 +451,7 @@ export class TaskRuntime {
|
|
|
330
451
|
throw missingTasksCapability();
|
|
331
452
|
return undefined;
|
|
332
453
|
}
|
|
333
|
-
return this.startTask(command, input, context);
|
|
454
|
+
return this.startTask(command, input, context, meta);
|
|
334
455
|
},
|
|
335
456
|
refuseComposite: compositeTaskError,
|
|
336
457
|
};
|
|
@@ -360,6 +481,14 @@ export class TaskRuntime {
|
|
|
360
481
|
installHandlers(server, opts) {
|
|
361
482
|
if (!this.declaresTasksTo(opts.isHttp))
|
|
362
483
|
return;
|
|
484
|
+
const throwInsufficientScope = (view, forbidden) => {
|
|
485
|
+
const error = view.insufficientScope(forbidden);
|
|
486
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
|
|
487
|
+
code: error.code,
|
|
488
|
+
suggestion: error.suggestion,
|
|
489
|
+
scopes: error.details?.scopes ?? forbidden,
|
|
490
|
+
});
|
|
491
|
+
};
|
|
363
492
|
const resolveCaller = async (ctx) => {
|
|
364
493
|
if (!requestDeclaresTasks(opts.era, ctx)) {
|
|
365
494
|
throw missingTasksCapability();
|
|
@@ -367,12 +496,7 @@ export class TaskRuntime {
|
|
|
367
496
|
const view = opts.requestView?.();
|
|
368
497
|
const reqDecision = view?.decideRequest();
|
|
369
498
|
if (view && reqDecision && reqDecision !== 'proceed') {
|
|
370
|
-
|
|
371
|
-
throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
|
|
372
|
-
code: error.code,
|
|
373
|
-
suggestion: error.suggestion,
|
|
374
|
-
scopes: reqDecision.forbidden,
|
|
375
|
-
});
|
|
499
|
+
throwInsufficientScope(view, reqDecision.forbidden);
|
|
376
500
|
}
|
|
377
501
|
let values;
|
|
378
502
|
try {
|
|
@@ -381,7 +505,10 @@ export class TaskRuntime {
|
|
|
381
505
|
catch (error) {
|
|
382
506
|
throw opts.internalError(error);
|
|
383
507
|
}
|
|
384
|
-
|
|
508
|
+
// A request-local copy, taken before the binding: the store's `getFor` then sees the
|
|
509
|
+
// actor the binding was made from, whatever later happens to a shared one.
|
|
510
|
+
const shared = (values.actor ?? this.actor);
|
|
511
|
+
const actor = shared ? snapshotActor(shared) : undefined;
|
|
385
512
|
const credentials = (view?.credentials ?? values.credentials);
|
|
386
513
|
let owner;
|
|
387
514
|
try {
|
|
@@ -390,14 +517,18 @@ export class TaskRuntime {
|
|
|
390
517
|
catch {
|
|
391
518
|
throw internalRpcError();
|
|
392
519
|
}
|
|
393
|
-
|
|
520
|
+
// The context the caller's request runs with, which the store's `getFor` and `approver` receive.
|
|
521
|
+
const context = { ...values, actor, credentials, interface: 'mcp' };
|
|
522
|
+
return { owner, view, context };
|
|
394
523
|
};
|
|
395
524
|
const findTask = async (caller, taskId, needsCommand) => {
|
|
396
525
|
if (!isTaskId(taskId))
|
|
397
526
|
throw taskNotFound();
|
|
398
527
|
let record;
|
|
399
528
|
try {
|
|
400
|
-
record =
|
|
529
|
+
record = this.store.getFor
|
|
530
|
+
? await this.store.getFor(taskId, caller.owner, caller.context)
|
|
531
|
+
: await this.store.get(taskId, caller.owner);
|
|
401
532
|
}
|
|
402
533
|
catch {
|
|
403
534
|
throw internalRpcError();
|
|
@@ -406,7 +537,8 @@ export class TaskRuntime {
|
|
|
406
537
|
if (!record ||
|
|
407
538
|
record.id !== taskId ||
|
|
408
539
|
!taskOwnerMatches(record.owner, caller.owner) ||
|
|
409
|
-
isTaskExpired(record, now)
|
|
540
|
+
isTaskExpired(record, now) ||
|
|
541
|
+
!this.commandNames.has(record.command)) {
|
|
410
542
|
throw taskNotFound();
|
|
411
543
|
}
|
|
412
544
|
if (caller.view && !caller.view.known(record.command)) {
|
|
@@ -415,24 +547,96 @@ export class TaskRuntime {
|
|
|
415
547
|
if (needsCommand && caller.view) {
|
|
416
548
|
const decision = caller.view.decideTask(record.command);
|
|
417
549
|
if (decision !== 'proceed') {
|
|
418
|
-
|
|
419
|
-
throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
|
|
420
|
-
code: error.code,
|
|
421
|
-
suggestion: error.suggestion,
|
|
422
|
-
scopes: decision.forbidden,
|
|
423
|
-
});
|
|
550
|
+
throwInsufficientScope(caller.view, decision.forbidden);
|
|
424
551
|
}
|
|
425
552
|
}
|
|
426
553
|
return record;
|
|
427
554
|
};
|
|
555
|
+
const checkInputScope = (view, record) => {
|
|
556
|
+
if (!view)
|
|
557
|
+
return;
|
|
558
|
+
const decision = view.decideTaskInput(record.command, record.inputSnapshot);
|
|
559
|
+
if (decision !== 'proceed') {
|
|
560
|
+
throwInsufficientScope(view, decision.forbidden);
|
|
561
|
+
}
|
|
562
|
+
};
|
|
428
563
|
server.setRequestHandler('tasks/get', { params: taskIdParamsSchema }, async (params, ctx) => {
|
|
429
564
|
const caller = await resolveCaller(ctx);
|
|
430
565
|
const record = await findTask(caller, params.taskId, true);
|
|
566
|
+
if (record.status === 'input_required' && record.pendingInput) {
|
|
567
|
+
checkInputScope(caller.view, record);
|
|
568
|
+
const rawCaps = ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY];
|
|
569
|
+
if (!allowsRequestElicitationMode(record.pendingInput.request, rawCaps)) {
|
|
570
|
+
throw missingElicitationCapability(record.pendingInput.request.params.mode);
|
|
571
|
+
}
|
|
572
|
+
return wireDetailedTask(record);
|
|
573
|
+
}
|
|
574
|
+
if (record.status === 'completed' &&
|
|
575
|
+
(record.approvalRefusal || hasApprovalTokenInResult(record.result))) {
|
|
576
|
+
if (record.approvalRefusal && record.inputSnapshot !== undefined) {
|
|
577
|
+
checkInputScope(caller.view, record);
|
|
578
|
+
}
|
|
579
|
+
let isApprover = false;
|
|
580
|
+
if (this.approver) {
|
|
581
|
+
try {
|
|
582
|
+
isApprover = this.approver(caller.context) === true;
|
|
583
|
+
}
|
|
584
|
+
catch {
|
|
585
|
+
throw internalRpcError();
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (!isApprover && record.result) {
|
|
589
|
+
return wireDetailedTask({
|
|
590
|
+
...record,
|
|
591
|
+
result: stripApprovalTokenFromResult(record.result),
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
}
|
|
431
595
|
return wireDetailedTask(record);
|
|
432
596
|
});
|
|
433
597
|
server.setRequestHandler('tasks/update', { params: updateTaskParamsSchema }, async (params, ctx) => {
|
|
434
598
|
const caller = await resolveCaller(ctx);
|
|
435
|
-
await findTask(caller, params.taskId, true);
|
|
599
|
+
const record = await findTask(caller, params.taskId, true);
|
|
600
|
+
if (!this.options.allowInput ||
|
|
601
|
+
isTerminalTaskStatus(record.status) ||
|
|
602
|
+
record.cancelRequested ||
|
|
603
|
+
!record.pendingInput ||
|
|
604
|
+
record.pendingInput.answered === true ||
|
|
605
|
+
record.answeredInput !== undefined) {
|
|
606
|
+
return {};
|
|
607
|
+
}
|
|
608
|
+
const mcpReq = ctx.mcpReq;
|
|
609
|
+
const responses = params.inputResponses ?? mcpReq.inputResponses;
|
|
610
|
+
const hasKey = (responses !== undefined && Object.hasOwn(responses, record.pendingInput.key)) ||
|
|
611
|
+
(mcpReq.droppedInputResponseKeys?.includes(record.pendingInput.key) ?? false);
|
|
612
|
+
if (!hasKey) {
|
|
613
|
+
return {};
|
|
614
|
+
}
|
|
615
|
+
checkInputScope(caller.view, record);
|
|
616
|
+
if (!responses || !Object.hasOwn(responses, record.pendingInput.key)) {
|
|
617
|
+
return {};
|
|
618
|
+
}
|
|
619
|
+
const validated = validateTaskInputResponse(record.pendingInput.request, responses[record.pendingInput.key]);
|
|
620
|
+
if (!validated) {
|
|
621
|
+
return {};
|
|
622
|
+
}
|
|
623
|
+
const now = this.clock.now();
|
|
624
|
+
let applied;
|
|
625
|
+
try {
|
|
626
|
+
const res = await this.store.update(record.id, caller.owner, {
|
|
627
|
+
kind: 'input-answered',
|
|
628
|
+
key: record.pendingInput.key,
|
|
629
|
+
response: validated,
|
|
630
|
+
at: now,
|
|
631
|
+
});
|
|
632
|
+
applied = typeof res === 'boolean' ? res : undefined;
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
throw internalRpcError();
|
|
636
|
+
}
|
|
637
|
+
if (applied !== false) {
|
|
638
|
+
this.running.get(record.id)?.notifyInput();
|
|
639
|
+
}
|
|
436
640
|
return {};
|
|
437
641
|
});
|
|
438
642
|
server.setRequestHandler('tasks/cancel', { params: taskIdParamsSchema }, async (params, ctx) => {
|
|
@@ -452,9 +656,33 @@ export class TaskRuntime {
|
|
|
452
656
|
return {};
|
|
453
657
|
});
|
|
454
658
|
}
|
|
455
|
-
async startTask(command, input, context) {
|
|
659
|
+
async startTask(command, input, context, meta) {
|
|
660
|
+
// Validated once, as the inline call would be, before anything is recorded: an input the
|
|
661
|
+
// command refuses is answered inline and gets no task. For a host-verified retry carrying a
|
|
662
|
+
// pending state or pending-list entry, reuse the inline relay's stored validated input first
|
|
663
|
+
// so dynamic schema defaults stay bound across the decision (`spec/tasks.md`).
|
|
456
664
|
const actor = (context.actor ?? this.actor);
|
|
457
665
|
const credentials = context.credentials;
|
|
666
|
+
let pendingValidated;
|
|
667
|
+
if (this.options.allowInput &&
|
|
668
|
+
command.confirmationMode === 'host-verified' &&
|
|
669
|
+
this.humanRelayGate?.resolvePendingInput) {
|
|
670
|
+
let ownerForPending;
|
|
671
|
+
try {
|
|
672
|
+
ownerForPending = principalBinding(actor, credentials);
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
ownerForPending = undefined;
|
|
676
|
+
}
|
|
677
|
+
if (ownerForPending !== undefined) {
|
|
678
|
+
pendingValidated = this.humanRelayGate.resolvePendingInput(command, input, context, ownerForPending);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
const checked = pendingValidated
|
|
682
|
+
? { ok: true, data: pendingValidated.data }
|
|
683
|
+
: await this.validateCommand(command.name, command, input, context);
|
|
684
|
+
if (!checked.ok)
|
|
685
|
+
return resultContent(checked.result, true);
|
|
458
686
|
let owner;
|
|
459
687
|
try {
|
|
460
688
|
owner = principalBinding(actor, credentials);
|
|
@@ -462,11 +690,107 @@ export class TaskRuntime {
|
|
|
462
690
|
catch {
|
|
463
691
|
throw internalRpcError();
|
|
464
692
|
}
|
|
693
|
+
let snapshotJson;
|
|
694
|
+
let inputSnapshot;
|
|
695
|
+
let needsConfirm = false;
|
|
696
|
+
let confirmValidUntil;
|
|
697
|
+
let preApprovedRelay;
|
|
698
|
+
let relayGate;
|
|
699
|
+
let initialApprovalAnswers;
|
|
700
|
+
const creatingApprover = this.options.allowInput ? approverCall(context) : undefined;
|
|
701
|
+
const canElicitForm = confirmationChannel(context)?.canElicit === true;
|
|
702
|
+
if (this.options.allowInput) {
|
|
703
|
+
const isHostVerified = command.confirmationMode === 'host-verified';
|
|
704
|
+
const isConfirmGated = !isHostVerified && this.confirmations !== 'off' && command.confirmPrompt !== undefined;
|
|
705
|
+
// Refusals the inline gates make first: canonical JSON for confirmation before snapshot.
|
|
706
|
+
if (isConfirmGated) {
|
|
707
|
+
try {
|
|
708
|
+
confirmationBinding([{ command: command.name, input: input ?? {} }]);
|
|
709
|
+
canonicalJson(checked.data);
|
|
710
|
+
}
|
|
711
|
+
catch {
|
|
712
|
+
return resultContent(failure(confirmInputNotCanonicalError(command.name)), true);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
// Snapshot the validated input in `JSON.stringify` form before scope checks and `create`
|
|
716
|
+
// so every check (creation, poll, update) decides on the exact same value.
|
|
717
|
+
try {
|
|
718
|
+
const raw = JSON.stringify(checked.data);
|
|
719
|
+
if (raw === undefined)
|
|
720
|
+
throw new TypeError('Input has no JSON form');
|
|
721
|
+
snapshotJson = raw;
|
|
722
|
+
inputSnapshot = JSON.parse(raw);
|
|
723
|
+
}
|
|
724
|
+
catch {
|
|
725
|
+
return resultContent(failure({
|
|
726
|
+
code: ErrorCodes.INTERNAL_ERROR,
|
|
727
|
+
message: 'The task could not be recorded, so nothing ran',
|
|
728
|
+
suggestion: 'Retry later.',
|
|
729
|
+
retryable: true,
|
|
730
|
+
}), true);
|
|
731
|
+
}
|
|
732
|
+
// Before any gate is worked out, check the caller's input-specific scopes on the
|
|
733
|
+
// validated snapshot (a resolver's `defer` counts as a failure).
|
|
734
|
+
if (this.isGatedTaskCommand(command)) {
|
|
735
|
+
const view = scopeViewOf(context);
|
|
736
|
+
if (view) {
|
|
737
|
+
const decision = view.decideTaskInput(command.name, inputSnapshot);
|
|
738
|
+
if (decision !== 'proceed') {
|
|
739
|
+
return resultContent(failure(view.insufficientScope(decision.forbidden)), true);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
if (isHostVerified) {
|
|
744
|
+
const pre = await this.inputRunner.precheckHostVerified(command, input, checked.data, context, actor, owner);
|
|
745
|
+
if (pre.kind === 'error')
|
|
746
|
+
return resultContent(failure(pre.error), true);
|
|
747
|
+
if (pre.kind === 'approved') {
|
|
748
|
+
preApprovedRelay = pre.approval;
|
|
749
|
+
}
|
|
750
|
+
else {
|
|
751
|
+
relayGate = pre.gate;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
else if (isConfirmGated) {
|
|
755
|
+
const binding = confirmationBinding([{ command: command.name, input: input ?? {} }]);
|
|
756
|
+
const channel = confirmationChannel(context);
|
|
757
|
+
const response = channel ? await channel.response(binding) : 'missing';
|
|
758
|
+
if (response === 'decline') {
|
|
759
|
+
return resultContent(failure(confirmDeclinedError(command.name)), true);
|
|
760
|
+
}
|
|
761
|
+
if (response === 'accept') {
|
|
762
|
+
confirmValidUntil =
|
|
763
|
+
(await channel?.responseExpiry?.(binding)) ??
|
|
764
|
+
this.clock.now() + DEFAULT_TASK_FORM_TIMEOUT_MS;
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
const ack = meta?.acknowledged;
|
|
768
|
+
const covered = this.confirmations === 'enforce' &&
|
|
769
|
+
(channel?.acknowledged === true ||
|
|
770
|
+
ack === 'all' ||
|
|
771
|
+
(ack instanceof Set && ack.has(command.name)));
|
|
772
|
+
if (!covered) {
|
|
773
|
+
if (channel?.canElicit) {
|
|
774
|
+
needsConfirm = true;
|
|
775
|
+
}
|
|
776
|
+
else {
|
|
777
|
+
return resultContent(failure(confirmRequiredError(command, this.confirmations, meta?.howToAcknowledge ?? 'repeat the call with confirm: true')), true);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
// Carry any inline approval answer/decline from the creating call into the task run.
|
|
783
|
+
const inlineApproval = approvalRelay(context);
|
|
784
|
+
if (inlineApproval) {
|
|
785
|
+
initialApprovalAnswers = await inlineApproval.answers();
|
|
786
|
+
}
|
|
787
|
+
}
|
|
465
788
|
const id = newTaskId();
|
|
466
789
|
const now = this.clock.now();
|
|
467
|
-
await this.store.expire(now).catch(() => { });
|
|
790
|
+
await this.store.expire?.(now).catch(() => { });
|
|
468
791
|
const expiresAtSeconds = typeof credentials?.expiresAt === 'number' ? credentials.expiresAt : undefined;
|
|
469
792
|
const ttlMs = taskTtlFor(this.options, now, expiresAtSeconds);
|
|
793
|
+
const gatedCommand = this.isGatedTaskCommand(command);
|
|
470
794
|
const record = {
|
|
471
795
|
id,
|
|
472
796
|
owner,
|
|
@@ -477,6 +801,12 @@ export class TaskRuntime {
|
|
|
477
801
|
ttlMs,
|
|
478
802
|
pollIntervalMs: this.options.pollIntervalMs,
|
|
479
803
|
cancelRequested: false,
|
|
804
|
+
...(this.options.allowInput && { handlerStarted: false }),
|
|
805
|
+
...(this.options.allowInput &&
|
|
806
|
+
gatedCommand &&
|
|
807
|
+
snapshotJson !== undefined && {
|
|
808
|
+
inputSnapshot: JSON.parse(snapshotJson),
|
|
809
|
+
}),
|
|
480
810
|
};
|
|
481
811
|
if (this.running.size >= this.options.maxRunning) {
|
|
482
812
|
return resultContent(failure(taskLimitError()), true);
|
|
@@ -484,10 +814,21 @@ export class TaskRuntime {
|
|
|
484
814
|
const running = createRunningTask();
|
|
485
815
|
this.running.set(id, running);
|
|
486
816
|
try {
|
|
487
|
-
|
|
817
|
+
// The validated input as JSON, as `JSON.stringify` gives it: a copy of its own, so a store
|
|
818
|
+
// that edits what it is given cannot change what the handler runs. A value JSON cannot
|
|
819
|
+
// hold fails here, as a store that cannot record it does: nothing ran.
|
|
820
|
+
// (A root `undefined` has no JSON form: `JSON.parse` throws, and nothing runs.)
|
|
821
|
+
const storeInput = snapshotJson !== undefined
|
|
822
|
+
? JSON.parse(snapshotJson)
|
|
823
|
+
: JSON.parse(JSON.stringify(checked.data));
|
|
824
|
+
await this.store.create(record, { command, input: storeInput, context });
|
|
488
825
|
}
|
|
489
826
|
catch (error) {
|
|
490
827
|
this.running.delete(id);
|
|
828
|
+
// The host's own refusal, answered as the inline call's failure.
|
|
829
|
+
if (error instanceof TaskStoreError && error.kind === 'refused' && error.error) {
|
|
830
|
+
return resultContent(failure(error.error), true);
|
|
831
|
+
}
|
|
491
832
|
if (error instanceof TaskStoreError &&
|
|
492
833
|
(error.kind === 'owner-limit' || error.kind === 'total-limit')) {
|
|
493
834
|
return resultContent(failure(taskLimitError()), true);
|
|
@@ -504,12 +845,12 @@ export class TaskRuntime {
|
|
|
504
845
|
const verifiedCredentials = context.credentials && typeof context.credentials === 'object'
|
|
505
846
|
? cloneVerifiedCredentials(context.credentials)
|
|
506
847
|
: undefined;
|
|
507
|
-
|
|
848
|
+
let taskContext = cloneTaskContext(verifiedCredentials ? { ...context, credentials: verifiedCredentials } : context, running.controller.signal, (message) => {
|
|
508
849
|
if (typeof message === 'string') {
|
|
509
850
|
latestProgress = message;
|
|
510
851
|
hasProgress = true;
|
|
511
852
|
}
|
|
512
|
-
});
|
|
853
|
+
}, creatingApprover);
|
|
513
854
|
const takeProgress = () => {
|
|
514
855
|
if (!hasProgress)
|
|
515
856
|
return undefined;
|
|
@@ -520,19 +861,66 @@ export class TaskRuntime {
|
|
|
520
861
|
};
|
|
521
862
|
const tokenDeadlineMs = expiresAtSeconds !== undefined ? expiresAtSeconds * 1000 : undefined;
|
|
522
863
|
const ttlDeadlineMs = record.createdAt + record.ttlMs;
|
|
523
|
-
|
|
864
|
+
const runDeadlineMs = Math.min(Number.MAX_SAFE_INTEGER, record.createdAt + this.options.maxRunMs);
|
|
865
|
+
const job = {
|
|
524
866
|
id,
|
|
525
867
|
owner,
|
|
526
868
|
commandName: command.name,
|
|
869
|
+
confirmPrompt: command.confirmPrompt,
|
|
527
870
|
mutation: command.mutation === true,
|
|
871
|
+
createdAt: record.createdAt,
|
|
872
|
+
expiresAtSeconds,
|
|
528
873
|
input,
|
|
874
|
+
validatedData: checked.data,
|
|
529
875
|
context: taskContext,
|
|
530
876
|
running,
|
|
531
877
|
takeProgress,
|
|
532
878
|
tokenDeadlineMs,
|
|
533
879
|
ttlDeadlineMs,
|
|
880
|
+
runDeadlineMs,
|
|
534
881
|
verifiedCredentials,
|
|
535
|
-
|
|
882
|
+
usedKeys: new Set(),
|
|
883
|
+
needsConfirm,
|
|
884
|
+
confirmValidUntil,
|
|
885
|
+
relayGate,
|
|
886
|
+
handlerStarted: false,
|
|
887
|
+
waitingForInput: false,
|
|
888
|
+
relayPendingWait: false,
|
|
889
|
+
earlyOutcome: undefined,
|
|
890
|
+
};
|
|
891
|
+
if (relayGate) {
|
|
892
|
+
this.inputRunner.rebindRelayGate(relayGate, taskContext, verifiedCredentials);
|
|
893
|
+
}
|
|
894
|
+
// Atomic `handler-started` barrier and input snapshot guard (`spec/tasks.md`): installed
|
|
895
|
+
// only when `allowInput` is enabled so 1.0 custom stores never receive `handler-started`.
|
|
896
|
+
if (this.options.allowInput) {
|
|
897
|
+
const snapshotCanonical = canonicalOrUndefined(inputSnapshot);
|
|
898
|
+
taskContext = withHostState(taskContext, {
|
|
899
|
+
beforeTaskHandler: () => this.inputRunner.markHandlerStarted(job),
|
|
900
|
+
...(snapshotCanonical !== undefined && {
|
|
901
|
+
taskInputSnapshot: { command: command.name, canonical: snapshotCanonical },
|
|
902
|
+
}),
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
if (preApprovedRelay) {
|
|
906
|
+
taskContext = {
|
|
907
|
+
...withoutApprovalRelay(taskContext),
|
|
908
|
+
...preApprovedRelay.extra,
|
|
909
|
+
};
|
|
910
|
+
attachRelayEvidence(taskContext, preApprovedRelay.evidence);
|
|
911
|
+
attachRelayDispatchAdmission(taskContext, preApprovedRelay.admission);
|
|
912
|
+
}
|
|
913
|
+
else if (this.options.allowInput &&
|
|
914
|
+
canElicitForm &&
|
|
915
|
+
!creatingApprover &&
|
|
916
|
+
command.confirmationMode !== 'host-verified') {
|
|
917
|
+
const snapshotCanonical = canonicalOrUndefined(inputSnapshot);
|
|
918
|
+
taskContext = bindApprovalRelay(taskContext, this.inputRunner.createTaskApprovalRelay(job, snapshotCanonical, initialApprovalAnswers));
|
|
919
|
+
}
|
|
920
|
+
// The input validated above, taken by the executor in place of validating it again.
|
|
921
|
+
attachRelayValidatedInput(taskContext, command.name, checked.data);
|
|
922
|
+
job.context = taskContext;
|
|
923
|
+
void this.runTask(job);
|
|
536
924
|
throw new CreateTaskSignal(wireCreateTask(record));
|
|
537
925
|
}
|
|
538
926
|
async runTask(job) {
|
|
@@ -550,21 +938,30 @@ export class TaskRuntime {
|
|
|
550
938
|
}
|
|
551
939
|
}
|
|
552
940
|
const now = this.clock.now();
|
|
941
|
+
const finalTtlMs = finishedTaskTtlFor(this.options, job.createdAt, now, job.expiresAtSeconds);
|
|
553
942
|
let change;
|
|
554
943
|
if (outcome.kind === 'finished') {
|
|
555
|
-
|
|
944
|
+
const errDetails = outcome.result.error?.details;
|
|
945
|
+
const approvalRefusal = this.options.allowInput &&
|
|
946
|
+
!outcome.result.success &&
|
|
947
|
+
(outcome.result.error?.code === ErrorCodes.APPROVAL_REQUIRED ||
|
|
948
|
+
(isRecord(errDetails) && Object.hasOwn(errDetails, 'approvalToken')));
|
|
949
|
+
change = completionChange(outcome.result, this.options.maxResultBytes, now, finalTtlMs, approvalRefusal);
|
|
556
950
|
}
|
|
557
951
|
else if (outcome.kind === 'internal') {
|
|
558
|
-
change = { kind: 'failed', error: internalErrorObject(), at: now };
|
|
952
|
+
change = { kind: 'failed', error: internalErrorObject(), at: now, ttlMs: finalTtlMs };
|
|
559
953
|
}
|
|
560
954
|
else if (outcome.stop === 'cancelled') {
|
|
561
|
-
change = { kind: 'cancelled', at: now };
|
|
955
|
+
change = { kind: 'cancelled', at: now, ttlMs: finalTtlMs };
|
|
562
956
|
}
|
|
563
957
|
else if (outcome.stop === 'token-expired') {
|
|
564
|
-
change = completionChange(failure(tokenExpiredError(outcome.stage, job.mutation)), Number.MAX_SAFE_INTEGER, now);
|
|
958
|
+
change = completionChange(failure(tokenExpiredError(outcome.stage, job.mutation)), Number.MAX_SAFE_INTEGER, now, finalTtlMs);
|
|
959
|
+
}
|
|
960
|
+
else if (outcome.stop === 'run-timeout') {
|
|
961
|
+
change = completionChange(failure(taskRunTimeoutError(outcome.stage, job.mutation)), Number.MAX_SAFE_INTEGER, now, finalTtlMs);
|
|
565
962
|
}
|
|
566
963
|
else if (outcome.stop === 'ttl-ended') {
|
|
567
|
-
await this.store.expire(now).catch(() => { });
|
|
964
|
+
await this.store.expire?.(now).catch(() => { });
|
|
568
965
|
return;
|
|
569
966
|
}
|
|
570
967
|
else {
|
|
@@ -584,24 +981,54 @@ export class TaskRuntime {
|
|
|
584
981
|
}
|
|
585
982
|
}
|
|
586
983
|
async driveTask(job) {
|
|
587
|
-
const initialStop = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now()) ??
|
|
984
|
+
const initialStop = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now(), job.runDeadlineMs) ??
|
|
985
|
+
job.running.reason;
|
|
588
986
|
if (initialStop !== undefined) {
|
|
589
987
|
return { kind: 'stopped', stop: initialStop, stage: 'not-started' };
|
|
590
988
|
}
|
|
591
989
|
let execSettled = false;
|
|
592
|
-
let
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
990
|
+
let execOutcome;
|
|
991
|
+
const execPromise = (async () => {
|
|
992
|
+
try {
|
|
993
|
+
// Server-owned pre-executor gates (`spec/tasks.md`, "Asking"): host relay or
|
|
994
|
+
// confirmation. Run inside `execPromise` so the single watchdog loop supervises
|
|
995
|
+
// hung relay callbacks with heartbeats, cancellation checks, and deadlines.
|
|
996
|
+
if (job.relayGate) {
|
|
997
|
+
const relayed = await this.inputRunner.runRelayGate(job, job.relayGate);
|
|
998
|
+
if (relayed.kind === 'outcome') {
|
|
999
|
+
execOutcome = relayed.outcome;
|
|
1000
|
+
return 'exec';
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
else if (job.needsConfirm) {
|
|
1004
|
+
const confirmed = await this.inputRunner.askConfirmInTask(job);
|
|
1005
|
+
if (confirmed.kind === 'outcome') {
|
|
1006
|
+
execOutcome = confirmed.outcome;
|
|
1007
|
+
return 'exec';
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
const preExecStop = job.running.reason ??
|
|
1011
|
+
dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now(), job.runDeadlineMs);
|
|
1012
|
+
if (preExecStop !== undefined) {
|
|
1013
|
+
job.running.stop(preExecStop);
|
|
1014
|
+
execOutcome = { kind: 'stopped', stop: preExecStop, stage: 'not-started' };
|
|
1015
|
+
return 'exec';
|
|
1016
|
+
}
|
|
1017
|
+
if (!this.options.allowInput) {
|
|
1018
|
+
job.handlerStarted = true;
|
|
1019
|
+
}
|
|
1020
|
+
const result = await this.executeCommand(job.commandName, job.input, job.context);
|
|
1021
|
+
execOutcome = { kind: 'finished', result };
|
|
1022
|
+
return 'exec';
|
|
1023
|
+
}
|
|
1024
|
+
catch {
|
|
1025
|
+
execOutcome = { kind: 'internal' };
|
|
1026
|
+
return 'exec';
|
|
1027
|
+
}
|
|
1028
|
+
finally {
|
|
1029
|
+
execSettled = true;
|
|
1030
|
+
}
|
|
1031
|
+
})();
|
|
605
1032
|
const stoppedPromise = new Promise((resolve) => {
|
|
606
1033
|
if (job.running.controller.signal.aborted) {
|
|
607
1034
|
resolve('stopped');
|
|
@@ -613,61 +1040,85 @@ export class TaskRuntime {
|
|
|
613
1040
|
}
|
|
614
1041
|
});
|
|
615
1042
|
const stopReason = () => job.running.reason;
|
|
1043
|
+
const currentStage = () => (job.handlerStarted ? 'running' : 'not-started');
|
|
616
1044
|
for (;;) {
|
|
1045
|
+
if (job.earlyOutcome)
|
|
1046
|
+
return job.earlyOutcome;
|
|
617
1047
|
if (stopReason() === 'lost') {
|
|
618
|
-
return { kind: 'stopped', stop: 'lost', stage:
|
|
1048
|
+
return { kind: 'stopped', stop: 'lost', stage: currentStage() };
|
|
619
1049
|
}
|
|
620
1050
|
if (execSettled) {
|
|
621
|
-
if (
|
|
1051
|
+
if (job.earlyOutcome)
|
|
1052
|
+
return job.earlyOutcome;
|
|
1053
|
+
if (!execOutcome)
|
|
622
1054
|
return { kind: 'internal' };
|
|
1055
|
+
if (execOutcome.kind !== 'finished')
|
|
1056
|
+
return execOutcome;
|
|
1057
|
+
// If a pre-handler stop (cancelled / token-expired / ttl-ended) prevented the handler
|
|
1058
|
+
// from starting, return that stop reason rather than a synthetic COMMAND_CANCELLED.
|
|
1059
|
+
if (!job.handlerStarted && stopReason() !== undefined) {
|
|
1060
|
+
return { kind: 'stopped', stop: stopReason(), stage: 'not-started' };
|
|
1061
|
+
}
|
|
1062
|
+
// A handler that already returned keeps its result unless the token or TTL expired.
|
|
623
1063
|
const due = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now());
|
|
624
1064
|
return due !== undefined
|
|
625
|
-
? { kind: 'stopped', stop: due, stage: 'finished' }
|
|
626
|
-
:
|
|
1065
|
+
? { kind: 'stopped', stop: due, stage: job.handlerStarted ? 'finished' : 'not-started' }
|
|
1066
|
+
: execOutcome;
|
|
627
1067
|
}
|
|
628
1068
|
const now = this.clock.now();
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
if (message !== undefined) {
|
|
636
|
-
await this.store
|
|
637
|
-
.update(job.id, job.owner, { kind: 'progress', message, at: now })
|
|
638
|
-
.catch(() => { });
|
|
639
|
-
}
|
|
640
|
-
if (this.store.heartbeat) {
|
|
641
|
-
await this.store.heartbeat(job.id, job.owner, now).catch(() => { });
|
|
1069
|
+
// While an active question owns `waitingForInput`, it enforces question expiry
|
|
1070
|
+
// (`unanswered`), token expiry, TTL, heartbeats and cancellation directly.
|
|
1071
|
+
if (!job.waitingForInput) {
|
|
1072
|
+
const due = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, now, job.runDeadlineMs);
|
|
1073
|
+
if (due !== undefined) {
|
|
1074
|
+
job.running.stop(due);
|
|
642
1075
|
}
|
|
643
|
-
|
|
644
|
-
const
|
|
645
|
-
if (
|
|
646
|
-
|
|
1076
|
+
if (stopReason() === undefined) {
|
|
1077
|
+
const message = job.takeProgress();
|
|
1078
|
+
if (message !== undefined) {
|
|
1079
|
+
await this.store
|
|
1080
|
+
.update(job.id, job.owner, { kind: 'progress', message, at: now })
|
|
1081
|
+
.catch(() => { });
|
|
647
1082
|
}
|
|
648
|
-
|
|
649
|
-
job.
|
|
1083
|
+
if (this.store.heartbeat) {
|
|
1084
|
+
await this.store.heartbeat(job.id, job.owner, now).catch(() => { });
|
|
650
1085
|
}
|
|
651
|
-
|
|
652
|
-
job.
|
|
1086
|
+
try {
|
|
1087
|
+
const current = await this.store.get(job.id, job.owner);
|
|
1088
|
+
if (!current || isTaskExpired(current, now)) {
|
|
1089
|
+
job.running.stop('ttl-ended');
|
|
1090
|
+
}
|
|
1091
|
+
else if (isTerminalTaskStatus(current.status)) {
|
|
1092
|
+
job.running.stop('lost');
|
|
1093
|
+
}
|
|
1094
|
+
else if (current.cancelRequested) {
|
|
1095
|
+
job.running.stop('cancelled');
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
// Transient store read failure: try again on the next check.
|
|
653
1100
|
}
|
|
654
|
-
}
|
|
655
|
-
catch {
|
|
656
|
-
// Transient store read failure: try again on the next check.
|
|
657
1101
|
}
|
|
658
1102
|
}
|
|
659
1103
|
const reason = stopReason();
|
|
660
1104
|
if (reason === 'lost' || reason === 'ttl-ended') {
|
|
661
|
-
return { kind: 'stopped', stop: reason, stage:
|
|
1105
|
+
return { kind: 'stopped', stop: reason, stage: currentStage() };
|
|
662
1106
|
}
|
|
663
1107
|
if (execSettled)
|
|
664
1108
|
continue;
|
|
665
1109
|
if (reason !== undefined) {
|
|
666
|
-
|
|
1110
|
+
if (reason === 'run-timeout' && job.relayPendingWait && !job.handlerStarted) {
|
|
1111
|
+
return {
|
|
1112
|
+
kind: 'finished',
|
|
1113
|
+
result: failure(confirmUnansweredError(job.commandName)),
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
return { kind: 'stopped', stop: reason, stage: currentStage() };
|
|
667
1117
|
}
|
|
1118
|
+
const hardDeadline = Math.min(job.ttlDeadlineMs, job.runDeadlineMs);
|
|
668
1119
|
const nearest = job.tokenDeadlineMs !== undefined
|
|
669
|
-
? Math.min(job.tokenDeadlineMs,
|
|
670
|
-
:
|
|
1120
|
+
? Math.min(job.tokenDeadlineMs, hardDeadline)
|
|
1121
|
+
: hardDeadline;
|
|
671
1122
|
const until = Math.max(1, nearest - now);
|
|
672
1123
|
const waitMs = Math.min(this.options.checkIntervalMs, until, MAX_TIMEOUT_MS);
|
|
673
1124
|
let timer;
|