@lushly-dev/afd-server 3.0.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 +36 -10
- package/dist/approval-crypto.d.ts +1 -1
- package/dist/approval-crypto.d.ts.map +1 -1
- package/dist/approval-crypto.js +2 -2
- package/dist/approval-crypto.js.map +1 -1
- package/dist/approval-process-state.d.ts +2 -0
- package/dist/approval-process-state.d.ts.map +1 -1
- package/dist/approval-process-state.js +1 -0
- package/dist/approval-process-state.js.map +1 -1
- package/dist/approval-relay.d.ts +18 -2
- package/dist/approval-relay.d.ts.map +1 -1
- package/dist/approval-relay.js.map +1 -1
- package/dist/approval-up-front.js +14 -9
- package/dist/approval-up-front.js.map +1 -1
- package/dist/approval.d.ts +7 -3
- package/dist/approval.d.ts.map +1 -1
- package/dist/approval.js +55 -28
- package/dist/approval.js.map +1 -1
- package/dist/confirmation-gate.d.ts.map +1 -1
- package/dist/confirmation-gate.js +18 -14
- package/dist/confirmation-gate.js.map +1 -1
- package/dist/confirmations.d.ts +18 -0
- package/dist/confirmations.d.ts.map +1 -1
- package/dist/confirmations.js.map +1 -1
- package/dist/direct-registry.d.ts +2 -2
- package/dist/direct-registry.js +3 -3
- 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 +7 -2
- package/dist/direct-tool-surface.js.map +1 -1
- package/dist/execution.d.ts +1 -1
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +1 -1
- 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 +15 -0
- package/dist/host-state.d.ts.map +1 -1
- package/dist/host-state.js.map +1 -1
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +13 -3
- package/dist/http-handler.js.map +1 -1
- package/dist/human-relay.d.ts.map +1 -1
- package/dist/human-relay.js +27 -0
- package/dist/human-relay.js.map +1 -1
- package/dist/idempotency-step.d.ts +15 -3
- package/dist/idempotency-step.d.ts.map +1 -1
- package/dist/idempotency-step.js +37 -7
- package/dist/idempotency-step.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.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 +1 -1
- package/dist/mcp-auth-view.d.ts.map +1 -1
- package/dist/mcp-auth-view.js +27 -3
- package/dist/mcp-auth-view.js.map +1 -1
- package/dist/mcp-auth.d.ts +10 -2
- package/dist/mcp-auth.d.ts.map +1 -1
- package/dist/mcp-auth.js +12 -3
- package/dist/mcp-auth.js.map +1 -1
- package/dist/mcp-modern.d.ts.map +1 -1
- package/dist/mcp-modern.js +10 -2
- package/dist/mcp-modern.js.map +1 -1
- package/dist/middleware.d.ts +2 -2
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +11 -2
- package/dist/middleware.js.map +1 -1
- 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/scope-view.d.ts +7 -0
- package/dist/scope-view.d.ts.map +1 -1
- package/dist/scope-view.js.map +1 -1
- package/dist/server-types.d.ts +11 -6
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +98 -28
- package/dist/server.js.map +1 -1
- package/dist/task-dispatch.d.ts +6 -1
- package/dist/task-dispatch.d.ts.map +1 -1
- 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 +29 -4
- package/dist/tasks-runtime.d.ts.map +1 -1
- package/dist/tasks-runtime.js +455 -77
- package/dist/tasks-runtime.js.map +1 -1
- package/dist/tasks.d.ts +162 -18
- package/dist/tasks.d.ts.map +1 -1
- package/dist/tasks.js +146 -16
- package/dist/tasks.js.map +1 -1
- package/dist/tool-router.d.ts +0 -2
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +58 -54
- package/dist/tool-router.js.map +1 -1
- package/package.json +7 -7
package/dist/tasks-runtime.js
CHANGED
|
@@ -7,13 +7,21 @@ 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';
|
|
11
16
|
import { withHostState } from './host-state.js';
|
|
12
17
|
import { JsonRpcError } from './json-rpc.js';
|
|
13
18
|
import { bindOutputBudgetAsk, OUTPUT_BUDGET_ASK } from './output-budget.js';
|
|
14
19
|
import { principalBinding } from './principal-binding.js';
|
|
20
|
+
import { attachRelayDispatchAdmission, attachRelayEvidence, attachRelayValidatedInput, } from './relay-evidence.js';
|
|
15
21
|
import { bindScopeView, scopeViewOf } from './scope-view.js';
|
|
16
|
-
import { finishedTaskTtlFor, 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';
|
|
17
25
|
import { resultContent } from './tool-router.js';
|
|
18
26
|
import { cloneVerifiedCredentials, unbrandVerifiedCredentials } from './verified-credentials.js';
|
|
19
27
|
/**
|
|
@@ -109,7 +117,10 @@ function wireDetailedTask(record) {
|
|
|
109
117
|
ttlMs: record.ttlMs,
|
|
110
118
|
pollIntervalMs: record.pollIntervalMs,
|
|
111
119
|
};
|
|
112
|
-
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') {
|
|
113
124
|
base.result = record.result ?? { content: [], isError: false };
|
|
114
125
|
}
|
|
115
126
|
else if (record.status === 'failed') {
|
|
@@ -195,8 +206,12 @@ function unidentifiedCallersError(command) {
|
|
|
195
206
|
recovery: { kind: 'external' },
|
|
196
207
|
};
|
|
197
208
|
}
|
|
209
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
210
|
+
// RUNNER STATE & DEADLINE HELPERS
|
|
211
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
198
212
|
function createRunningTask() {
|
|
199
213
|
const controller = new AbortController();
|
|
214
|
+
const inputListeners = new Set();
|
|
200
215
|
const running = {
|
|
201
216
|
controller,
|
|
202
217
|
reason: undefined,
|
|
@@ -207,6 +222,18 @@ function createRunningTask() {
|
|
|
207
222
|
if (!controller.signal.aborted) {
|
|
208
223
|
controller.abort();
|
|
209
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
|
+
};
|
|
210
237
|
},
|
|
211
238
|
};
|
|
212
239
|
return running;
|
|
@@ -271,7 +298,7 @@ export function tokenExpiredError(stage, mutation) {
|
|
|
271
298
|
recovery: { kind: 'external' },
|
|
272
299
|
};
|
|
273
300
|
}
|
|
274
|
-
function completionChange(result, maxResultBytes, at, ttlMs) {
|
|
301
|
+
function completionChange(result, maxResultBytes, at, ttlMs, approvalRefusal = false) {
|
|
275
302
|
// A result JSON cannot hold (a BigInt, a cycle) throws in resultContent too: the task fails
|
|
276
303
|
// with an internal error instead of staying `working`.
|
|
277
304
|
let toolResult;
|
|
@@ -285,7 +312,13 @@ function completionChange(result, maxResultBytes, at, ttlMs) {
|
|
|
285
312
|
}
|
|
286
313
|
const size = utf8.encode(serialized).byteLength;
|
|
287
314
|
if (size <= maxResultBytes) {
|
|
288
|
-
return {
|
|
315
|
+
return {
|
|
316
|
+
kind: 'completed',
|
|
317
|
+
result: toolResult,
|
|
318
|
+
at,
|
|
319
|
+
ttlMs,
|
|
320
|
+
...(approvalRefusal && { approvalRefusal: true }),
|
|
321
|
+
};
|
|
289
322
|
}
|
|
290
323
|
const tooLarge = {
|
|
291
324
|
code: ErrorCodes.INTERNAL_ERROR,
|
|
@@ -296,8 +329,8 @@ function completionChange(result, maxResultBytes, at, ttlMs) {
|
|
|
296
329
|
};
|
|
297
330
|
return { kind: 'completed', result: resultContent(failure(tooLarge), true), at, ttlMs };
|
|
298
331
|
}
|
|
299
|
-
/** Copy string-keyed properties and only the safe symbols (`scopeView`, `contextState`). */
|
|
300
|
-
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) {
|
|
301
334
|
const copy = {};
|
|
302
335
|
for (const key of Object.keys(context)) {
|
|
303
336
|
copy[key] = context[key];
|
|
@@ -324,6 +357,9 @@ function cloneTaskContext(context, signal, reportProgress) {
|
|
|
324
357
|
if (Object.hasOwn(context, OUTPUT_BUDGET_ASK)) {
|
|
325
358
|
taskContext = bindOutputBudgetAsk(taskContext, context[OUTPUT_BUDGET_ASK]);
|
|
326
359
|
}
|
|
360
|
+
if (approver) {
|
|
361
|
+
taskContext = bindApprover(taskContext, approver);
|
|
362
|
+
}
|
|
327
363
|
// The idempotency step never acts on a task run, and the retry middleware counts it as carrying
|
|
328
364
|
// no key (spec/idempotency.md, S11).
|
|
329
365
|
return withHostState(taskContext, { taskRun: true });
|
|
@@ -341,18 +377,48 @@ export class TaskRuntime {
|
|
|
341
377
|
hasAuth;
|
|
342
378
|
hasContextHook;
|
|
343
379
|
actor;
|
|
380
|
+
confirmations;
|
|
381
|
+
approver;
|
|
382
|
+
commandNames;
|
|
383
|
+
humanRelayGate;
|
|
384
|
+
listedApprovalCommands;
|
|
344
385
|
executeCommand;
|
|
386
|
+
validateCommand;
|
|
387
|
+
inputRunner;
|
|
345
388
|
running = new Map();
|
|
346
389
|
constructor(deps) {
|
|
347
390
|
this.store = deps.store ?? new InMemoryTaskStore();
|
|
348
|
-
this.options = resolveTaskOptions(deps.options);
|
|
391
|
+
this.options = resolveTaskOptions(deps.options, deps.store);
|
|
349
392
|
this.clock = deps.clock ?? systemClock;
|
|
350
393
|
this.hasAuth = deps.hasAuth;
|
|
351
394
|
this.hasContextHook = deps.hasContextHook;
|
|
352
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();
|
|
353
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
|
+
});
|
|
354
414
|
this.servesTasks = deps.commands.some((cmd) => cmd.task === 'optional' || cmd.task === 'required');
|
|
355
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
|
+
}
|
|
356
422
|
get hookIdentifiesCallers() {
|
|
357
423
|
return this.options.callersIdentifiedByHook && this.hasContextHook;
|
|
358
424
|
}
|
|
@@ -371,7 +437,7 @@ export class TaskRuntime {
|
|
|
371
437
|
/** Build the {@link TaskDispatch} for one modern/stdio `tools/call`. */
|
|
372
438
|
dispatchFor(era, isHttp, ctx, credentials) {
|
|
373
439
|
return {
|
|
374
|
-
dispatch: async (command, input, context) => {
|
|
440
|
+
dispatch: async (command, input, context, meta) => {
|
|
375
441
|
if (command.task !== 'optional' && command.task !== 'required')
|
|
376
442
|
return undefined;
|
|
377
443
|
if (!this.identifiesCaller(isHttp, credentials)) {
|
|
@@ -385,7 +451,7 @@ export class TaskRuntime {
|
|
|
385
451
|
throw missingTasksCapability();
|
|
386
452
|
return undefined;
|
|
387
453
|
}
|
|
388
|
-
return this.startTask(command, input, context);
|
|
454
|
+
return this.startTask(command, input, context, meta);
|
|
389
455
|
},
|
|
390
456
|
refuseComposite: compositeTaskError,
|
|
391
457
|
};
|
|
@@ -415,6 +481,14 @@ export class TaskRuntime {
|
|
|
415
481
|
installHandlers(server, opts) {
|
|
416
482
|
if (!this.declaresTasksTo(opts.isHttp))
|
|
417
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
|
+
};
|
|
418
492
|
const resolveCaller = async (ctx) => {
|
|
419
493
|
if (!requestDeclaresTasks(opts.era, ctx)) {
|
|
420
494
|
throw missingTasksCapability();
|
|
@@ -422,12 +496,7 @@ export class TaskRuntime {
|
|
|
422
496
|
const view = opts.requestView?.();
|
|
423
497
|
const reqDecision = view?.decideRequest();
|
|
424
498
|
if (view && reqDecision && reqDecision !== 'proceed') {
|
|
425
|
-
|
|
426
|
-
throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
|
|
427
|
-
code: error.code,
|
|
428
|
-
suggestion: error.suggestion,
|
|
429
|
-
scopes: reqDecision.forbidden,
|
|
430
|
-
});
|
|
499
|
+
throwInsufficientScope(view, reqDecision.forbidden);
|
|
431
500
|
}
|
|
432
501
|
let values;
|
|
433
502
|
try {
|
|
@@ -448,8 +517,8 @@ export class TaskRuntime {
|
|
|
448
517
|
catch {
|
|
449
518
|
throw internalRpcError();
|
|
450
519
|
}
|
|
451
|
-
// The context the caller's request runs with, which the store's `getFor`
|
|
452
|
-
const context = { ...values, actor, credentials };
|
|
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' };
|
|
453
522
|
return { owner, view, context };
|
|
454
523
|
};
|
|
455
524
|
const findTask = async (caller, taskId, needsCommand) => {
|
|
@@ -468,7 +537,8 @@ export class TaskRuntime {
|
|
|
468
537
|
if (!record ||
|
|
469
538
|
record.id !== taskId ||
|
|
470
539
|
!taskOwnerMatches(record.owner, caller.owner) ||
|
|
471
|
-
isTaskExpired(record, now)
|
|
540
|
+
isTaskExpired(record, now) ||
|
|
541
|
+
!this.commandNames.has(record.command)) {
|
|
472
542
|
throw taskNotFound();
|
|
473
543
|
}
|
|
474
544
|
if (caller.view && !caller.view.known(record.command)) {
|
|
@@ -477,24 +547,96 @@ export class TaskRuntime {
|
|
|
477
547
|
if (needsCommand && caller.view) {
|
|
478
548
|
const decision = caller.view.decideTask(record.command);
|
|
479
549
|
if (decision !== 'proceed') {
|
|
480
|
-
|
|
481
|
-
throw new ProtocolError(ProtocolErrorCode.InvalidRequest, error.message, {
|
|
482
|
-
code: error.code,
|
|
483
|
-
suggestion: error.suggestion,
|
|
484
|
-
scopes: decision.forbidden,
|
|
485
|
-
});
|
|
550
|
+
throwInsufficientScope(caller.view, decision.forbidden);
|
|
486
551
|
}
|
|
487
552
|
}
|
|
488
553
|
return record;
|
|
489
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
|
+
};
|
|
490
563
|
server.setRequestHandler('tasks/get', { params: taskIdParamsSchema }, async (params, ctx) => {
|
|
491
564
|
const caller = await resolveCaller(ctx);
|
|
492
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
|
+
}
|
|
493
595
|
return wireDetailedTask(record);
|
|
494
596
|
});
|
|
495
597
|
server.setRequestHandler('tasks/update', { params: updateTaskParamsSchema }, async (params, ctx) => {
|
|
496
598
|
const caller = await resolveCaller(ctx);
|
|
497
|
-
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
|
+
}
|
|
498
640
|
return {};
|
|
499
641
|
});
|
|
500
642
|
server.setRequestHandler('tasks/cancel', { params: taskIdParamsSchema }, async (params, ctx) => {
|
|
@@ -514,9 +656,33 @@ export class TaskRuntime {
|
|
|
514
656
|
return {};
|
|
515
657
|
});
|
|
516
658
|
}
|
|
517
|
-
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`).
|
|
518
664
|
const actor = (context.actor ?? this.actor);
|
|
519
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);
|
|
520
686
|
let owner;
|
|
521
687
|
try {
|
|
522
688
|
owner = principalBinding(actor, credentials);
|
|
@@ -524,11 +690,107 @@ export class TaskRuntime {
|
|
|
524
690
|
catch {
|
|
525
691
|
throw internalRpcError();
|
|
526
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
|
+
}
|
|
527
788
|
const id = newTaskId();
|
|
528
789
|
const now = this.clock.now();
|
|
529
|
-
await this.store.expire(now).catch(() => { });
|
|
790
|
+
await this.store.expire?.(now).catch(() => { });
|
|
530
791
|
const expiresAtSeconds = typeof credentials?.expiresAt === 'number' ? credentials.expiresAt : undefined;
|
|
531
792
|
const ttlMs = taskTtlFor(this.options, now, expiresAtSeconds);
|
|
793
|
+
const gatedCommand = this.isGatedTaskCommand(command);
|
|
532
794
|
const record = {
|
|
533
795
|
id,
|
|
534
796
|
owner,
|
|
@@ -539,6 +801,12 @@ export class TaskRuntime {
|
|
|
539
801
|
ttlMs,
|
|
540
802
|
pollIntervalMs: this.options.pollIntervalMs,
|
|
541
803
|
cancelRequested: false,
|
|
804
|
+
...(this.options.allowInput && { handlerStarted: false }),
|
|
805
|
+
...(this.options.allowInput &&
|
|
806
|
+
gatedCommand &&
|
|
807
|
+
snapshotJson !== undefined && {
|
|
808
|
+
inputSnapshot: JSON.parse(snapshotJson),
|
|
809
|
+
}),
|
|
542
810
|
};
|
|
543
811
|
if (this.running.size >= this.options.maxRunning) {
|
|
544
812
|
return resultContent(failure(taskLimitError()), true);
|
|
@@ -546,10 +814,21 @@ export class TaskRuntime {
|
|
|
546
814
|
const running = createRunningTask();
|
|
547
815
|
this.running.set(id, running);
|
|
548
816
|
try {
|
|
549
|
-
|
|
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 });
|
|
550
825
|
}
|
|
551
826
|
catch (error) {
|
|
552
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
|
+
}
|
|
553
832
|
if (error instanceof TaskStoreError &&
|
|
554
833
|
(error.kind === 'owner-limit' || error.kind === 'total-limit')) {
|
|
555
834
|
return resultContent(failure(taskLimitError()), true);
|
|
@@ -566,12 +845,12 @@ export class TaskRuntime {
|
|
|
566
845
|
const verifiedCredentials = context.credentials && typeof context.credentials === 'object'
|
|
567
846
|
? cloneVerifiedCredentials(context.credentials)
|
|
568
847
|
: undefined;
|
|
569
|
-
|
|
848
|
+
let taskContext = cloneTaskContext(verifiedCredentials ? { ...context, credentials: verifiedCredentials } : context, running.controller.signal, (message) => {
|
|
570
849
|
if (typeof message === 'string') {
|
|
571
850
|
latestProgress = message;
|
|
572
851
|
hasProgress = true;
|
|
573
852
|
}
|
|
574
|
-
});
|
|
853
|
+
}, creatingApprover);
|
|
575
854
|
const takeProgress = () => {
|
|
576
855
|
if (!hasProgress)
|
|
577
856
|
return undefined;
|
|
@@ -583,14 +862,16 @@ export class TaskRuntime {
|
|
|
583
862
|
const tokenDeadlineMs = expiresAtSeconds !== undefined ? expiresAtSeconds * 1000 : undefined;
|
|
584
863
|
const ttlDeadlineMs = record.createdAt + record.ttlMs;
|
|
585
864
|
const runDeadlineMs = Math.min(Number.MAX_SAFE_INTEGER, record.createdAt + this.options.maxRunMs);
|
|
586
|
-
|
|
865
|
+
const job = {
|
|
587
866
|
id,
|
|
588
867
|
owner,
|
|
589
868
|
commandName: command.name,
|
|
869
|
+
confirmPrompt: command.confirmPrompt,
|
|
590
870
|
mutation: command.mutation === true,
|
|
591
871
|
createdAt: record.createdAt,
|
|
592
872
|
expiresAtSeconds,
|
|
593
873
|
input,
|
|
874
|
+
validatedData: checked.data,
|
|
594
875
|
context: taskContext,
|
|
595
876
|
running,
|
|
596
877
|
takeProgress,
|
|
@@ -598,7 +879,48 @@ export class TaskRuntime {
|
|
|
598
879
|
ttlDeadlineMs,
|
|
599
880
|
runDeadlineMs,
|
|
600
881
|
verifiedCredentials,
|
|
601
|
-
|
|
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);
|
|
602
924
|
throw new CreateTaskSignal(wireCreateTask(record));
|
|
603
925
|
}
|
|
604
926
|
async runTask(job) {
|
|
@@ -619,7 +941,12 @@ export class TaskRuntime {
|
|
|
619
941
|
const finalTtlMs = finishedTaskTtlFor(this.options, job.createdAt, now, job.expiresAtSeconds);
|
|
620
942
|
let change;
|
|
621
943
|
if (outcome.kind === 'finished') {
|
|
622
|
-
|
|
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);
|
|
623
950
|
}
|
|
624
951
|
else if (outcome.kind === 'internal') {
|
|
625
952
|
change = { kind: 'failed', error: internalErrorObject(), at: now, ttlMs: finalTtlMs };
|
|
@@ -634,7 +961,7 @@ export class TaskRuntime {
|
|
|
634
961
|
change = completionChange(failure(taskRunTimeoutError(outcome.stage, job.mutation)), Number.MAX_SAFE_INTEGER, now, finalTtlMs);
|
|
635
962
|
}
|
|
636
963
|
else if (outcome.stop === 'ttl-ended') {
|
|
637
|
-
await this.store.expire(now).catch(() => { });
|
|
964
|
+
await this.store.expire?.(now).catch(() => { });
|
|
638
965
|
return;
|
|
639
966
|
}
|
|
640
967
|
else {
|
|
@@ -660,19 +987,48 @@ export class TaskRuntime {
|
|
|
660
987
|
return { kind: 'stopped', stop: initialStop, stage: 'not-started' };
|
|
661
988
|
}
|
|
662
989
|
let execSettled = false;
|
|
663
|
-
let
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
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
|
+
})();
|
|
676
1032
|
const stoppedPromise = new Promise((resolve) => {
|
|
677
1033
|
if (job.running.controller.signal.aborted) {
|
|
678
1034
|
resolve('stopped');
|
|
@@ -684,58 +1040,80 @@ export class TaskRuntime {
|
|
|
684
1040
|
}
|
|
685
1041
|
});
|
|
686
1042
|
const stopReason = () => job.running.reason;
|
|
1043
|
+
const currentStage = () => (job.handlerStarted ? 'running' : 'not-started');
|
|
687
1044
|
for (;;) {
|
|
1045
|
+
if (job.earlyOutcome)
|
|
1046
|
+
return job.earlyOutcome;
|
|
688
1047
|
if (stopReason() === 'lost') {
|
|
689
|
-
return { kind: 'stopped', stop: 'lost', stage:
|
|
1048
|
+
return { kind: 'stopped', stop: 'lost', stage: currentStage() };
|
|
690
1049
|
}
|
|
691
1050
|
if (execSettled) {
|
|
692
|
-
if (
|
|
1051
|
+
if (job.earlyOutcome)
|
|
1052
|
+
return job.earlyOutcome;
|
|
1053
|
+
if (!execOutcome)
|
|
693
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
|
+
}
|
|
694
1062
|
// A handler that already returned keeps its result unless the token or TTL expired.
|
|
695
1063
|
const due = dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now());
|
|
696
1064
|
return due !== undefined
|
|
697
|
-
? { kind: 'stopped', stop: due, stage: 'finished' }
|
|
698
|
-
:
|
|
1065
|
+
? { kind: 'stopped', stop: due, stage: job.handlerStarted ? 'finished' : 'not-started' }
|
|
1066
|
+
: execOutcome;
|
|
699
1067
|
}
|
|
700
1068
|
const now = this.clock.now();
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
if (message !== undefined) {
|
|
708
|
-
await this.store
|
|
709
|
-
.update(job.id, job.owner, { kind: 'progress', message, at: now })
|
|
710
|
-
.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);
|
|
711
1075
|
}
|
|
712
|
-
if (
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
job.running.stop('ttl-ended');
|
|
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(() => { });
|
|
719
1082
|
}
|
|
720
|
-
|
|
721
|
-
job.
|
|
1083
|
+
if (this.store.heartbeat) {
|
|
1084
|
+
await this.store.heartbeat(job.id, job.owner, now).catch(() => { });
|
|
722
1085
|
}
|
|
723
|
-
|
|
724
|
-
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.
|
|
725
1100
|
}
|
|
726
|
-
}
|
|
727
|
-
catch {
|
|
728
|
-
// Transient store read failure: try again on the next check.
|
|
729
1101
|
}
|
|
730
1102
|
}
|
|
731
1103
|
const reason = stopReason();
|
|
732
1104
|
if (reason === 'lost' || reason === 'ttl-ended') {
|
|
733
|
-
return { kind: 'stopped', stop: reason, stage:
|
|
1105
|
+
return { kind: 'stopped', stop: reason, stage: currentStage() };
|
|
734
1106
|
}
|
|
735
1107
|
if (execSettled)
|
|
736
1108
|
continue;
|
|
737
1109
|
if (reason !== undefined) {
|
|
738
|
-
|
|
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() };
|
|
739
1117
|
}
|
|
740
1118
|
const hardDeadline = Math.min(job.ttlDeadlineMs, job.runDeadlineMs);
|
|
741
1119
|
const nearest = job.tokenDeadlineMs !== undefined
|