@dotdrelle/wiki-manager 0.7.3 → 0.8.2
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/.env.example +20 -0
- package/README.md +35 -1
- package/docker-compose.yml +1 -23
- package/mcp.endpoints.example.json +13 -0
- package/package.json +2 -2
- package/src/agent/graph.js +101 -15
- package/src/agent/graph.test.js +145 -0
- package/src/cli/wiki-manager.js +274 -53
- package/src/commands/slash.js +1 -1
- package/src/core/agentEvents.js +124 -4
- package/src/core/agentEvents.test.js +145 -4
- package/src/core/agentLoop.js +3 -0
- package/src/core/compose.js +1 -2
- package/src/core/dockerCompose.test.js +5 -5
- package/src/core/jobQueue.js +29 -12
- package/src/core/mcp.js +120 -10
- package/src/core/mcp.test.js +121 -1
- package/src/core/plan.js +33 -0
- package/src/core/queueStore.test.js +1 -0
- package/src/core/wikiWorkspace.test.js +24 -0
- package/src/runtime/approvals.js +113 -0
- package/src/runtime/auth.test.js +8 -0
- package/src/runtime/client.js +52 -6
- package/src/runtime/lifecycle.js +27 -3
- package/src/runtime/queueStore.js +3 -3
- package/src/runtime/runner.js +340 -0
- package/src/runtime/runner.test.js +270 -0
- package/src/runtime/server.js +85 -29
- package/src/runtime/server.test.js +255 -0
- package/src/runtime/store.js +178 -39
- package/src/runtime/store.test.js +338 -4
- package/src/runtime/supervisor.js +6 -0
- package/src/runtime/supervisor.test.js +141 -0
- package/src/shell/RightPane.tsx +1 -1
- package/src/shell/repl.js +22 -6
- package/src/shell/useAgent.ts +1 -1
- package/src/shell/useSession.ts +10 -5
- package/wiki-workspace +198 -4
|
@@ -22,7 +22,9 @@ test('reduceAgentEvents: run_started clears stale plan', () => {
|
|
|
22
22
|
}),
|
|
23
23
|
createAgentEvent('run_started', { origin: 'user' }),
|
|
24
24
|
]);
|
|
25
|
-
assert.equal(projection.plan,
|
|
25
|
+
assert.equal(projection.plan.length, 3);
|
|
26
|
+
assert.equal(projection.plan[0].description, 'Analyze the request');
|
|
27
|
+
assert.equal(projection.plan[0].owner, 'orchestrator');
|
|
26
28
|
assert.equal(projection.activities.length, 0);
|
|
27
29
|
assert.equal(projection.status, 'running');
|
|
28
30
|
});
|
|
@@ -67,7 +69,7 @@ test('reduceAgentEvents: activity with plan creates visible plan and progress',
|
|
|
67
69
|
assert.equal(projection.plan[1].status, 'pending');
|
|
68
70
|
});
|
|
69
71
|
|
|
70
|
-
test('reduceAgentEvents:
|
|
72
|
+
test('reduceAgentEvents: activity attaches to orchestrator plan without replacing it', () => {
|
|
71
73
|
const projection = reduceAgentEvents([
|
|
72
74
|
createAgentEvent('plan_set', {
|
|
73
75
|
origin: 'tool',
|
|
@@ -87,8 +89,147 @@ test('reduceAgentEvents: real activity replaces minimal MCP plan', () => {
|
|
|
87
89
|
}),
|
|
88
90
|
]);
|
|
89
91
|
assert.equal(projection.plan.length, 1);
|
|
90
|
-
assert.equal(projection.plan[0].description, '
|
|
91
|
-
assert.equal(projection.plan[0].
|
|
92
|
+
assert.equal(projection.plan[0].description, 'cme.cme_export_run');
|
|
93
|
+
assert.equal(projection.plan[0].owner, 'orchestrator');
|
|
94
|
+
assert.equal(projection.plan[0].activityKey, 'cme:export-1');
|
|
95
|
+
assert.equal(projection.plan[0].ownerActivityKey, 'cme:export-1');
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('reduceAgentEvents: run activity attaches to execution step of default plan', () => {
|
|
99
|
+
const projection = reduceAgentEvents([
|
|
100
|
+
createAgentEvent('run_started', { origin: 'runtime' }),
|
|
101
|
+
createAgentEvent('activity_upserted', {
|
|
102
|
+
origin: 'tool',
|
|
103
|
+
payload: {
|
|
104
|
+
activity: {
|
|
105
|
+
key: 'production:build-1',
|
|
106
|
+
id: 'build-1',
|
|
107
|
+
source: 'production',
|
|
108
|
+
label: 'Production build',
|
|
109
|
+
status: 'running',
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
}),
|
|
113
|
+
]);
|
|
114
|
+
|
|
115
|
+
assert.equal(projection.plan[0].status, 'done');
|
|
116
|
+
assert.equal(projection.plan[1].status, 'running');
|
|
117
|
+
assert.equal(projection.plan[1].activityKey, 'production:build-1');
|
|
118
|
+
assert.equal(projection.plan[2].status, 'pending');
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('reduceAgentEvents: run_done finalizes running and pending plan steps', () => {
|
|
122
|
+
const projection = reduceAgentEvents([
|
|
123
|
+
createAgentEvent('run_started', { origin: 'runtime' }),
|
|
124
|
+
createAgentEvent('run_done', { origin: 'runtime' }),
|
|
125
|
+
]);
|
|
126
|
+
|
|
127
|
+
assert.deepEqual(projection.plan.map((step) => step.status), ['done', 'done', 'done']);
|
|
128
|
+
assert.equal(projection.status, 'done');
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('dispatchAgentEvent: run_done finalizes session plan', () => {
|
|
132
|
+
const session = {};
|
|
133
|
+
dispatchAgentEvent(session, createAgentEvent('run_started', { origin: 'runtime' }));
|
|
134
|
+
dispatchAgentEvent(session, createAgentEvent('run_done', { origin: 'runtime' }));
|
|
135
|
+
|
|
136
|
+
assert.deepEqual(session.headlessPlan.map((step) => step.status), ['done', 'done', 'done']);
|
|
137
|
+
assert.equal(session.agentProjection.status, 'done');
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test('reduceAgentEvents: run_evaluated exposes evaluator verdict', () => {
|
|
141
|
+
const projection = reduceAgentEvents([
|
|
142
|
+
createAgentEvent('run_started', { origin: 'runtime', runId: 'run-1' }),
|
|
143
|
+
createAgentEvent('run_evaluated', {
|
|
144
|
+
origin: 'runtime',
|
|
145
|
+
runId: 'run-1',
|
|
146
|
+
payload: {
|
|
147
|
+
ok: false,
|
|
148
|
+
reason: 'Missing export.',
|
|
149
|
+
suggestedAction: 'Run export step.',
|
|
150
|
+
},
|
|
151
|
+
}),
|
|
152
|
+
]);
|
|
153
|
+
|
|
154
|
+
assert.deepEqual(projection.evaluation, {
|
|
155
|
+
ok: false,
|
|
156
|
+
reason: 'Missing export.',
|
|
157
|
+
suggestedAction: 'Run export step.',
|
|
158
|
+
runId: 'run-1',
|
|
159
|
+
});
|
|
160
|
+
assert.equal(projection.status, 'running');
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test('reduceAgentEvents: run_replanned records replan trace', () => {
|
|
164
|
+
const projection = reduceAgentEvents([
|
|
165
|
+
createAgentEvent('run_started', { origin: 'runtime', runId: 'run-1' }),
|
|
166
|
+
createAgentEvent('run_replanned', {
|
|
167
|
+
origin: 'runtime',
|
|
168
|
+
runId: 'run-1',
|
|
169
|
+
payload: {
|
|
170
|
+
reason: 'Export file missing.',
|
|
171
|
+
plan: ['Run export again'],
|
|
172
|
+
replansLeft: 1,
|
|
173
|
+
},
|
|
174
|
+
}),
|
|
175
|
+
]);
|
|
176
|
+
|
|
177
|
+
assert.deepEqual(projection.replans, [{
|
|
178
|
+
reason: 'Export file missing.',
|
|
179
|
+
plan: ['Run export again'],
|
|
180
|
+
replansLeft: 1,
|
|
181
|
+
runId: 'run-1',
|
|
182
|
+
}]);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
test('reduceAgentEvents: approvals move from pending to approved', () => {
|
|
186
|
+
const projection = reduceAgentEvents([
|
|
187
|
+
createAgentEvent('run_pending_approval', {
|
|
188
|
+
origin: 'runtime',
|
|
189
|
+
runId: 'run-1',
|
|
190
|
+
payload: {
|
|
191
|
+
approvalId: 'approval-1',
|
|
192
|
+
runId: 'run-1',
|
|
193
|
+
reason: 'Approve plan.',
|
|
194
|
+
plan: ['Build'],
|
|
195
|
+
},
|
|
196
|
+
}),
|
|
197
|
+
createAgentEvent('run_approved', {
|
|
198
|
+
origin: 'runtime',
|
|
199
|
+
runId: 'run-1',
|
|
200
|
+
payload: {
|
|
201
|
+
approvalId: 'approval-1',
|
|
202
|
+
runId: 'run-1',
|
|
203
|
+
},
|
|
204
|
+
}),
|
|
205
|
+
]);
|
|
206
|
+
|
|
207
|
+
assert.equal(projection.approvals.length, 1);
|
|
208
|
+
assert.equal(projection.approvals[0].status, 'approved');
|
|
209
|
+
assert.equal(projection.approvals[0].scope, 'run');
|
|
210
|
+
assert.deepEqual(projection.approvals[0].plan, ['Build']);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test('reduceAgentEvents: activity-owned plan is used when no orchestrator plan exists', () => {
|
|
214
|
+
const projection = reduceAgentEvents([
|
|
215
|
+
createAgentEvent('activity_upserted', {
|
|
216
|
+
origin: 'tool',
|
|
217
|
+
payload: {
|
|
218
|
+
activity: {
|
|
219
|
+
key: 'production:job-1',
|
|
220
|
+
id: 'job-1',
|
|
221
|
+
source: 'production',
|
|
222
|
+
label: 'Production build',
|
|
223
|
+
status: 'running',
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
}),
|
|
227
|
+
]);
|
|
228
|
+
|
|
229
|
+
assert.equal(projection.plan.length, 1);
|
|
230
|
+
assert.equal(projection.plan[0].description, 'Production build');
|
|
231
|
+
assert.equal(projection.plan[0].owner, 'activity');
|
|
232
|
+
assert.equal(projection.plan[0].ownerActivityKey, 'production:job-1');
|
|
92
233
|
});
|
|
93
234
|
|
|
94
235
|
test('dispatchAgentEvent: writes compatibility projections to session', () => {
|
package/src/core/agentLoop.js
CHANGED
|
@@ -72,6 +72,9 @@ export async function runAgenticLoop(agent, session, initialInput, {
|
|
|
72
72
|
|
|
73
73
|
for (let turn = 1; turn <= maxTurns; turn += 1) {
|
|
74
74
|
throwIfAborted(signal, abortMessage);
|
|
75
|
+
if (session._currentRunIdentity && runId) {
|
|
76
|
+
session._currentRunIdentity.turnId = `${runId}:turn-${turn}`;
|
|
77
|
+
}
|
|
75
78
|
onTurnStart?.({ turn, maxTurns });
|
|
76
79
|
|
|
77
80
|
const snapshot = activitySnapshot(session);
|
package/src/core/compose.js
CHANGED
|
@@ -9,7 +9,7 @@ import { managerRoot } from './workspaces.js';
|
|
|
9
9
|
|
|
10
10
|
const execFileAsync = promisify(execFile);
|
|
11
11
|
|
|
12
|
-
export const COMPOSE_SERVICES = ['serve', 'mcp-http', '
|
|
12
|
+
export const COMPOSE_SERVICES = ['serve', 'mcp-http', 'production-mcp'];
|
|
13
13
|
const SERVICE_DESCRIPTION_LABEL = 'wiki-manager.description';
|
|
14
14
|
|
|
15
15
|
const DEFAULT_SERVICE_ALIASES = {
|
|
@@ -17,7 +17,6 @@ const DEFAULT_SERVICE_ALIASES = {
|
|
|
17
17
|
ui: ['serve'],
|
|
18
18
|
wiki: ['mcp-http'],
|
|
19
19
|
mcp: ['mcp-http'],
|
|
20
|
-
runtime: ['agent-runtime'],
|
|
21
20
|
production: ['production-mcp'],
|
|
22
21
|
};
|
|
23
22
|
|
|
@@ -3,12 +3,12 @@ import { test } from 'node:test';
|
|
|
3
3
|
import assert from 'node:assert/strict';
|
|
4
4
|
import YAML from 'yaml';
|
|
5
5
|
|
|
6
|
-
test('
|
|
6
|
+
test('workspace compose does not start a per-workspace agent runtime', async () => {
|
|
7
7
|
const raw = await readFile(new URL('../../docker-compose.yml', import.meta.url), 'utf8');
|
|
8
8
|
const compose = YAML.parse(raw);
|
|
9
|
-
const
|
|
9
|
+
const aliases = compose['x-wiki-manager']['service-aliases'];
|
|
10
10
|
|
|
11
|
-
assert.equal(
|
|
12
|
-
assert.
|
|
13
|
-
assert.
|
|
11
|
+
assert.equal(compose.services['agent-runtime'], undefined);
|
|
12
|
+
assert.deepEqual(aliases.all.targets, ['serve', 'mcp-http', 'production-mcp']);
|
|
13
|
+
assert.equal(aliases.runtime, undefined);
|
|
14
14
|
});
|
package/src/core/jobQueue.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
1
2
|
import { extractActivity, parseJsonText, sessionActivities } from './activity.js';
|
|
2
3
|
import { createAgentEvent, dispatchAgentEvent } from './agentEvents.js';
|
|
3
4
|
import { callMcpTool, formatMcpToolResult } from './mcp.js';
|
|
@@ -14,7 +15,7 @@ function notifyQueueUpdate(session) {
|
|
|
14
15
|
}
|
|
15
16
|
|
|
16
17
|
function shortId() {
|
|
17
|
-
return `q-${
|
|
18
|
+
return `q-${randomUUID()}`;
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
function terminalStatus(status) {
|
|
@@ -61,17 +62,33 @@ export function queueSummary(args = {}) {
|
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
export function queueCounts(session) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
65
|
+
const queue = projectQueue(session.headlessPlan, ensureJobQueue(session), { workspace: session.workspace ?? null });
|
|
66
|
+
return {
|
|
67
|
+
active: queue.length,
|
|
68
|
+
current: queue.filter((item) => item.workspace === session.workspace || !item.workspace).length,
|
|
69
|
+
frozen: queue.filter((item) => item.workspace && item.workspace !== session.workspace).length,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function projectQueue(plan, queue, { workspace = null } = {}) {
|
|
74
|
+
const blockedJobs = (queue ?? [])
|
|
75
|
+
.filter((item) => ['waiting', 'blocked', 'pending_approval'].includes(String(item.status ?? '').toLowerCase()))
|
|
76
|
+
.map((item) => ({
|
|
77
|
+
...item,
|
|
78
|
+
queueType: 'blocked_job',
|
|
79
|
+
}));
|
|
80
|
+
const pendingSteps = (plan ?? [])
|
|
81
|
+
.filter((step) => step.status === 'pending')
|
|
82
|
+
.map((step) => ({
|
|
83
|
+
id: `plan-${step.step}`,
|
|
84
|
+
queueType: 'pending_step',
|
|
85
|
+
status: 'pending',
|
|
86
|
+
workspace,
|
|
87
|
+
step: step.step,
|
|
88
|
+
activityKey: step.activityKey ?? step.ownerActivityKey ?? undefined,
|
|
89
|
+
args: { type: step.description },
|
|
90
|
+
}));
|
|
91
|
+
return [...blockedJobs, ...pendingSteps];
|
|
75
92
|
}
|
|
76
93
|
|
|
77
94
|
export function formatQueue(session) {
|
package/src/core/mcp.js
CHANGED
|
@@ -70,11 +70,28 @@ function endpointStatus(configured, detail = '') {
|
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
function approvalToolsFor(serverName) {
|
|
74
|
+
const raw = envValue('WIKI_MANAGER_REQUIRE_APPROVAL_TOOLS');
|
|
75
|
+
if (!raw) return undefined;
|
|
76
|
+
const tools = String(raw)
|
|
77
|
+
.split(',')
|
|
78
|
+
.map((item) => item.trim())
|
|
79
|
+
.filter(Boolean)
|
|
80
|
+
.filter((item) => item === '*' || item.startsWith(`${serverName}.`) || !item.includes('.'))
|
|
81
|
+
.map((item) => item.startsWith(`${serverName}.`) ? item.slice(serverName.length + 1) : item);
|
|
82
|
+
return tools.length > 0 ? tools : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
73
85
|
const MCP_SERVICE_MAP = {
|
|
74
86
|
wiki: 'mcp-http',
|
|
75
87
|
production: 'production-mcp',
|
|
76
88
|
};
|
|
77
89
|
|
|
90
|
+
const DEFAULT_MCP_RETRY_POLICY = {
|
|
91
|
+
maxAttempts: 2,
|
|
92
|
+
backoffMs: 500,
|
|
93
|
+
};
|
|
94
|
+
|
|
78
95
|
export function buildMcpStatus(session) {
|
|
79
96
|
const workspaceEnv = session.workspaceEnv ?? {};
|
|
80
97
|
const wikiMcpToken = session.wikircConfig?.mcp?.accessKey;
|
|
@@ -91,6 +108,7 @@ export function buildMcpStatus(session) {
|
|
|
91
108
|
),
|
|
92
109
|
url: workspaceEnv.WIKI_MCP_PORT ? `http://127.0.0.1:${workspaceEnv.WIKI_MCP_PORT}/mcp` : null,
|
|
93
110
|
token: wikiMcpToken || null,
|
|
111
|
+
requireApproval: approvalToolsFor('wiki'),
|
|
94
112
|
},
|
|
95
113
|
production: {
|
|
96
114
|
...endpointStatus(
|
|
@@ -100,6 +118,7 @@ export function buildMcpStatus(session) {
|
|
|
100
118
|
url: workspaceEnv.PRODUCTION_MCP_PORT ? `http://127.0.0.1:${workspaceEnv.PRODUCTION_MCP_PORT}/mcp/` : null,
|
|
101
119
|
token: workspaceEnv.PRODUCTION_MCP_AUTH_TOKEN || null,
|
|
102
120
|
activeConfigPath: session.wikirc?.fileName || null,
|
|
121
|
+
requireApproval: approvalToolsFor('production'),
|
|
103
122
|
},
|
|
104
123
|
...external,
|
|
105
124
|
};
|
|
@@ -211,7 +230,7 @@ async function mcpRequest(endpoint, method, params, signal, options = {}) {
|
|
|
211
230
|
params: {
|
|
212
231
|
protocolVersion: '2025-06-18',
|
|
213
232
|
capabilities: {},
|
|
214
|
-
clientInfo: { name: 'wiki-manager', version: '0.
|
|
233
|
+
clientInfo: { name: 'wiki-manager', version: '0.8.2' },
|
|
215
234
|
},
|
|
216
235
|
}),
|
|
217
236
|
});
|
|
@@ -240,7 +259,7 @@ async function mcpRequest(endpoint, method, params, signal, options = {}) {
|
|
|
240
259
|
}
|
|
241
260
|
}
|
|
242
261
|
|
|
243
|
-
export async function callMcpTool(mcpStatus, serverName, toolName, args = {}, signal) {
|
|
262
|
+
export async function callMcpTool(mcpStatus, serverName, toolName, args = {}, signal, options = {}) {
|
|
244
263
|
const endpoint = mcpStatus?.[serverName];
|
|
245
264
|
if (!endpoint) throw new Error(`Unknown MCP: ${serverName}`);
|
|
246
265
|
if (endpoint.status !== 'connected') throw new Error(`MCP is not connected: ${serverName}`);
|
|
@@ -254,14 +273,17 @@ export async function callMcpTool(mcpStatus, serverName, toolName, args = {}, si
|
|
|
254
273
|
...(shouldInjectConfigPath ? { configPath: endpoint.activeConfigPath } : {}),
|
|
255
274
|
};
|
|
256
275
|
const timeoutMs = serverName === 'documents' && toolName === 'documents_convert_to_markdown' ? 600_000 : 8000;
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
276
|
+
const retry = resolveRetryPolicy(endpoint, toolName, options.retry);
|
|
277
|
+
return withRetry(async () => {
|
|
278
|
+
const payload = await mcpRequest(endpoint, 'tools/call', {
|
|
279
|
+
name: toolName,
|
|
280
|
+
arguments: toolArgs,
|
|
281
|
+
}, signal, { timeoutMs });
|
|
282
|
+
if (payload?.result?.isError) {
|
|
283
|
+
throw new Error(formatMcpToolResult(payload.result));
|
|
284
|
+
}
|
|
285
|
+
return payload?.result ?? null;
|
|
286
|
+
}, retry, { signal, onRetry: options.onRetry });
|
|
265
287
|
}
|
|
266
288
|
|
|
267
289
|
export function formatMcpToolResult(result) {
|
|
@@ -278,6 +300,94 @@ export function formatMcpToolResult(result) {
|
|
|
278
300
|
.trim() || 'No result.';
|
|
279
301
|
}
|
|
280
302
|
|
|
303
|
+
let _cachedEnvRetryPolicy = null;
|
|
304
|
+
function getEnvRetryPolicy() {
|
|
305
|
+
if (!_cachedEnvRetryPolicy) {
|
|
306
|
+
_cachedEnvRetryPolicy = {
|
|
307
|
+
maxAttempts: numberFromEnv('WIKI_MANAGER_MCP_RETRY_MAX_ATTEMPTS')
|
|
308
|
+
?? numberFromEnv('WIKI_MANAGER_MCP_RETRY_ATTEMPTS')
|
|
309
|
+
?? DEFAULT_MCP_RETRY_POLICY.maxAttempts,
|
|
310
|
+
backoffMs: numberFromEnv('WIKI_MANAGER_MCP_RETRY_BACKOFF_MS')
|
|
311
|
+
?? DEFAULT_MCP_RETRY_POLICY.backoffMs,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
return _cachedEnvRetryPolicy;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function resolveRetryPolicy(endpoint = {}, toolName = null, override = null) {
|
|
318
|
+
const toolPolicy = toolName ? endpoint.toolRetries?.[toolName] : null;
|
|
319
|
+
return normalizeRetryPolicy(getEnvRetryPolicy(), endpoint.retry, toolPolicy, override);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function normalizeRetryPolicy(...policies) {
|
|
323
|
+
const merged = {};
|
|
324
|
+
for (const policy of policies) {
|
|
325
|
+
if (policy === false) {
|
|
326
|
+
merged.maxAttempts = 1;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (!policy || typeof policy !== 'object') continue;
|
|
330
|
+
if (policy.maxAttempts != null) merged.maxAttempts = Number(policy.maxAttempts);
|
|
331
|
+
if (policy.backoffMs != null) merged.backoffMs = Number(policy.backoffMs);
|
|
332
|
+
}
|
|
333
|
+
const maxAttempts = Number.isFinite(merged.maxAttempts)
|
|
334
|
+
? Math.max(1, Math.floor(merged.maxAttempts))
|
|
335
|
+
: DEFAULT_MCP_RETRY_POLICY.maxAttempts;
|
|
336
|
+
const backoffMs = Number.isFinite(merged.backoffMs)
|
|
337
|
+
? Math.max(0, Math.floor(merged.backoffMs))
|
|
338
|
+
: DEFAULT_MCP_RETRY_POLICY.backoffMs;
|
|
339
|
+
return { maxAttempts, backoffMs };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function numberFromEnv(key) {
|
|
343
|
+
const raw = envValue(key);
|
|
344
|
+
if (raw == null || raw === '') return null;
|
|
345
|
+
const value = Number(raw);
|
|
346
|
+
return Number.isFinite(value) ? value : null;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function withRetry(operation, policy, { signal = null, onRetry = null } = {}) {
|
|
350
|
+
let lastError;
|
|
351
|
+
for (let attempt = 1; attempt <= policy.maxAttempts; attempt += 1) {
|
|
352
|
+
try {
|
|
353
|
+
return await operation({ attempt });
|
|
354
|
+
} catch (err) {
|
|
355
|
+
lastError = err;
|
|
356
|
+
if (attempt >= policy.maxAttempts || signal?.aborted) throw err;
|
|
357
|
+
onRetry?.({ attempt, maxAttempts: policy.maxAttempts, error: err });
|
|
358
|
+
await retryDelay(policy.backoffMs * (2 ** (attempt - 1)), signal);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
throw lastError;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function retryDelay(ms, signal) {
|
|
365
|
+
if (ms <= 0) return Promise.resolve();
|
|
366
|
+
return new Promise((resolve, reject) => {
|
|
367
|
+
let timer = null;
|
|
368
|
+
const cleanup = () => {
|
|
369
|
+
if (timer) clearTimeout(timer);
|
|
370
|
+
signal?.removeEventListener('abort', onAbort);
|
|
371
|
+
};
|
|
372
|
+
const onAbort = () => {
|
|
373
|
+
cleanup();
|
|
374
|
+
const err = new Error('Operation aborted.');
|
|
375
|
+
err.name = 'AbortError';
|
|
376
|
+
reject(err);
|
|
377
|
+
};
|
|
378
|
+
timer = setTimeout(() => {
|
|
379
|
+
cleanup();
|
|
380
|
+
resolve();
|
|
381
|
+
}, ms);
|
|
382
|
+
if (!signal) return;
|
|
383
|
+
if (signal.aborted) {
|
|
384
|
+
onAbort();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
281
391
|
export async function discoverMcpTools(mcpStatus) {
|
|
282
392
|
const next = {};
|
|
283
393
|
await Promise.all(Object.entries(mcpStatus ?? {}).map(async ([name, value]) => {
|
package/src/core/mcp.test.js
CHANGED
|
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
|
|
3
3
|
import { mkdtemp, writeFile } from 'node:fs/promises';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { buildMcpStatus, callMcpTool, discoverMcpTools } from './mcp.js';
|
|
6
|
+
import { buildMcpStatus, callMcpTool, discoverMcpTools, resolveRetryPolicy } from './mcp.js';
|
|
7
7
|
|
|
8
8
|
test('buildMcpStatus reads external MCP endpoints from mcp.endpoints.json', async () => {
|
|
9
9
|
const originalCwd = process.cwd();
|
|
@@ -163,6 +163,29 @@ test('buildMcpStatus uses active wikirc mcp.accessKey for wiki MCP', () => {
|
|
|
163
163
|
assert.equal(status.wiki.token, 'wikirc-wiki-token');
|
|
164
164
|
});
|
|
165
165
|
|
|
166
|
+
test('buildMcpStatus applies internal tool approval policy from env', () => {
|
|
167
|
+
const original = process.env.WIKI_MANAGER_REQUIRE_APPROVAL_TOOLS;
|
|
168
|
+
process.env.WIKI_MANAGER_REQUIRE_APPROVAL_TOOLS = 'production.production_start_job,wiki.wiki_search';
|
|
169
|
+
try {
|
|
170
|
+
const status = buildMcpStatus({
|
|
171
|
+
workspaceEnv: {
|
|
172
|
+
PRODUCTION_MCP_PORT: '3102',
|
|
173
|
+
PRODUCTION_MCP_AUTH_TOKEN: 'production-token',
|
|
174
|
+
WIKI_MCP_PORT: '3101',
|
|
175
|
+
},
|
|
176
|
+
wikircConfig: {
|
|
177
|
+
mcp: { accessKey: 'wiki-token' },
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
assert.deepEqual(status.production.requireApproval, ['production_start_job']);
|
|
182
|
+
assert.deepEqual(status.wiki.requireApproval, ['wiki_search']);
|
|
183
|
+
} finally {
|
|
184
|
+
if (original === undefined) delete process.env.WIKI_MANAGER_REQUIRE_APPROVAL_TOOLS;
|
|
185
|
+
else process.env.WIKI_MANAGER_REQUIRE_APPROVAL_TOOLS = original;
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
166
189
|
test('callMcpTool injects active configPath for production_start_job', async () => {
|
|
167
190
|
const originalFetch = globalThis.fetch;
|
|
168
191
|
let requestBody = null;
|
|
@@ -269,6 +292,103 @@ test('callMcpTool sends configured endpoint headers', async () => {
|
|
|
269
292
|
}
|
|
270
293
|
});
|
|
271
294
|
|
|
295
|
+
test('callMcpTool retries transient MCP failures', async () => {
|
|
296
|
+
const originalFetch = globalThis.fetch;
|
|
297
|
+
let attempts = 0;
|
|
298
|
+
const retries = [];
|
|
299
|
+
globalThis.fetch = async () => {
|
|
300
|
+
attempts += 1;
|
|
301
|
+
if (attempts === 1) {
|
|
302
|
+
return {
|
|
303
|
+
ok: false,
|
|
304
|
+
status: 503,
|
|
305
|
+
headers: { get: () => null },
|
|
306
|
+
text: async () => 'temporarily unavailable',
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
ok: true,
|
|
311
|
+
status: 200,
|
|
312
|
+
headers: { get: () => null },
|
|
313
|
+
text: async () => JSON.stringify({ result: { content: [{ type: 'text', text: '{"ok":true}' }] } }),
|
|
314
|
+
};
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
try {
|
|
318
|
+
const result = await callMcpTool(
|
|
319
|
+
{
|
|
320
|
+
production: {
|
|
321
|
+
status: 'connected',
|
|
322
|
+
url: 'http://127.0.0.1:3000/mcp/',
|
|
323
|
+
retry: { maxAttempts: 2, backoffMs: 0 },
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
'production',
|
|
327
|
+
'production_start_job',
|
|
328
|
+
{ type: 'doctor' },
|
|
329
|
+
null,
|
|
330
|
+
{ onRetry: (event) => retries.push(event) },
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
assert.equal(attempts, 2);
|
|
334
|
+
assert.equal(retries.length, 1);
|
|
335
|
+
assert.match(retries[0].error.message, /503/);
|
|
336
|
+
assert.equal(result.content[0].text, '{"ok":true}');
|
|
337
|
+
} finally {
|
|
338
|
+
globalThis.fetch = originalFetch;
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
test('callMcpTool retries tool result errors', async () => {
|
|
343
|
+
const originalFetch = globalThis.fetch;
|
|
344
|
+
let attempts = 0;
|
|
345
|
+
globalThis.fetch = async () => {
|
|
346
|
+
attempts += 1;
|
|
347
|
+
return {
|
|
348
|
+
ok: true,
|
|
349
|
+
status: 200,
|
|
350
|
+
headers: { get: () => null },
|
|
351
|
+
text: async () => JSON.stringify({
|
|
352
|
+
result: attempts === 1
|
|
353
|
+
? { isError: true, content: [{ type: 'text', text: 'rate limited' }] }
|
|
354
|
+
: { content: [{ type: 'text', text: '{"ok":true}' }] },
|
|
355
|
+
}),
|
|
356
|
+
};
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
try {
|
|
360
|
+
const result = await callMcpTool(
|
|
361
|
+
{
|
|
362
|
+
production: {
|
|
363
|
+
status: 'connected',
|
|
364
|
+
url: 'http://127.0.0.1:3000/mcp/',
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
'production',
|
|
368
|
+
'production_start_job',
|
|
369
|
+
{ type: 'doctor' },
|
|
370
|
+
null,
|
|
371
|
+
{ retry: { maxAttempts: 2, backoffMs: 0 } },
|
|
372
|
+
);
|
|
373
|
+
|
|
374
|
+
assert.equal(attempts, 2);
|
|
375
|
+
assert.equal(result.content[0].text, '{"ok":true}');
|
|
376
|
+
} finally {
|
|
377
|
+
globalThis.fetch = originalFetch;
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
test('resolveRetryPolicy supports endpoint and tool overrides', () => {
|
|
382
|
+
const policy = resolveRetryPolicy({
|
|
383
|
+
retry: { maxAttempts: 2, backoffMs: 100 },
|
|
384
|
+
toolRetries: {
|
|
385
|
+
production_start_job: { maxAttempts: 4 },
|
|
386
|
+
},
|
|
387
|
+
}, 'production_start_job');
|
|
388
|
+
|
|
389
|
+
assert.deepEqual(policy, { maxAttempts: 4, backoffMs: 100 });
|
|
390
|
+
});
|
|
391
|
+
|
|
272
392
|
test('discoverMcpTools downgrades connected endpoint when tool discovery fails', async () => {
|
|
273
393
|
const originalFetch = globalThis.fetch;
|
|
274
394
|
globalThis.fetch = async () => ({
|
package/src/core/plan.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
export function ensurePlanFromActivity(session, activity) {
|
|
2
2
|
if (!activity) return;
|
|
3
3
|
const actKey = activity.key ?? null;
|
|
4
|
+
if (session.headlessPlan?.some((step) => step.owner === 'orchestrator')) {
|
|
5
|
+
attachActivityToExistingPlan(session.headlessPlan, activity);
|
|
6
|
+
session._onPlanUpdate?.();
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
4
9
|
// Same activity still being tracked — preserve current plan state (polling update).
|
|
5
10
|
if (session.headlessPlan && actKey !== null && session.headlessPlan[0]?._activityKey === actKey) return;
|
|
6
11
|
const steps = activity.plan?.steps;
|
|
@@ -10,6 +15,8 @@ export function ensurePlanFromActivity(session, activity) {
|
|
|
10
15
|
id: s.id ?? null,
|
|
11
16
|
description: s.label,
|
|
12
17
|
status: 'pending',
|
|
18
|
+
owner: 'activity',
|
|
19
|
+
ownerActivityKey: activity.key,
|
|
13
20
|
_activityKey: activity.key,
|
|
14
21
|
}));
|
|
15
22
|
} else {
|
|
@@ -18,6 +25,8 @@ export function ensurePlanFromActivity(session, activity) {
|
|
|
18
25
|
id: null,
|
|
19
26
|
description: activity.label,
|
|
20
27
|
status: 'pending',
|
|
28
|
+
owner: 'activity',
|
|
29
|
+
ownerActivityKey: activity.key,
|
|
21
30
|
_activityKey: activity.key,
|
|
22
31
|
}];
|
|
23
32
|
}
|
|
@@ -179,3 +188,27 @@ function statusRank(status) {
|
|
|
179
188
|
if (status === 'done') return 2;
|
|
180
189
|
return 3;
|
|
181
190
|
}
|
|
191
|
+
|
|
192
|
+
export function attachActivityToExistingPlan(plan, activity) {
|
|
193
|
+
const actKey = activity.key ?? activity.id ?? activity.jobId ?? null;
|
|
194
|
+
if (!actKey) return;
|
|
195
|
+
const matched = plan.find((step) => step.activityKey === actKey)
|
|
196
|
+
?? plan.find((step) => step.ownerActivityKey === actKey)
|
|
197
|
+
?? plan.find((step) => step.status === 'pending')
|
|
198
|
+
?? plan.find((step) => step.status === 'running');
|
|
199
|
+
if (!matched) return;
|
|
200
|
+
matched.activityKey = actKey;
|
|
201
|
+
if (!matched.ownerActivityKey) matched.ownerActivityKey = actKey;
|
|
202
|
+
const failed = ['failed', 'error', 'cancelled', 'canceled'].includes(String(activity.status).toLowerCase());
|
|
203
|
+
if (activity.terminal) {
|
|
204
|
+
matched.status = failed ? 'failed' : 'done';
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (!failed) {
|
|
208
|
+
for (const step of plan) {
|
|
209
|
+
if (step.status === 'failed') continue;
|
|
210
|
+
if (step.step < matched.step) step.status = 'done';
|
|
211
|
+
else if (step.step === matched.step) step.status = 'running';
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -25,6 +25,7 @@ test('job queue uses an injected queue store', () => {
|
|
|
25
25
|
const item = enqueueProductionJob(session, { type: 'build' }, 'workspace_busy');
|
|
26
26
|
|
|
27
27
|
assert.equal(item.workspace, 'docs');
|
|
28
|
+
assert.match(item.id, /^q-[0-9a-f-]{36}$/);
|
|
28
29
|
assert.equal(queue.length, 1);
|
|
29
30
|
assert.equal(ensureJobQueue(session), queue);
|
|
30
31
|
assert.equal(changed, 1);
|