mcp-rubber-duck 1.20.0 → 1.20.1
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/CHANGELOG.md +8 -0
- package/audit-ci.json +1 -6
- package/dist/services/retention-task-store.d.ts +69 -0
- package/dist/services/retention-task-store.d.ts.map +1 -0
- package/dist/services/retention-task-store.js +192 -0
- package/dist/services/retention-task-store.js.map +1 -0
- package/dist/services/task-manager.d.ts +7 -1
- package/dist/services/task-manager.d.ts.map +1 -1
- package/dist/services/task-manager.js +22 -7
- package/dist/services/task-manager.js.map +1 -1
- package/package.json +3 -2
- package/src/services/retention-task-store.ts +248 -0
- package/src/services/task-manager.ts +23 -10
- package/tests/services/retention-task-store.test.ts +180 -0
- package/tests/services/task-manager.test.ts +100 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
## [1.20.1](https://github.com/nesquikm/mcp-rubber-duck/compare/v1.20.0...v1.20.1) (2026-07-21)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Bug Fixes
|
|
5
|
+
|
|
6
|
+
* **deps:** clear audit-ci CVEs (tar, brace-expansion, js-yaml, body-parser) ([9b12879](https://github.com/nesquikm/mcp-rubber-duck/commit/9b1287949cb981d819ec34597d142397c87d712e))
|
|
7
|
+
* **tasks:** stop evicting running debate/iterate tasks at TTL ([0c0ea93](https://github.com/nesquikm/mcp-rubber-duck/commit/0c0ea93688350e5ee6f26247e5b3c4abb7fad8e4)), closes [#127](https://github.com/nesquikm/mcp-rubber-duck/issues/127)
|
|
8
|
+
|
|
1
9
|
# [1.20.0](https://github.com/nesquikm/mcp-rubber-duck/compare/v1.19.12...v1.20.0) (2026-07-14)
|
|
2
10
|
|
|
3
11
|
|
package/audit-ci.json
CHANGED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `TaskStore` implementation with post-terminal retention semantics.
|
|
3
|
+
*
|
|
4
|
+
* Unlike the SDK's `InMemoryTaskStore` — which arms a deletion timer at task
|
|
5
|
+
* creation and evicts the record after `ttl` regardless of status — this store
|
|
6
|
+
* treats `ttl` as a *retention window that starts when the task reaches a
|
|
7
|
+
* terminal state*. Consequences:
|
|
8
|
+
*
|
|
9
|
+
* - A non-terminal task (`submitted`/`working`) is immortal: it has no
|
|
10
|
+
* `expiresAt` and is never evicted, no matter how much time elapses.
|
|
11
|
+
* - Once a task reaches a terminal state (`completed`/`failed`/`cancelled`),
|
|
12
|
+
* its retention window opens (`expiresAt = now + ttl`). It stays retrievable
|
|
13
|
+
* until the window elapses, then is evicted lazily on read or by the periodic
|
|
14
|
+
* `sweepExpired()` sweep.
|
|
15
|
+
*
|
|
16
|
+
* Method contracts and error-message strings mirror `InMemoryTaskStore` so the
|
|
17
|
+
* only behavioral difference is timer semantics.
|
|
18
|
+
*
|
|
19
|
+
* WARNING: builds on the experimental `@modelcontextprotocol/sdk/experimental`
|
|
20
|
+
* Tasks API, which may change without notice.
|
|
21
|
+
*/
|
|
22
|
+
import type { TaskStore, CreateTaskOptions } from '@modelcontextprotocol/sdk/experimental';
|
|
23
|
+
import type { Task, RequestId, Request, Result } from '@modelcontextprotocol/sdk/types.js';
|
|
24
|
+
export declare class RetentionTaskStore implements TaskStore {
|
|
25
|
+
private readonly defaultTtl;
|
|
26
|
+
private tasks;
|
|
27
|
+
/**
|
|
28
|
+
* @param defaultTtl Retention window (ms) applied when a task is created
|
|
29
|
+
* without an explicit `ttl`. `null` means unlimited (no eviction).
|
|
30
|
+
*/
|
|
31
|
+
constructor(defaultTtl?: number | null);
|
|
32
|
+
/**
|
|
33
|
+
* Generates a unique task ID (16 random bytes as 32 hex chars), matching
|
|
34
|
+
* `InMemoryTaskStore`.
|
|
35
|
+
*/
|
|
36
|
+
private generateTaskId;
|
|
37
|
+
/** True when a stored task's retention window has elapsed. */
|
|
38
|
+
private isExpired;
|
|
39
|
+
/**
|
|
40
|
+
* Evict a task and log a distinct eviction message (never a failure). Logged
|
|
41
|
+
* at `info` so a post-retention `-32602` remains diagnosable under the default
|
|
42
|
+
* `LOG_LEVEL=info` — this is a benign, expected event, not an error.
|
|
43
|
+
*/
|
|
44
|
+
private evict;
|
|
45
|
+
/**
|
|
46
|
+
* Look up a live (non-expired) stored task, lazily evicting it if its
|
|
47
|
+
* retention window has elapsed.
|
|
48
|
+
*/
|
|
49
|
+
private getLive;
|
|
50
|
+
createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, _sessionId?: string): Promise<Task>;
|
|
51
|
+
getTask(taskId: string, _sessionId?: string): Promise<Task | null>;
|
|
52
|
+
storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, _sessionId?: string): Promise<void>;
|
|
53
|
+
getTaskResult(taskId: string, _sessionId?: string): Promise<Result>;
|
|
54
|
+
updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, _sessionId?: string): Promise<void>;
|
|
55
|
+
listTasks(cursor?: string, _sessionId?: string): Promise<{
|
|
56
|
+
tasks: Task[];
|
|
57
|
+
nextCursor?: string;
|
|
58
|
+
}>;
|
|
59
|
+
/**
|
|
60
|
+
* Evict every terminal task whose retention window has elapsed. Non-terminal
|
|
61
|
+
* (immortal) tasks are always spared. Returns the number of tasks dropped.
|
|
62
|
+
*/
|
|
63
|
+
sweepExpired(): number;
|
|
64
|
+
/** Clear all stored tasks (useful for testing or graceful shutdown). */
|
|
65
|
+
cleanup(): void;
|
|
66
|
+
/** Open a terminal task's retention window from now, if a ttl is configured. */
|
|
67
|
+
private openRetentionWindow;
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=retention-task-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retention-task-store.d.ts","sourceRoot":"","sources":["../../src/services/retention-task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAUH,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AA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,EAAE,MAAM,CAAA;KAAE,CAAC;IAyBlD;;;OAGG;IACH,YAAY,IAAI,MAAM;IAWtB,wEAAwE;IACxE,OAAO,IAAI,IAAI;IAIf,gFAAgF;IAChF,OAAO,CAAC,mBAAmB;CAK5B"}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `TaskStore` implementation with post-terminal retention semantics.
|
|
3
|
+
*
|
|
4
|
+
* Unlike the SDK's `InMemoryTaskStore` — which arms a deletion timer at task
|
|
5
|
+
* creation and evicts the record after `ttl` regardless of status — this store
|
|
6
|
+
* treats `ttl` as a *retention window that starts when the task reaches a
|
|
7
|
+
* terminal state*. Consequences:
|
|
8
|
+
*
|
|
9
|
+
* - A non-terminal task (`submitted`/`working`) is immortal: it has no
|
|
10
|
+
* `expiresAt` and is never evicted, no matter how much time elapses.
|
|
11
|
+
* - Once a task reaches a terminal state (`completed`/`failed`/`cancelled`),
|
|
12
|
+
* its retention window opens (`expiresAt = now + ttl`). It stays retrievable
|
|
13
|
+
* until the window elapses, then is evicted lazily on read or by the periodic
|
|
14
|
+
* `sweepExpired()` sweep.
|
|
15
|
+
*
|
|
16
|
+
* Method contracts and error-message strings mirror `InMemoryTaskStore` so the
|
|
17
|
+
* only behavioral difference is timer semantics.
|
|
18
|
+
*
|
|
19
|
+
* WARNING: builds on the experimental `@modelcontextprotocol/sdk/experimental`
|
|
20
|
+
* Tasks API, which may change without notice.
|
|
21
|
+
*/
|
|
22
|
+
/* eslint-disable @typescript-eslint/require-await --
|
|
23
|
+
* The `TaskStore` interface requires every method to return a Promise. This
|
|
24
|
+
* store is backed by a synchronous in-memory Map, but its methods stay `async`
|
|
25
|
+
* to match the interface and the SDK's `InMemoryTaskStore`. Keeping them async
|
|
26
|
+
* (rather than returning `Promise.resolve`) ensures a guard-clause `throw`
|
|
27
|
+
* surfaces as a rejected promise instead of a synchronous throw. */
|
|
28
|
+
import { isTerminal } from '@modelcontextprotocol/sdk/experimental';
|
|
29
|
+
import { randomBytes } from 'node:crypto';
|
|
30
|
+
import { logger } from '../utils/logger.js';
|
|
31
|
+
export class RetentionTaskStore {
|
|
32
|
+
defaultTtl;
|
|
33
|
+
tasks = new Map();
|
|
34
|
+
/**
|
|
35
|
+
* @param defaultTtl Retention window (ms) applied when a task is created
|
|
36
|
+
* without an explicit `ttl`. `null` means unlimited (no eviction).
|
|
37
|
+
*/
|
|
38
|
+
constructor(defaultTtl = null) {
|
|
39
|
+
this.defaultTtl = defaultTtl;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Generates a unique task ID (16 random bytes as 32 hex chars), matching
|
|
43
|
+
* `InMemoryTaskStore`.
|
|
44
|
+
*/
|
|
45
|
+
generateTaskId() {
|
|
46
|
+
return randomBytes(16).toString('hex');
|
|
47
|
+
}
|
|
48
|
+
/** True when a stored task's retention window has elapsed. */
|
|
49
|
+
isExpired(stored) {
|
|
50
|
+
return stored.expiresAt !== undefined && Date.now() >= stored.expiresAt;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Evict a task and log a distinct eviction message (never a failure). Logged
|
|
54
|
+
* at `info` so a post-retention `-32602` remains diagnosable under the default
|
|
55
|
+
* `LOG_LEVEL=info` — this is a benign, expected event, not an error.
|
|
56
|
+
*/
|
|
57
|
+
evict(taskId) {
|
|
58
|
+
this.tasks.delete(taskId);
|
|
59
|
+
logger.info(`Evicting task ${taskId}: retention window elapsed`);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Look up a live (non-expired) stored task, lazily evicting it if its
|
|
63
|
+
* retention window has elapsed.
|
|
64
|
+
*/
|
|
65
|
+
getLive(taskId) {
|
|
66
|
+
const stored = this.tasks.get(taskId);
|
|
67
|
+
if (!stored) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
if (this.isExpired(stored)) {
|
|
71
|
+
this.evict(taskId);
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
return stored;
|
|
75
|
+
}
|
|
76
|
+
async createTask(taskParams, requestId, request, _sessionId) {
|
|
77
|
+
const taskId = this.generateTaskId();
|
|
78
|
+
if (this.tasks.has(taskId)) {
|
|
79
|
+
throw new Error(`Task with ID ${taskId} already exists`);
|
|
80
|
+
}
|
|
81
|
+
const actualTtl = taskParams.ttl ?? this.defaultTtl;
|
|
82
|
+
const createdAt = new Date().toISOString();
|
|
83
|
+
const task = {
|
|
84
|
+
taskId,
|
|
85
|
+
status: 'working',
|
|
86
|
+
ttl: actualTtl,
|
|
87
|
+
createdAt,
|
|
88
|
+
lastUpdatedAt: createdAt,
|
|
89
|
+
pollInterval: taskParams.pollInterval ?? 1000,
|
|
90
|
+
};
|
|
91
|
+
// No `expiresAt`: a freshly-created (non-terminal) task is immortal.
|
|
92
|
+
this.tasks.set(taskId, { task, request, requestId });
|
|
93
|
+
return task;
|
|
94
|
+
}
|
|
95
|
+
async getTask(taskId, _sessionId) {
|
|
96
|
+
const stored = this.getLive(taskId);
|
|
97
|
+
return stored ? { ...stored.task } : null;
|
|
98
|
+
}
|
|
99
|
+
async storeTaskResult(taskId, status, result, _sessionId) {
|
|
100
|
+
const stored = this.getLive(taskId);
|
|
101
|
+
if (!stored) {
|
|
102
|
+
throw new Error(`Task with ID ${taskId} not found`);
|
|
103
|
+
}
|
|
104
|
+
if (isTerminal(stored.task.status)) {
|
|
105
|
+
throw new Error(`Cannot store result for task ${taskId} in terminal status '${stored.task.status}'. Task results can only be stored once.`);
|
|
106
|
+
}
|
|
107
|
+
stored.result = result;
|
|
108
|
+
stored.task.status = status;
|
|
109
|
+
stored.task.lastUpdatedAt = new Date().toISOString();
|
|
110
|
+
// Task just became terminal: open its retention window (if a ttl is set).
|
|
111
|
+
this.openRetentionWindow(stored);
|
|
112
|
+
}
|
|
113
|
+
async getTaskResult(taskId, _sessionId) {
|
|
114
|
+
const stored = this.getLive(taskId);
|
|
115
|
+
if (!stored) {
|
|
116
|
+
throw new Error(`Task with ID ${taskId} not found`);
|
|
117
|
+
}
|
|
118
|
+
if (!stored.result) {
|
|
119
|
+
throw new Error(`Task ${taskId} has no result stored`);
|
|
120
|
+
}
|
|
121
|
+
return stored.result;
|
|
122
|
+
}
|
|
123
|
+
async updateTaskStatus(taskId, status, statusMessage, _sessionId) {
|
|
124
|
+
const stored = this.getLive(taskId);
|
|
125
|
+
if (!stored) {
|
|
126
|
+
throw new Error(`Task with ID ${taskId} not found`);
|
|
127
|
+
}
|
|
128
|
+
if (isTerminal(stored.task.status)) {
|
|
129
|
+
throw new Error(`Cannot update task ${taskId} from terminal status '${stored.task.status}' to '${status}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`);
|
|
130
|
+
}
|
|
131
|
+
stored.task.status = status;
|
|
132
|
+
if (statusMessage) {
|
|
133
|
+
stored.task.statusMessage = statusMessage;
|
|
134
|
+
}
|
|
135
|
+
stored.task.lastUpdatedAt = new Date().toISOString();
|
|
136
|
+
if (isTerminal(status)) {
|
|
137
|
+
// Terminal transition: open the retention window.
|
|
138
|
+
this.openRetentionWindow(stored);
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
// Still non-terminal: remains immortal.
|
|
142
|
+
stored.expiresAt = undefined;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async listTasks(cursor, _sessionId) {
|
|
146
|
+
// Lazily drop terminal tasks whose retention window has elapsed.
|
|
147
|
+
this.sweepExpired();
|
|
148
|
+
const PAGE_SIZE = 10;
|
|
149
|
+
const allTaskIds = Array.from(this.tasks.keys());
|
|
150
|
+
let startIndex = 0;
|
|
151
|
+
if (cursor) {
|
|
152
|
+
const cursorIndex = allTaskIds.indexOf(cursor);
|
|
153
|
+
if (cursorIndex >= 0) {
|
|
154
|
+
startIndex = cursorIndex + 1;
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
throw new Error(`Invalid cursor: ${cursor}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const pageTaskIds = allTaskIds.slice(startIndex, startIndex + PAGE_SIZE);
|
|
161
|
+
const tasks = pageTaskIds.map((taskId) => ({ ...this.tasks.get(taskId).task }));
|
|
162
|
+
const nextCursor = startIndex + PAGE_SIZE < allTaskIds.length
|
|
163
|
+
? pageTaskIds[pageTaskIds.length - 1]
|
|
164
|
+
: undefined;
|
|
165
|
+
return { tasks, nextCursor };
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Evict every terminal task whose retention window has elapsed. Non-terminal
|
|
169
|
+
* (immortal) tasks are always spared. Returns the number of tasks dropped.
|
|
170
|
+
*/
|
|
171
|
+
sweepExpired() {
|
|
172
|
+
let dropped = 0;
|
|
173
|
+
for (const [taskId, stored] of this.tasks) {
|
|
174
|
+
if (this.isExpired(stored)) {
|
|
175
|
+
this.evict(taskId);
|
|
176
|
+
dropped++;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return dropped;
|
|
180
|
+
}
|
|
181
|
+
/** Clear all stored tasks (useful for testing or graceful shutdown). */
|
|
182
|
+
cleanup() {
|
|
183
|
+
this.tasks.clear();
|
|
184
|
+
}
|
|
185
|
+
/** Open a terminal task's retention window from now, if a ttl is configured. */
|
|
186
|
+
openRetentionWindow(stored) {
|
|
187
|
+
if (stored.task.ttl) {
|
|
188
|
+
stored.expiresAt = Date.now() + stored.task.ttl;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=retention-task-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retention-task-store.js","sourceRoot":"","sources":["../../src/services/retention-task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;oEAKoE;AAEpE,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;AAGpE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAe5C,MAAM,OAAO,kBA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,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;IAC/B,CAAC;IAED;;;OAGG;IACH,YAAY;QACV,IAAI,OAAO,GAAG,CAAC,CAAC;QAChB,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC1C,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC3B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;gBACnB,OAAO,EAAE,CAAC;YACZ,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,wEAAwE;IACxE,OAAO;QACL,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED,gFAAgF;IACxE,mBAAmB,CAAC,MAAkB;QAC5C,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;YACpB,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;QAClD,CAAC;IACH,CAAC;CACF"}
|
|
@@ -20,7 +20,7 @@ export interface TaskManagerConfig {
|
|
|
20
20
|
/**
|
|
21
21
|
* Manages MCP task lifecycle: creation, background execution, cancellation, and cleanup.
|
|
22
22
|
*
|
|
23
|
-
* - Provides `
|
|
23
|
+
* - Provides `RetentionTaskStore` and `InMemoryTaskMessageQueue` instances for
|
|
24
24
|
* `McpServer`'s `ProtocolOptions`.
|
|
25
25
|
* - Tracks active background work via `AbortController` per task for cancellation.
|
|
26
26
|
* - Handles graceful shutdown (cancels active tasks, clears timers).
|
|
@@ -29,6 +29,12 @@ export declare class TaskManager {
|
|
|
29
29
|
readonly taskStore: TaskStore;
|
|
30
30
|
readonly taskMessageQueue: TaskMessageQueue;
|
|
31
31
|
readonly config: TaskManagerConfig;
|
|
32
|
+
/**
|
|
33
|
+
* Concrete handle to the same instance exposed as `taskStore`. Retained so the
|
|
34
|
+
* periodic sweep and shutdown can call `RetentionTaskStore`-specific methods
|
|
35
|
+
* (`sweepExpired`, `cleanup`) without repeatedly downcasting the `TaskStore`.
|
|
36
|
+
*/
|
|
37
|
+
private readonly retentionStore;
|
|
32
38
|
/** Maps taskId → AbortController for active background work. */
|
|
33
39
|
private activeControllers;
|
|
34
40
|
private cleanupTimer?;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-manager.d.ts","sourceRoot":"","sources":["../../src/services/task-manager.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;
|
|
1
|
+
{"version":3,"file":"task-manager.d.ts","sourceRoot":"","sources":["../../src/services/task-manager.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAU,MAAM,oCAAoC,CAAC;AAIjF,MAAM,WAAW,iBAAiB;IAChC,8DAA8D;IAC9D,UAAU,EAAE,MAAM,CAAC;IACnB,8DAA8D;IAC9D,YAAY,EAAE,MAAM,CAAC;IACrB,mEAAmE;IACnE,YAAY,EAAE,MAAM,CAAC;IACrB,4DAA4D;IAC5D,eAAe,EAAE,MAAM,CAAC;CACzB;AASD;;;;;;;GAOG;AACH,qBAAa,WAAW;IACtB,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAEnC;;;;OAIG;IACH,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAqB;IAEpD,gEAAgE;IAChE,OAAO,CAAC,iBAAiB,CAA2C;IACpE,OAAO,CAAC,YAAY,CAAC,CAAiC;gBAE1C,MAAM,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC;IAW/C;;;;;;;;;;OAUG;IACH,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI;IA+C7F,6DAA6D;IAC7D,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAS/B,mDAAmD;IACnD,IAAI,WAAW,IAAI,MAAM,CAExB;IAED,OAAO,CAAC,YAAY;IAgBpB,mEAAmE;IACnE,QAAQ,IAAI,IAAI;CAejB"}
|
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
* behind a single adapter class so that future breaking changes in the experimental
|
|
6
6
|
* API only require updates here.
|
|
7
7
|
*/
|
|
8
|
-
import {
|
|
8
|
+
import { InMemoryTaskMessageQueue } from '@modelcontextprotocol/sdk/experimental';
|
|
9
|
+
import { RetentionTaskStore } from './retention-task-store.js';
|
|
9
10
|
import { logger } from '../utils/logger.js';
|
|
10
11
|
const DEFAULT_CONFIG = {
|
|
11
|
-
defaultTtl:
|
|
12
|
+
defaultTtl: 1_800_000, // 30 minutes
|
|
12
13
|
pollInterval: 2_000, // 2 seconds
|
|
13
14
|
maxQueueSize: 100,
|
|
14
15
|
cleanupInterval: 60_000, // 1 minute
|
|
@@ -16,7 +17,7 @@ const DEFAULT_CONFIG = {
|
|
|
16
17
|
/**
|
|
17
18
|
* Manages MCP task lifecycle: creation, background execution, cancellation, and cleanup.
|
|
18
19
|
*
|
|
19
|
-
* - Provides `
|
|
20
|
+
* - Provides `RetentionTaskStore` and `InMemoryTaskMessageQueue` instances for
|
|
20
21
|
* `McpServer`'s `ProtocolOptions`.
|
|
21
22
|
* - Tracks active background work via `AbortController` per task for cancellation.
|
|
22
23
|
* - Handles graceful shutdown (cancels active tasks, clears timers).
|
|
@@ -25,12 +26,22 @@ export class TaskManager {
|
|
|
25
26
|
taskStore;
|
|
26
27
|
taskMessageQueue;
|
|
27
28
|
config;
|
|
29
|
+
/**
|
|
30
|
+
* Concrete handle to the same instance exposed as `taskStore`. Retained so the
|
|
31
|
+
* periodic sweep and shutdown can call `RetentionTaskStore`-specific methods
|
|
32
|
+
* (`sweepExpired`, `cleanup`) without repeatedly downcasting the `TaskStore`.
|
|
33
|
+
*/
|
|
34
|
+
retentionStore;
|
|
28
35
|
/** Maps taskId → AbortController for active background work. */
|
|
29
36
|
activeControllers = new Map();
|
|
30
37
|
cleanupTimer;
|
|
31
38
|
constructor(config) {
|
|
32
39
|
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
33
|
-
|
|
40
|
+
// Feed the configured default into the store so a task created without an
|
|
41
|
+
// explicit `ttl` still gets a bounded post-terminal retention window rather
|
|
42
|
+
// than becoming an immortal terminal entry.
|
|
43
|
+
this.retentionStore = new RetentionTaskStore(this.config.defaultTtl);
|
|
44
|
+
this.taskStore = this.retentionStore;
|
|
34
45
|
this.taskMessageQueue = new InMemoryTaskMessageQueue();
|
|
35
46
|
this.startCleanup();
|
|
36
47
|
}
|
|
@@ -85,7 +96,9 @@ export class TaskManager {
|
|
|
85
96
|
});
|
|
86
97
|
}
|
|
87
98
|
catch {
|
|
88
|
-
//
|
|
99
|
+
// Defensive: a still-'working' task is immortal under RetentionTaskStore,
|
|
100
|
+
// so this should not fail via TTL eviction — guard only against a
|
|
101
|
+
// concurrent terminal-state transition on the same task.
|
|
89
102
|
}
|
|
90
103
|
}
|
|
91
104
|
}
|
|
@@ -110,6 +123,8 @@ export class TaskManager {
|
|
|
110
123
|
startCleanup() {
|
|
111
124
|
this.cleanupTimer = setInterval(() => {
|
|
112
125
|
logger.debug(`Active background tasks: ${this.activeControllers.size}`);
|
|
126
|
+
// Drop expired terminal task entries whose retention window has elapsed.
|
|
127
|
+
this.retentionStore.sweepExpired();
|
|
113
128
|
}, this.config.cleanupInterval);
|
|
114
129
|
// Allow the process to exit even if the timer is still running
|
|
115
130
|
if (this.cleanupTimer &&
|
|
@@ -129,8 +144,8 @@ export class TaskManager {
|
|
|
129
144
|
controller.abort();
|
|
130
145
|
}
|
|
131
146
|
this.activeControllers.clear();
|
|
132
|
-
// Clear
|
|
133
|
-
this.
|
|
147
|
+
// Clear RetentionTaskStore internal state
|
|
148
|
+
this.retentionStore.cleanup();
|
|
134
149
|
}
|
|
135
150
|
}
|
|
136
151
|
//# sourceMappingURL=task-manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-manager.js","sourceRoot":"","sources":["../../src/services/task-manager.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,
|
|
1
|
+
{"version":3,"file":"task-manager.js","sourceRoot":"","sources":["../../src/services/task-manager.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAC;AAGlF,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAa5C,MAAM,cAAc,GAAsB;IACxC,UAAU,EAAE,SAAS,EAAE,aAAa;IACpC,YAAY,EAAE,KAAK,EAAE,YAAY;IACjC,YAAY,EAAE,GAAG;IACjB,eAAe,EAAE,MAAM,EAAE,WAAW;CACrC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,OAAO,WAAW;IACb,SAAS,CAAY;IACrB,gBAAgB,CAAmB;IACnC,MAAM,CAAoB;IAEnC;;;;OAIG;IACc,cAAc,CAAqB;IAEpD,gEAAgE;IACxD,iBAAiB,GAAiC,IAAI,GAAG,EAAE,CAAC;IAC5D,YAAY,CAAkC;IAEtD,YAAY,MAAmC;QAC7C,IAAI,CAAC,MAAM,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,MAAM,EAAE,CAAC;QAC/C,0EAA0E;QAC1E,4EAA4E;QAC5E,4CAA4C;QAC5C,IAAI,CAAC,cAAc,GAAG,IAAI,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACrE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,cAAc,CAAC;QACrC,IAAI,CAAC,gB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,CAAC,CAAC;QAChC,+DAA+D;QAC/D,IACE,IAAI,CAAC,YAAY;YACjB,OAAO,IAAI,CAAC,YAAY,KAAK,QAAQ;YACrC,OAAO,IAAI,IAAI,CAAC,YAAY,EAC5B,CAAC;YACD,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;QAC5B,CAAC;IACH,CAAC;IAED,mEAAmE;IACnE,QAAQ;QACN,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,aAAa,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YACjC,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;QAChC,CAAC;QAED,KAAK,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC1D,MAAM,CAAC,IAAI,CAAC,0BAA0B,MAAM,kBAAkB,CAAC,CAAC;YAChE,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC;QAE/B,0CAA0C;QAC1C,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;IAChC,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-rubber-duck",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.1",
|
|
4
4
|
"description": "An MCP server that bridges to multiple OpenAI-compatible LLMs - your AI rubber duck debugging panel",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -78,6 +78,7 @@
|
|
|
78
78
|
"fast-uri": "^3.1.2",
|
|
79
79
|
"ip-address": "^10.2.0",
|
|
80
80
|
"qs": "^6.15.2",
|
|
81
|
-
"npm": "^11.16.0"
|
|
81
|
+
"npm": "^11.16.0",
|
|
82
|
+
"brace-expansion@1.x": "^1.1.16"
|
|
82
83
|
}
|
|
83
84
|
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `TaskStore` implementation with post-terminal retention semantics.
|
|
3
|
+
*
|
|
4
|
+
* Unlike the SDK's `InMemoryTaskStore` — which arms a deletion timer at task
|
|
5
|
+
* creation and evicts the record after `ttl` regardless of status — this store
|
|
6
|
+
* treats `ttl` as a *retention window that starts when the task reaches a
|
|
7
|
+
* terminal state*. Consequences:
|
|
8
|
+
*
|
|
9
|
+
* - A non-terminal task (`submitted`/`working`) is immortal: it has no
|
|
10
|
+
* `expiresAt` and is never evicted, no matter how much time elapses.
|
|
11
|
+
* - Once a task reaches a terminal state (`completed`/`failed`/`cancelled`),
|
|
12
|
+
* its retention window opens (`expiresAt = now + ttl`). It stays retrievable
|
|
13
|
+
* until the window elapses, then is evicted lazily on read or by the periodic
|
|
14
|
+
* `sweepExpired()` sweep.
|
|
15
|
+
*
|
|
16
|
+
* Method contracts and error-message strings mirror `InMemoryTaskStore` so the
|
|
17
|
+
* only behavioral difference is timer semantics.
|
|
18
|
+
*
|
|
19
|
+
* WARNING: builds on the experimental `@modelcontextprotocol/sdk/experimental`
|
|
20
|
+
* Tasks API, which may change without notice.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/* eslint-disable @typescript-eslint/require-await --
|
|
24
|
+
* The `TaskStore` interface requires every method to return a Promise. This
|
|
25
|
+
* store is backed by a synchronous in-memory Map, but its methods stay `async`
|
|
26
|
+
* to match the interface and the SDK's `InMemoryTaskStore`. Keeping them async
|
|
27
|
+
* (rather than returning `Promise.resolve`) ensures a guard-clause `throw`
|
|
28
|
+
* surfaces as a rejected promise instead of a synchronous throw. */
|
|
29
|
+
|
|
30
|
+
import { isTerminal } from '@modelcontextprotocol/sdk/experimental';
|
|
31
|
+
import type { TaskStore, CreateTaskOptions } from '@modelcontextprotocol/sdk/experimental';
|
|
32
|
+
import type { Task, RequestId, Request, Result } from '@modelcontextprotocol/sdk/types.js';
|
|
33
|
+
import { randomBytes } from 'node:crypto';
|
|
34
|
+
import { logger } from '../utils/logger.js';
|
|
35
|
+
|
|
36
|
+
/** Internal record wrapping a task with its request context and retention window. */
|
|
37
|
+
interface StoredTask {
|
|
38
|
+
task: Task;
|
|
39
|
+
request: Request;
|
|
40
|
+
requestId: RequestId;
|
|
41
|
+
result?: Result;
|
|
42
|
+
/**
|
|
43
|
+
* Epoch milliseconds after which a *terminal* task is evicted. Undefined
|
|
44
|
+
* means the task is non-terminal (immortal) — it has no retention window.
|
|
45
|
+
*/
|
|
46
|
+
expiresAt?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class RetentionTaskStore implements TaskStore {
|
|
50
|
+
private tasks: Map<string, StoredTask> = new Map();
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param defaultTtl Retention window (ms) applied when a task is created
|
|
54
|
+
* without an explicit `ttl`. `null` means unlimited (no eviction).
|
|
55
|
+
*/
|
|
56
|
+
constructor(private readonly defaultTtl: number | null = null) {}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Generates a unique task ID (16 random bytes as 32 hex chars), matching
|
|
60
|
+
* `InMemoryTaskStore`.
|
|
61
|
+
*/
|
|
62
|
+
private generateTaskId(): string {
|
|
63
|
+
return randomBytes(16).toString('hex');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** True when a stored task's retention window has elapsed. */
|
|
67
|
+
private isExpired(stored: StoredTask): boolean {
|
|
68
|
+
return stored.expiresAt !== undefined && Date.now() >= stored.expiresAt;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Evict a task and log a distinct eviction message (never a failure). Logged
|
|
73
|
+
* at `info` so a post-retention `-32602` remains diagnosable under the default
|
|
74
|
+
* `LOG_LEVEL=info` — this is a benign, expected event, not an error.
|
|
75
|
+
*/
|
|
76
|
+
private evict(taskId: string): void {
|
|
77
|
+
this.tasks.delete(taskId);
|
|
78
|
+
logger.info(`Evicting task ${taskId}: retention window elapsed`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Look up a live (non-expired) stored task, lazily evicting it if its
|
|
83
|
+
* retention window has elapsed.
|
|
84
|
+
*/
|
|
85
|
+
private getLive(taskId: string): StoredTask | undefined {
|
|
86
|
+
const stored = this.tasks.get(taskId);
|
|
87
|
+
if (!stored) {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
if (this.isExpired(stored)) {
|
|
91
|
+
this.evict(taskId);
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
return stored;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async createTask(
|
|
98
|
+
taskParams: CreateTaskOptions,
|
|
99
|
+
requestId: RequestId,
|
|
100
|
+
request: Request,
|
|
101
|
+
_sessionId?: string
|
|
102
|
+
): Promise<Task> {
|
|
103
|
+
const taskId = this.generateTaskId();
|
|
104
|
+
if (this.tasks.has(taskId)) {
|
|
105
|
+
throw new Error(`Task with ID ${taskId} already exists`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const actualTtl = taskParams.ttl ?? this.defaultTtl;
|
|
109
|
+
const createdAt = new Date().toISOString();
|
|
110
|
+
const task: Task = {
|
|
111
|
+
taskId,
|
|
112
|
+
status: 'working',
|
|
113
|
+
ttl: actualTtl,
|
|
114
|
+
createdAt,
|
|
115
|
+
lastUpdatedAt: createdAt,
|
|
116
|
+
pollInterval: taskParams.pollInterval ?? 1000,
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// No `expiresAt`: a freshly-created (non-terminal) task is immortal.
|
|
120
|
+
this.tasks.set(taskId, { task, request, requestId });
|
|
121
|
+
return task;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async getTask(taskId: string, _sessionId?: string): Promise<Task | null> {
|
|
125
|
+
const stored = this.getLive(taskId);
|
|
126
|
+
return stored ? { ...stored.task } : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async storeTaskResult(
|
|
130
|
+
taskId: string,
|
|
131
|
+
status: 'completed' | 'failed',
|
|
132
|
+
result: Result,
|
|
133
|
+
_sessionId?: string
|
|
134
|
+
): Promise<void> {
|
|
135
|
+
const stored = this.getLive(taskId);
|
|
136
|
+
if (!stored) {
|
|
137
|
+
throw new Error(`Task with ID ${taskId} not found`);
|
|
138
|
+
}
|
|
139
|
+
if (isTerminal(stored.task.status)) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
`Cannot store result for task ${taskId} in terminal status '${stored.task.status}'. Task results can only be stored once.`
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
stored.result = result;
|
|
146
|
+
stored.task.status = status;
|
|
147
|
+
stored.task.lastUpdatedAt = new Date().toISOString();
|
|
148
|
+
// Task just became terminal: open its retention window (if a ttl is set).
|
|
149
|
+
this.openRetentionWindow(stored);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async getTaskResult(taskId: string, _sessionId?: string): Promise<Result> {
|
|
153
|
+
const stored = this.getLive(taskId);
|
|
154
|
+
if (!stored) {
|
|
155
|
+
throw new Error(`Task with ID ${taskId} not found`);
|
|
156
|
+
}
|
|
157
|
+
if (!stored.result) {
|
|
158
|
+
throw new Error(`Task ${taskId} has no result stored`);
|
|
159
|
+
}
|
|
160
|
+
return stored.result;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async updateTaskStatus(
|
|
164
|
+
taskId: string,
|
|
165
|
+
status: Task['status'],
|
|
166
|
+
statusMessage?: string,
|
|
167
|
+
_sessionId?: string
|
|
168
|
+
): Promise<void> {
|
|
169
|
+
const stored = this.getLive(taskId);
|
|
170
|
+
if (!stored) {
|
|
171
|
+
throw new Error(`Task with ID ${taskId} not found`);
|
|
172
|
+
}
|
|
173
|
+
if (isTerminal(stored.task.status)) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
`Cannot update task ${taskId} from terminal status '${stored.task.status}' to '${status}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
stored.task.status = status;
|
|
180
|
+
if (statusMessage) {
|
|
181
|
+
stored.task.statusMessage = statusMessage;
|
|
182
|
+
}
|
|
183
|
+
stored.task.lastUpdatedAt = new Date().toISOString();
|
|
184
|
+
|
|
185
|
+
if (isTerminal(status)) {
|
|
186
|
+
// Terminal transition: open the retention window.
|
|
187
|
+
this.openRetentionWindow(stored);
|
|
188
|
+
} else {
|
|
189
|
+
// Still non-terminal: remains immortal.
|
|
190
|
+
stored.expiresAt = undefined;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async listTasks(
|
|
195
|
+
cursor?: string,
|
|
196
|
+
_sessionId?: string
|
|
197
|
+
): Promise<{ tasks: Task[]; nextCursor?: string }> {
|
|
198
|
+
// Lazily drop terminal tasks whose retention window has elapsed.
|
|
199
|
+
this.sweepExpired();
|
|
200
|
+
|
|
201
|
+
const PAGE_SIZE = 10;
|
|
202
|
+
const allTaskIds = Array.from(this.tasks.keys());
|
|
203
|
+
let startIndex = 0;
|
|
204
|
+
if (cursor) {
|
|
205
|
+
const cursorIndex = allTaskIds.indexOf(cursor);
|
|
206
|
+
if (cursorIndex >= 0) {
|
|
207
|
+
startIndex = cursorIndex + 1;
|
|
208
|
+
} else {
|
|
209
|
+
throw new Error(`Invalid cursor: ${cursor}`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const pageTaskIds = allTaskIds.slice(startIndex, startIndex + PAGE_SIZE);
|
|
214
|
+
const tasks = pageTaskIds.map((taskId) => ({ ...this.tasks.get(taskId)!.task }));
|
|
215
|
+
const nextCursor =
|
|
216
|
+
startIndex + PAGE_SIZE < allTaskIds.length
|
|
217
|
+
? pageTaskIds[pageTaskIds.length - 1]
|
|
218
|
+
: undefined;
|
|
219
|
+
return { tasks, nextCursor };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Evict every terminal task whose retention window has elapsed. Non-terminal
|
|
224
|
+
* (immortal) tasks are always spared. Returns the number of tasks dropped.
|
|
225
|
+
*/
|
|
226
|
+
sweepExpired(): number {
|
|
227
|
+
let dropped = 0;
|
|
228
|
+
for (const [taskId, stored] of this.tasks) {
|
|
229
|
+
if (this.isExpired(stored)) {
|
|
230
|
+
this.evict(taskId);
|
|
231
|
+
dropped++;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return dropped;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Clear all stored tasks (useful for testing or graceful shutdown). */
|
|
238
|
+
cleanup(): void {
|
|
239
|
+
this.tasks.clear();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Open a terminal task's retention window from now, if a ttl is configured. */
|
|
243
|
+
private openRetentionWindow(stored: StoredTask): void {
|
|
244
|
+
if (stored.task.ttl) {
|
|
245
|
+
stored.expiresAt = Date.now() + stored.task.ttl;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
@@ -6,12 +6,10 @@
|
|
|
6
6
|
* API only require updates here.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import {
|
|
10
|
-
InMemoryTaskStore,
|
|
11
|
-
InMemoryTaskMessageQueue,
|
|
12
|
-
} from '@modelcontextprotocol/sdk/experimental';
|
|
9
|
+
import { InMemoryTaskMessageQueue } from '@modelcontextprotocol/sdk/experimental';
|
|
13
10
|
import type { TaskStore, TaskMessageQueue } from '@modelcontextprotocol/sdk/experimental';
|
|
14
11
|
import type { CallToolResult, Result } from '@modelcontextprotocol/sdk/types.js';
|
|
12
|
+
import { RetentionTaskStore } from './retention-task-store.js';
|
|
15
13
|
import { logger } from '../utils/logger.js';
|
|
16
14
|
|
|
17
15
|
export interface TaskManagerConfig {
|
|
@@ -26,7 +24,7 @@ export interface TaskManagerConfig {
|
|
|
26
24
|
}
|
|
27
25
|
|
|
28
26
|
const DEFAULT_CONFIG: TaskManagerConfig = {
|
|
29
|
-
defaultTtl:
|
|
27
|
+
defaultTtl: 1_800_000, // 30 minutes
|
|
30
28
|
pollInterval: 2_000, // 2 seconds
|
|
31
29
|
maxQueueSize: 100,
|
|
32
30
|
cleanupInterval: 60_000, // 1 minute
|
|
@@ -35,7 +33,7 @@ const DEFAULT_CONFIG: TaskManagerConfig = {
|
|
|
35
33
|
/**
|
|
36
34
|
* Manages MCP task lifecycle: creation, background execution, cancellation, and cleanup.
|
|
37
35
|
*
|
|
38
|
-
* - Provides `
|
|
36
|
+
* - Provides `RetentionTaskStore` and `InMemoryTaskMessageQueue` instances for
|
|
39
37
|
* `McpServer`'s `ProtocolOptions`.
|
|
40
38
|
* - Tracks active background work via `AbortController` per task for cancellation.
|
|
41
39
|
* - Handles graceful shutdown (cancels active tasks, clears timers).
|
|
@@ -45,13 +43,24 @@ export class TaskManager {
|
|
|
45
43
|
readonly taskMessageQueue: TaskMessageQueue;
|
|
46
44
|
readonly config: TaskManagerConfig;
|
|
47
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Concrete handle to the same instance exposed as `taskStore`. Retained so the
|
|
48
|
+
* periodic sweep and shutdown can call `RetentionTaskStore`-specific methods
|
|
49
|
+
* (`sweepExpired`, `cleanup`) without repeatedly downcasting the `TaskStore`.
|
|
50
|
+
*/
|
|
51
|
+
private readonly retentionStore: RetentionTaskStore;
|
|
52
|
+
|
|
48
53
|
/** Maps taskId → AbortController for active background work. */
|
|
49
54
|
private activeControllers: Map<string, AbortController> = new Map();
|
|
50
55
|
private cleanupTimer?: ReturnType<typeof setInterval>;
|
|
51
56
|
|
|
52
57
|
constructor(config?: Partial<TaskManagerConfig>) {
|
|
53
58
|
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
54
|
-
|
|
59
|
+
// Feed the configured default into the store so a task created without an
|
|
60
|
+
// explicit `ttl` still gets a bounded post-terminal retention window rather
|
|
61
|
+
// than becoming an immortal terminal entry.
|
|
62
|
+
this.retentionStore = new RetentionTaskStore(this.config.defaultTtl);
|
|
63
|
+
this.taskStore = this.retentionStore;
|
|
55
64
|
this.taskMessageQueue = new InMemoryTaskMessageQueue();
|
|
56
65
|
this.startCleanup();
|
|
57
66
|
}
|
|
@@ -103,7 +112,9 @@ export class TaskManager {
|
|
|
103
112
|
isError: true,
|
|
104
113
|
} as Result);
|
|
105
114
|
} catch {
|
|
106
|
-
//
|
|
115
|
+
// Defensive: a still-'working' task is immortal under RetentionTaskStore,
|
|
116
|
+
// so this should not fail via TTL eviction — guard only against a
|
|
117
|
+
// concurrent terminal-state transition on the same task.
|
|
107
118
|
}
|
|
108
119
|
}
|
|
109
120
|
} finally {
|
|
@@ -130,6 +141,8 @@ export class TaskManager {
|
|
|
130
141
|
private startCleanup(): void {
|
|
131
142
|
this.cleanupTimer = setInterval(() => {
|
|
132
143
|
logger.debug(`Active background tasks: ${this.activeControllers.size}`);
|
|
144
|
+
// Drop expired terminal task entries whose retention window has elapsed.
|
|
145
|
+
this.retentionStore.sweepExpired();
|
|
133
146
|
}, this.config.cleanupInterval);
|
|
134
147
|
// Allow the process to exit even if the timer is still running
|
|
135
148
|
if (
|
|
@@ -154,7 +167,7 @@ export class TaskManager {
|
|
|
154
167
|
}
|
|
155
168
|
this.activeControllers.clear();
|
|
156
169
|
|
|
157
|
-
// Clear
|
|
158
|
-
|
|
170
|
+
// Clear RetentionTaskStore internal state
|
|
171
|
+
this.retentionStore.cleanup();
|
|
159
172
|
}
|
|
160
173
|
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
|
2
|
+
|
|
3
|
+
import { RetentionTaskStore } from '../../src/services/retention-task-store.js';
|
|
4
|
+
import { logger } from '../../src/utils/logger.js';
|
|
5
|
+
import type { CallToolResult, Result } from '@modelcontextprotocol/sdk/types.js';
|
|
6
|
+
|
|
7
|
+
// A minimal request object mirroring the shape used in task-manager.test.ts.
|
|
8
|
+
const REQUEST = { method: 'tools/call', params: { name: 'test', arguments: {} } };
|
|
9
|
+
|
|
10
|
+
function makeResult(text: string): Result {
|
|
11
|
+
return { content: [{ type: 'text', text }] } as CallToolResult as Result;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Under this repo's ESM Jest config (ts-jest default-esm, isolatedModules),
|
|
15
|
+
// `jest.mock(path, factory)` is a no-op — the statically-imported `logger` stays
|
|
16
|
+
// the real winston singleton. So we spy on the singleton's methods directly and
|
|
17
|
+
// read genuine `mock.calls` for the eviction-log assertions. Spying across every
|
|
18
|
+
// level also silences winston output during the run.
|
|
19
|
+
let debugSpy: ReturnType<typeof jest.spyOn>;
|
|
20
|
+
let infoSpy: ReturnType<typeof jest.spyOn>;
|
|
21
|
+
let warnSpy: ReturnType<typeof jest.spyOn>;
|
|
22
|
+
let errorSpy: ReturnType<typeof jest.spyOn>;
|
|
23
|
+
|
|
24
|
+
/** Flatten every logged call (all levels) into single-line strings. */
|
|
25
|
+
function collectLoggedMessages(): string[] {
|
|
26
|
+
const spies = [debugSpy, infoSpy, warnSpy, errorSpy];
|
|
27
|
+
const messages: string[] = [];
|
|
28
|
+
for (const spy of spies) {
|
|
29
|
+
for (const call of spy.mock.calls) {
|
|
30
|
+
messages.push((call as unknown[]).map((a) => String(a)).join(' '));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return messages;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Only the error-level logged lines, as single-line strings. */
|
|
37
|
+
function collectErrorMessages(): string[] {
|
|
38
|
+
return errorSpy.mock.calls.map((call) =>
|
|
39
|
+
(call as unknown[]).map((a) => String(a)).join(' ')
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
describe('RetentionTaskStore', () => {
|
|
44
|
+
let store: RetentionTaskStore;
|
|
45
|
+
|
|
46
|
+
beforeEach(() => {
|
|
47
|
+
debugSpy = jest.spyOn(logger, 'debug').mockImplementation(() => logger as never);
|
|
48
|
+
infoSpy = jest.spyOn(logger, 'info').mockImplementation(() => logger as never);
|
|
49
|
+
warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => logger as never);
|
|
50
|
+
errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger as never);
|
|
51
|
+
jest.useFakeTimers();
|
|
52
|
+
store = new RetentionTaskStore();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
afterEach(() => {
|
|
56
|
+
store.cleanup();
|
|
57
|
+
jest.useRealTimers();
|
|
58
|
+
jest.restoreAllMocks();
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// AC-XNJKNA.1 — a non-terminal (working) task is never evicted, no matter how
|
|
62
|
+
// much time passes. The old InMemoryTaskStore armed a deletion timer at creation
|
|
63
|
+
// and would have deleted this record after `ttl`; the retention store must not.
|
|
64
|
+
it('AC-XNJKNA.1: keeps a non-terminal task alive past defaultTtl (running tasks are immortal)', async () => {
|
|
65
|
+
const task = await store.createTask({ ttl: 1_800_000 }, 'req-1', REQUEST);
|
|
66
|
+
expect(task.status).toBe('working');
|
|
67
|
+
|
|
68
|
+
// Advance well past the retention window with NO terminal transition.
|
|
69
|
+
jest.advanceTimersByTime(1_800_000 + 60_000);
|
|
70
|
+
|
|
71
|
+
const stored = await store.getTask(task.taskId);
|
|
72
|
+
expect(stored).not.toBeNull();
|
|
73
|
+
expect(stored?.status).toBe('working');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// AC-XNJKNA.2 — ttl is a post-terminal retention window, not a lifetime-from-creation
|
|
77
|
+
// wall: the completed result is retrievable at ttl-1 and evicted at ttl+1.
|
|
78
|
+
it('AC-XNJKNA.2: retains a completed result until ttl, then evicts it', async () => {
|
|
79
|
+
const ttl = 1_800_000;
|
|
80
|
+
const task = await store.createTask({ ttl }, 'req-2', REQUEST);
|
|
81
|
+
const result = makeResult('debate complete');
|
|
82
|
+
|
|
83
|
+
await store.storeTaskResult(task.taskId, 'completed', result);
|
|
84
|
+
|
|
85
|
+
// Just before the retention boundary: result still retrievable.
|
|
86
|
+
jest.advanceTimersByTime(ttl - 1);
|
|
87
|
+
const stillThere = await store.getTaskResult(task.taskId);
|
|
88
|
+
expect(stillThere).toEqual(result);
|
|
89
|
+
|
|
90
|
+
// At exactly t = ttl the window has elapsed. `isExpired` uses `now >= expiresAt`,
|
|
91
|
+
// so the entry is evicted at the boundary itself (parity with the SDK store's
|
|
92
|
+
// `setTimeout(ttl)` deletion) — a `>` implementation would wrongly keep it here.
|
|
93
|
+
jest.advanceTimersByTime(1);
|
|
94
|
+
|
|
95
|
+
expect(await store.getTask(task.taskId)).toBeNull();
|
|
96
|
+
await expect(store.getTaskResult(task.taskId)).rejects.toThrow(
|
|
97
|
+
`Task with ID ${task.taskId} not found`
|
|
98
|
+
);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// listTasks lazy filter — terminal tasks past their window are filtered out;
|
|
102
|
+
// a still-working task and a not-yet-expired terminal remain.
|
|
103
|
+
it('listTasks lazily filters out terminal tasks whose retention window elapsed', async () => {
|
|
104
|
+
const ttl = 1_800_000;
|
|
105
|
+
const working = await store.createTask({ ttl }, 'req-working', REQUEST);
|
|
106
|
+
const doneOld = await store.createTask({ ttl }, 'req-old', REQUEST);
|
|
107
|
+
const doneRecent = await store.createTask({ ttl }, 'req-recent', REQUEST);
|
|
108
|
+
|
|
109
|
+
await store.storeTaskResult(doneOld.taskId, 'completed', makeResult('old'));
|
|
110
|
+
|
|
111
|
+
// Let the old terminal task's window fully elapse.
|
|
112
|
+
jest.advanceTimersByTime(ttl + 1);
|
|
113
|
+
|
|
114
|
+
// A fresh terminal task, well within its own window.
|
|
115
|
+
await store.storeTaskResult(doneRecent.taskId, 'completed', makeResult('recent'));
|
|
116
|
+
|
|
117
|
+
const { tasks } = await store.listTasks();
|
|
118
|
+
const ids = tasks.map((t) => t.taskId);
|
|
119
|
+
|
|
120
|
+
expect(ids).toContain(working.taskId); // working never expires
|
|
121
|
+
expect(ids).toContain(doneRecent.taskId); // within retention window
|
|
122
|
+
expect(ids).not.toContain(doneOld.taskId); // lazily evicted
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// sweepExpired — drops expired terminal entries, returns the drop count, and
|
|
126
|
+
// leaves working tasks untouched (called by TaskManager's 60s sweep).
|
|
127
|
+
it('sweepExpired() drops expired terminal entries and returns their count, sparing working tasks', async () => {
|
|
128
|
+
const ttl = 1_800_000;
|
|
129
|
+
const working = await store.createTask({ ttl }, 'req-w', REQUEST);
|
|
130
|
+
const done = await store.createTask({ ttl }, 'req-d', REQUEST);
|
|
131
|
+
await store.storeTaskResult(done.taskId, 'completed', makeResult('x'));
|
|
132
|
+
|
|
133
|
+
jest.advanceTimersByTime(ttl + 1);
|
|
134
|
+
|
|
135
|
+
const dropped = store.sweepExpired();
|
|
136
|
+
expect(dropped).toBe(1);
|
|
137
|
+
|
|
138
|
+
// The working task survives the sweep.
|
|
139
|
+
expect(await store.getTask(working.taskId)).not.toBeNull();
|
|
140
|
+
// The swept terminal task is gone.
|
|
141
|
+
expect(await store.getTask(done.taskId)).toBeNull();
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
// Terminal-overwrite rejection — updateTaskStatus out of a terminal state throws,
|
|
145
|
+
// and storeTaskResult over a terminal task throws (matching InMemoryTaskStore).
|
|
146
|
+
it('rejects transitions out of, and result-stores over, a terminal task', async () => {
|
|
147
|
+
const task = await store.createTask({ ttl: 1_800_000 }, 'req-term', REQUEST);
|
|
148
|
+
await store.storeTaskResult(task.taskId, 'completed', makeResult('done'));
|
|
149
|
+
|
|
150
|
+
await expect(store.updateTaskStatus(task.taskId, 'working')).rejects.toThrow(
|
|
151
|
+
/Cannot update task .* from terminal status/
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
await expect(
|
|
155
|
+
store.storeTaskResult(task.taskId, 'failed', makeResult('nope'))
|
|
156
|
+
).rejects.toThrow('Cannot store result for task');
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// AC-XNJKNA.5 (store side) — when a terminal task is lazily evicted on read, a
|
|
160
|
+
// distinct eviction message is logged that is NOT conflated with a task failure.
|
|
161
|
+
it('AC-XNJKNA.5 (store): logs a distinct eviction message (not a failure) on lazy eviction', async () => {
|
|
162
|
+
const ttl = 1_800_000;
|
|
163
|
+
const task = await store.createTask({ ttl }, 'req-evict', REQUEST);
|
|
164
|
+
// Use a *completed* task so any "failed" wording can only come from wrongly
|
|
165
|
+
// conflating eviction with failure — not from the task's own status.
|
|
166
|
+
await store.storeTaskResult(task.taskId, 'completed', makeResult('done'));
|
|
167
|
+
|
|
168
|
+
jest.advanceTimersByTime(ttl + 1);
|
|
169
|
+
|
|
170
|
+
// Trigger lazy eviction on read.
|
|
171
|
+
expect(await store.getTask(task.taskId)).toBeNull();
|
|
172
|
+
|
|
173
|
+
const evictionLog = collectLoggedMessages().find((msg) => /evict/i.test(msg));
|
|
174
|
+
expect(evictionLog).toBeDefined(); // an eviction message was logged
|
|
175
|
+
expect(evictionLog).not.toMatch(/failed/i); // and it is distinct from a failure
|
|
176
|
+
|
|
177
|
+
// No error-level "failed" line for an ordinary retention eviction.
|
|
178
|
+
expect(collectErrorMessages().filter((msg) => /failed/i.test(msg))).toHaveLength(0);
|
|
179
|
+
});
|
|
180
|
+
});
|
|
@@ -1,14 +1,28 @@
|
|
|
1
1
|
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
|
2
2
|
|
|
3
|
-
jest.mock('../../src/utils/logger');
|
|
4
|
-
|
|
5
3
|
import { TaskManager } from '../../src/services/task-manager.js';
|
|
4
|
+
import { logger } from '../../src/utils/logger.js';
|
|
6
5
|
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
|
|
7
6
|
|
|
7
|
+
// Under this repo's ESM Jest config (ts-jest default-esm, isolatedModules),
|
|
8
|
+
// `jest.mock(path, factory)` is a no-op. Spy on the real winston singleton
|
|
9
|
+
// instead: `mockImplementation` silences output for the tests that don't assert
|
|
10
|
+
// on the logger, while `errorSpy.mock.calls` gives the AC-XNJKNA.5 success-path
|
|
11
|
+
// test a genuine record of error-level logs to assert against.
|
|
12
|
+
let errorSpy: ReturnType<typeof jest.spyOn>;
|
|
13
|
+
|
|
14
|
+
function installLoggerSpies(): void {
|
|
15
|
+
jest.spyOn(logger, 'debug').mockImplementation(() => logger as never);
|
|
16
|
+
jest.spyOn(logger, 'info').mockImplementation(() => logger as never);
|
|
17
|
+
jest.spyOn(logger, 'warn').mockImplementation(() => logger as never);
|
|
18
|
+
errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger as never);
|
|
19
|
+
}
|
|
20
|
+
|
|
8
21
|
describe('TaskManager', () => {
|
|
9
22
|
let taskManager: TaskManager;
|
|
10
23
|
|
|
11
24
|
beforeEach(() => {
|
|
25
|
+
installLoggerSpies();
|
|
12
26
|
taskManager = new TaskManager({
|
|
13
27
|
cleanupInterval: 600_000, // long interval to avoid noise
|
|
14
28
|
});
|
|
@@ -16,13 +30,15 @@ describe('TaskManager', () => {
|
|
|
16
30
|
|
|
17
31
|
afterEach(() => {
|
|
18
32
|
taskManager.shutdown();
|
|
33
|
+
jest.restoreAllMocks();
|
|
19
34
|
});
|
|
20
35
|
|
|
21
36
|
describe('constructor', () => {
|
|
22
37
|
it('should use default config values when none provided', () => {
|
|
23
38
|
const tm = new TaskManager();
|
|
24
39
|
try {
|
|
25
|
-
|
|
40
|
+
// AC-XNJKNA.3: default TTL is now the 30-min post-terminal retention window.
|
|
41
|
+
expect(tm.config.defaultTtl).toBe(1_800_000);
|
|
26
42
|
expect(tm.config.pollInterval).toBe(2_000);
|
|
27
43
|
expect(tm.config.maxQueueSize).toBe(100);
|
|
28
44
|
expect(tm.config.cleanupInterval).toBe(60_000);
|
|
@@ -341,4 +357,85 @@ describe('TaskManager', () => {
|
|
|
341
357
|
}
|
|
342
358
|
});
|
|
343
359
|
});
|
|
360
|
+
|
|
361
|
+
// AC-XNJKNA.4 / AC-XNJKNA.5 — the RetentionTaskStore is wired into TaskManager,
|
|
362
|
+
// so a run that outlives the old 5-min wall completes with its result retained
|
|
363
|
+
// and no misleading error-level "failed" log on the success path. These drive
|
|
364
|
+
// fake timers against real background work, so they live in their own describe.
|
|
365
|
+
describe('RetentionTaskStore wiring (fake timers)', () => {
|
|
366
|
+
let tm: TaskManager;
|
|
367
|
+
|
|
368
|
+
beforeEach(() => {
|
|
369
|
+
jest.clearAllMocks();
|
|
370
|
+
jest.useFakeTimers();
|
|
371
|
+
tm = new TaskManager({ cleanupInterval: 600_000 });
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
afterEach(() => {
|
|
375
|
+
tm.shutdown();
|
|
376
|
+
jest.useRealTimers();
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
// AC-XNJKNA.4: the task store TaskManager hands the server is the new store class.
|
|
380
|
+
it('AC-XNJKNA.4: exposes a RetentionTaskStore as its taskStore', async () => {
|
|
381
|
+
const { RetentionTaskStore } = await import(
|
|
382
|
+
'../../src/services/retention-task-store.js'
|
|
383
|
+
);
|
|
384
|
+
expect(tm.taskStore).toBeInstanceOf(RetentionTaskStore);
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
// AC-XNJKNA.4: a run whose work exceeds the old 300_000 ms wall still completes
|
|
388
|
+
// and its result stays retrievable (the old store would have evicted it mid-run).
|
|
389
|
+
it('AC-XNJKNA.4: completes a run exceeding the old 5-min wall and keeps its result retrievable', async () => {
|
|
390
|
+
const task = await tm.taskStore.createTask(
|
|
391
|
+
{ ttl: 300_000 }, // the old 5-minute wall
|
|
392
|
+
'req-long',
|
|
393
|
+
{ method: 'tools/call', params: { name: 'duck_debate', arguments: {} } }
|
|
394
|
+
);
|
|
395
|
+
|
|
396
|
+
const expected: CallToolResult = {
|
|
397
|
+
content: [{ type: 'text', text: 'debate complete' }],
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
tm.startBackground(task.taskId, async () => {
|
|
401
|
+
// Work that runs longer than the old 5-minute eviction wall.
|
|
402
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 350_000));
|
|
403
|
+
return expected;
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
// Drive past the old wall; the run finishes at 350s.
|
|
407
|
+
await jest.advanceTimersByTimeAsync(360_000);
|
|
408
|
+
|
|
409
|
+
const stored = await tm.taskStore.getTask(task.taskId);
|
|
410
|
+
expect(stored?.status).toBe('completed');
|
|
411
|
+
|
|
412
|
+
const result = await tm.taskStore.getTaskResult(task.taskId);
|
|
413
|
+
expect(result).toEqual(expected);
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
// AC-XNJKNA.5: the completed success path emits no error-level "failed" log.
|
|
417
|
+
it('AC-XNJKNA.5: does not log an error-level "failed" message on the success path', async () => {
|
|
418
|
+
const task = await tm.taskStore.createTask(
|
|
419
|
+
{ ttl: 300_000 },
|
|
420
|
+
'req-success-log',
|
|
421
|
+
{ method: 'tools/call', params: { name: 'duck_iterate', arguments: {} } }
|
|
422
|
+
);
|
|
423
|
+
|
|
424
|
+
tm.startBackground(task.taskId, async () => {
|
|
425
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 350_000));
|
|
426
|
+
return { content: [{ type: 'text', text: 'iterate complete' }] };
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
await jest.advanceTimersByTimeAsync(360_000);
|
|
430
|
+
|
|
431
|
+
// Sanity: the run actually reached the completed success path.
|
|
432
|
+
const stored = await tm.taskStore.getTask(task.taskId);
|
|
433
|
+
expect(stored?.status).toBe('completed');
|
|
434
|
+
|
|
435
|
+
const failedErrorLogs = errorSpy.mock.calls
|
|
436
|
+
.map((call) => (call as unknown[]).map((a) => String(a)).join(' '))
|
|
437
|
+
.filter((msg) => /failed/i.test(msg));
|
|
438
|
+
expect(failedErrorLogs).toHaveLength(0);
|
|
439
|
+
});
|
|
440
|
+
});
|
|
344
441
|
});
|