claude-flow 3.77.0 → 3.77.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/.claude/helpers/hook-handler.cjs +85 -5
- package/README.md +12 -2
- package/node_modules/@claude-flow/plugin-agent-federation/README.md +18 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.d.ts +4 -1
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.d.ts.map +1 -1
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js +11 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js.map +1 -1
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.d.ts +29 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.d.ts.map +1 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.js +96 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.js.map +1 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.d.ts.map +1 -1
- package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.js +3 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.js.map +1 -1
- package/package.json +8 -5
- package/v3/@claude-flow/cli/README.md +5 -0
- package/v3/@claude-flow/cli/bin/cli.js +8 -3
- package/v3/@claude-flow/cli/dist/src/commands/init.js +8 -1
- package/v3/@claude-flow/cli/dist/src/commands/session.js +2 -1
- package/v3/@claude-flow/cli/dist/src/commands/workflow.js +2 -1
- package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +85 -5
- package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.js +26 -25
- package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +161 -157
- package/v3/@claude-flow/cli/dist/src/mcp-tools/claims-tools.js +257 -258
- package/v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.js +48 -29
- package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +6 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/locked-json-store.d.ts +20 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/locked-json-store.js +99 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/managed-agent-tools.js +51 -7
- package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +19 -9
- package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.js +299 -270
- package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.js +245 -215
- package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +29 -4
- package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +5 -4
- package/v3/@claude-flow/cli/dist/src/services/managed-run-store.d.ts +11 -0
- package/v3/@claude-flow/cli/dist/src/services/managed-run-store.js +125 -3
- package/v3/@claude-flow/cli/dist/src/services/policy-runtime.d.ts +3 -0
- package/v3/@claude-flow/cli/dist/src/services/policy-runtime.js +3 -1
- package/v3/@claude-flow/cli/package.json +11 -8
- package/v3/@claude-flow/guidance/package.json +1 -0
- package/.claude/.proven-config-version +0 -1
- package/.claude/proven-config.json +0 -42
|
@@ -9,6 +9,7 @@ import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
|
|
|
9
9
|
import { getProjectCwd } from './types.js';
|
|
10
10
|
import { validateIdentifier, validateText } from './validate-input.js';
|
|
11
11
|
import { readPreservedJsonStore } from './record-store.js';
|
|
12
|
+
import { saved, unchanged, updateJsonStore } from './locked-json-store.js';
|
|
12
13
|
// Storage paths
|
|
13
14
|
const STORAGE_DIR = '.claude-flow';
|
|
14
15
|
const HIVE_DIR = 'hive-mind';
|
|
@@ -259,11 +260,15 @@ function loadAgentStore(storePath = getHiveAgentPath()) {
|
|
|
259
260
|
}
|
|
260
261
|
return store;
|
|
261
262
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
263
|
+
/**
|
|
264
|
+
* #4736: locked read-modify-write of an agent store. `agents.json` and
|
|
265
|
+
* `agents/store.json` are also written by agent-tools, agent-execute-core and
|
|
266
|
+
* task-tools under the same lock (locked-json-store), so every hive-mind write
|
|
267
|
+
* goes through here too: `mutate` sees a fresh read taken inside the lock, and
|
|
268
|
+
* a concurrent agent_spawn or task update is never overwritten by a stale copy.
|
|
269
|
+
*/
|
|
270
|
+
function updateAgentStore(storePath, mutate) {
|
|
271
|
+
return updateJsonStore(storePath, () => loadAgentStore(storePath), mutate, 'agents');
|
|
267
272
|
}
|
|
268
273
|
function findAgent(store, agentId) {
|
|
269
274
|
if (Array.isArray(store.agents))
|
|
@@ -338,7 +343,7 @@ export const hiveMindTools = [
|
|
|
338
343
|
}
|
|
339
344
|
const agentType = input.agentType || 'worker';
|
|
340
345
|
const prefix = input.prefix || 'hive-worker';
|
|
341
|
-
const
|
|
346
|
+
const newAgents = [];
|
|
342
347
|
const spawnedWorkers = [];
|
|
343
348
|
for (let i = 0; i < count; i++) {
|
|
344
349
|
const agentId = `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
|
|
@@ -353,10 +358,7 @@ export const hiveMindTools = [
|
|
|
353
358
|
createdAt: new Date().toISOString(),
|
|
354
359
|
domain: 'hive-mind',
|
|
355
360
|
};
|
|
356
|
-
|
|
357
|
-
agentStore.agents.push(agent);
|
|
358
|
-
else
|
|
359
|
-
agentStore.agents[agentId] = agent;
|
|
361
|
+
newAgents.push(agent);
|
|
360
362
|
// Join to hive-mind (like hive-mind/join)
|
|
361
363
|
if (!state.workers.includes(agentId)) {
|
|
362
364
|
state.workers.push(agentId);
|
|
@@ -367,7 +369,16 @@ export const hiveMindTools = [
|
|
|
367
369
|
joinedAt: new Date().toISOString(),
|
|
368
370
|
});
|
|
369
371
|
}
|
|
370
|
-
|
|
372
|
+
// Add the new records to a fresh read under the store lock.
|
|
373
|
+
await updateAgentStore(getHiveAgentPath(), (agentStore) => {
|
|
374
|
+
for (const agent of newAgents) {
|
|
375
|
+
if (Array.isArray(agentStore.agents))
|
|
376
|
+
agentStore.agents.push(agent);
|
|
377
|
+
else
|
|
378
|
+
agentStore.agents[agent.agentId] = agent;
|
|
379
|
+
}
|
|
380
|
+
return saved(undefined);
|
|
381
|
+
});
|
|
371
382
|
saveHiveState(state);
|
|
372
383
|
return {
|
|
373
384
|
success: true,
|
|
@@ -649,11 +660,7 @@ export const hiveMindTools = [
|
|
|
649
660
|
join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json'),
|
|
650
661
|
getHiveAgentPath(),
|
|
651
662
|
];
|
|
652
|
-
const records = paths.
|
|
653
|
-
const store = loadAgentStore(path);
|
|
654
|
-
const agent = findAgent(store, agentId);
|
|
655
|
-
return agent ? [{ path, store, agent }] : [];
|
|
656
|
-
});
|
|
663
|
+
const records = paths.filter(path => findAgent(loadAgentStore(path), agentId));
|
|
657
664
|
if (records.length === 0) {
|
|
658
665
|
return { success: false, agentId, error: 'Agent not found. Register it with agent_spawn or hive-mind_spawn first.' };
|
|
659
666
|
}
|
|
@@ -661,9 +668,20 @@ export const hiveMindTools = [
|
|
|
661
668
|
if (!HIVE_ROLES.has(role)) {
|
|
662
669
|
return { success: false, agentId, error: `role must be one of: ${[...HIVE_ROLES].join(', ')}` };
|
|
663
670
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
671
|
+
// Re-read each store under its lock: the copy read above may already be
|
|
672
|
+
// stale, and writing it back would drop a concurrent agent_spawn.
|
|
673
|
+
let updated = 0;
|
|
674
|
+
for (const path of records) {
|
|
675
|
+
updated += await updateAgentStore(path, (store) => {
|
|
676
|
+
const agent = findAgent(store, agentId);
|
|
677
|
+
if (!agent)
|
|
678
|
+
return unchanged(0);
|
|
679
|
+
agent.config = { ...agent.config, role, hiveRole: role };
|
|
680
|
+
return saved(1);
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
if (updated === 0) {
|
|
684
|
+
return { success: false, agentId, error: 'Agent not found. Register it with agent_spawn or hive-mind_spawn first.' };
|
|
667
685
|
}
|
|
668
686
|
if (!alreadyJoined) {
|
|
669
687
|
state.workers.push(agentId);
|
|
@@ -1136,18 +1154,19 @@ export const hiveMindTools = [
|
|
|
1136
1154
|
};
|
|
1137
1155
|
}
|
|
1138
1156
|
// Clear workers from agent store
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1157
|
+
await updateAgentStore(getHiveAgentPath(), (agentStore) => {
|
|
1158
|
+
if (Array.isArray(agentStore.agents)) {
|
|
1159
|
+
agentStore.agents = agentStore.agents.filter(agent => !state.workers.includes(agent.agentId));
|
|
1160
|
+
}
|
|
1161
|
+
else {
|
|
1162
|
+
for (const workerId of state.workers) {
|
|
1163
|
+
if (Object.prototype.hasOwnProperty.call(agentStore.agents, workerId)) {
|
|
1164
|
+
delete agentStore.agents[workerId];
|
|
1165
|
+
}
|
|
1147
1166
|
}
|
|
1148
1167
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1168
|
+
return saved(undefined);
|
|
1169
|
+
});
|
|
1151
1170
|
// Reset hive state
|
|
1152
1171
|
const shutdownTime = new Date().toISOString();
|
|
1153
1172
|
const previousQueen = state.queen?.agentId;
|
|
@@ -8,6 +8,8 @@ import * as nodeFs from 'fs';
|
|
|
8
8
|
import { dirname, join, resolve, sep } from 'path';
|
|
9
9
|
import { getProjectCwd } from './types.js';
|
|
10
10
|
import { dispatchQueueDir } from '../services/dispatch-queue.js';
|
|
11
|
+
import { resolveMemoryRoot } from '../memory/memory-root.js';
|
|
12
|
+
import { getProjectRoot } from '../services/project-root.js';
|
|
11
13
|
import { validateIdentifier, validateText, validatePath } from './validate-input.js';
|
|
12
14
|
import { realpathNearest, isInsideRealRoot } from './realpath-containment.js';
|
|
13
15
|
import { commandRecordingDisabled, redactCommandForStorage } from '../services/command-recording.js';
|
|
@@ -319,12 +321,16 @@ async function buildSemanticRouter(kind, selectionReason) {
|
|
|
319
321
|
const router = require('@ruvector/router');
|
|
320
322
|
if (router.VectorDb && router.DistanceMetric) {
|
|
321
323
|
// Try to create VectorDb - may fail with lock error in concurrent envs
|
|
324
|
+
// Native VectorDb otherwise creates ruvector.db in process.cwd().
|
|
325
|
+
const memoryRoot = resolveMemoryRoot(getProjectRoot());
|
|
326
|
+
mkdirSync(memoryRoot, { recursive: true });
|
|
322
327
|
const db = new router.VectorDb({
|
|
323
328
|
dimensions: 384,
|
|
324
329
|
distanceMetric: router.DistanceMetric.Cosine,
|
|
325
330
|
hnswM: 16,
|
|
326
331
|
hnswEfConstruction: 200,
|
|
327
332
|
hnswEfSearch: 100,
|
|
333
|
+
storagePath: join(memoryRoot, 'ruvector.db'),
|
|
328
334
|
});
|
|
329
335
|
// Initialize with static + runtime-learned task patterns
|
|
330
336
|
for (const [patternName, { keywords }] of Object.entries(patterns)) {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface StoreUpdate<R> {
|
|
2
|
+
/** Returned to the caller of updateJsonStore. */
|
|
3
|
+
result: R;
|
|
4
|
+
/** false leaves the file untouched, e.g. for a refused operation. */
|
|
5
|
+
save: boolean;
|
|
6
|
+
}
|
|
7
|
+
/** Save the mutated store and return `result`. */
|
|
8
|
+
export declare function saved<R>(result: R): StoreUpdate<R>;
|
|
9
|
+
/** Return `result` without writing, e.g. for a refused operation. */
|
|
10
|
+
export declare function unchanged<R>(result: R): StoreUpdate<R>;
|
|
11
|
+
/** Lock file guarding `file`. Every writer of a store must use this path. */
|
|
12
|
+
export declare function storeLockPath(file: string): string;
|
|
13
|
+
export declare function updateJsonStore<S, R>(file: string, load: () => S, mutate: (store: S) => StoreUpdate<R>, label: string): Promise<R>;
|
|
14
|
+
/**
|
|
15
|
+
* Overwrite a whole store under its lock, e.g. when session_restore puts back
|
|
16
|
+
* a saved copy. Without the lock, a concurrent locked update that read the
|
|
17
|
+
* file before the restore would write its stale copy over the restored one.
|
|
18
|
+
*/
|
|
19
|
+
export declare function replaceJsonStore(file: string, value: unknown, label: string): Promise<void>;
|
|
20
|
+
//# sourceMappingURL=locked-json-store.d.ts.map
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Locked read-modify-write for the MCP JSON stores (claims, tasks, agents,
|
|
3
|
+
* workflows).
|
|
4
|
+
*
|
|
5
|
+
* Each store used to load the whole file, change it in memory, and write it
|
|
6
|
+
* back with writeFileSync. Two processes (two MCP servers, parallel agents)
|
|
7
|
+
* doing that at once both read the same file, and the last write erased the
|
|
8
|
+
* other's change while both reported success: 4 of 4 racers "won" the same
|
|
9
|
+
* claims_claim, and 8 concurrent task_create calls kept 1 task.
|
|
10
|
+
*
|
|
11
|
+
* updateJsonStore runs load → mutate → save under the store's cross-process
|
|
12
|
+
* lock file, so the mutation always sees the latest data and a check-and-set
|
|
13
|
+
* (an issue is free → claim it) cannot interleave. The lock and the atomic
|
|
14
|
+
* write are the policy runtime's (`acquireLock`, `writeJsonAtomic`), shared
|
|
15
|
+
* rather than copied, as ADR-406 mission storage does.
|
|
16
|
+
*
|
|
17
|
+
* Rules for callers:
|
|
18
|
+
* - Keep `mutate` synchronous. Do slow work (model calls, imports) before
|
|
19
|
+
* the call, then reload and apply the result inside it.
|
|
20
|
+
* - Never wait on updateJsonStore for the same file while a call for it is
|
|
21
|
+
* still running: the turn is not re-entrant, so that wait never ends. Run
|
|
22
|
+
* follow-up writes after the call returns (see task-tools' afterSave).
|
|
23
|
+
*/
|
|
24
|
+
import { mkdirSync } from 'node:fs';
|
|
25
|
+
import { basename, dirname, resolve } from 'node:path';
|
|
26
|
+
import { acquireLock, writeJsonAtomic } from '../services/policy-runtime.js';
|
|
27
|
+
/** Save the mutated store and return `result`. */
|
|
28
|
+
export function saved(result) {
|
|
29
|
+
return { result, save: true };
|
|
30
|
+
}
|
|
31
|
+
/** Return `result` without writing, e.g. for a refused operation. */
|
|
32
|
+
export function unchanged(result) {
|
|
33
|
+
return { result, save: false };
|
|
34
|
+
}
|
|
35
|
+
/** Lock file guarding `file`. Every writer of a store must use this path. */
|
|
36
|
+
export function storeLockPath(file) {
|
|
37
|
+
return `${file}.lock`;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Calls in one process queue here, in order, before taking the lock file.
|
|
41
|
+
* The lock file then only arbitrates between processes, and a call in this
|
|
42
|
+
* process never polls it on a timer while another call here holds it.
|
|
43
|
+
*/
|
|
44
|
+
const queues = new Map();
|
|
45
|
+
async function inProcessTurn(key, run) {
|
|
46
|
+
const previous = queues.get(key) ?? Promise.resolve();
|
|
47
|
+
let finish;
|
|
48
|
+
const mine = previous.then(() => new Promise((done) => { finish = done; }));
|
|
49
|
+
queues.set(key, mine);
|
|
50
|
+
await previous;
|
|
51
|
+
try {
|
|
52
|
+
return await run();
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
finish();
|
|
56
|
+
if (queues.get(key) === mine)
|
|
57
|
+
queues.delete(key);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export function updateJsonStore(file, load, mutate, label) {
|
|
61
|
+
return inProcessTurn(resolve(file), () => lockedUpdate(file, load, mutate, label));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Overwrite a whole store under its lock, e.g. when session_restore puts back
|
|
65
|
+
* a saved copy. Without the lock, a concurrent locked update that read the
|
|
66
|
+
* file before the restore would write its stale copy over the restored one.
|
|
67
|
+
*/
|
|
68
|
+
export function replaceJsonStore(file, value, label) {
|
|
69
|
+
return updateJsonStore(file, () => value, () => saved(undefined), label);
|
|
70
|
+
}
|
|
71
|
+
async function lockedUpdate(file, load, mutate, label) {
|
|
72
|
+
// acquireLock creates its lock file next to the store, so the folder must
|
|
73
|
+
// exist on the very first write.
|
|
74
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
75
|
+
let release;
|
|
76
|
+
try {
|
|
77
|
+
release = await acquireLock(storeLockPath(file));
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
// Only a timeout means another writer holds the lock; other lock errors
|
|
81
|
+
// (permissions, a non-file at the lock path) keep their own message.
|
|
82
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
83
|
+
if (message.startsWith('policy-state-lock-timeout')) {
|
|
84
|
+
throw new Error(`${label} store is busy (another process holds ${basename(storeLockPath(file))}); retry`, { cause: error });
|
|
85
|
+
}
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
const store = load();
|
|
90
|
+
const { result, save } = mutate(store);
|
|
91
|
+
if (save)
|
|
92
|
+
await writeJsonAtomic(file, store);
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
release();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=locked-json-store.js.map
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import { managedLearningTool } from './managed-learning-tool.js';
|
|
21
21
|
import { ManagedRunCollector } from '../services/managed-run-collector.js';
|
|
22
|
-
import { collectWithLease, executeManagedControl, publishManagedSnapshot, publishManagedTermination } from '../services/managed-run-store.js';
|
|
22
|
+
import { collectWithLease, executeManagedControl, forgetManagedSession, ownedManagedSession, publishManagedSnapshot, publishManagedTermination, recordManagedSession } from '../services/managed-run-store.js';
|
|
23
23
|
import { getProjectCwd } from './types.js';
|
|
24
24
|
import { dynamicConfig, eventPage, readManagedEvents, ManagedProgress } from '../services/managed-workflows.js';
|
|
25
25
|
// Dedicated override avoids forwarding credentials to a generic model proxy.
|
|
@@ -211,6 +211,24 @@ async function waitForIdle(sessionId, maxWaitMs, messageId) {
|
|
|
211
211
|
}
|
|
212
212
|
return progress.snapshot();
|
|
213
213
|
}
|
|
214
|
+
function hostAllowlist() {
|
|
215
|
+
return (process.env.RUFLO_MANAGED_CONTROL_SESSIONS ?? '').split(',').map(s => s.trim()).filter(Boolean);
|
|
216
|
+
}
|
|
217
|
+
// The API key reaches every session in the organisation. Only sessions this project created, or that the host
|
|
218
|
+
// allowlisted, may be read or changed; an unreadable ledger owns nothing.
|
|
219
|
+
const NOT_OWNED = 'Managed session was not created by this project and is not in RUFLO_MANAGED_CONTROL_SESSIONS';
|
|
220
|
+
function sessionAccess(sessionId) {
|
|
221
|
+
let owned;
|
|
222
|
+
try {
|
|
223
|
+
owned = ownedManagedSession(getProjectCwd(), sessionId);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
owned = undefined;
|
|
227
|
+
}
|
|
228
|
+
if (owned)
|
|
229
|
+
return { owned };
|
|
230
|
+
return hostAllowlist().includes(sessionId) ? {} : undefined;
|
|
231
|
+
}
|
|
214
232
|
function definiteRejection(status) { return [400, 401, 403, 404, 422].includes(status); }
|
|
215
233
|
function maName(prefix, given) {
|
|
216
234
|
if (typeof given === 'string' && given.trim())
|
|
@@ -361,6 +379,13 @@ export const managedAgentTools = [
|
|
|
361
379
|
}
|
|
362
380
|
if (!s.data || typeof s.data.id !== 'string' || !/^sesn_[A-Za-z0-9]+$/.test(s.data.id))
|
|
363
381
|
return { success: false, stage: 'session', agentId: a.data.id, environmentId: e.data.id, error: 'Invalid session acknowledgement; inspect provider resources before retrying', cleanupRequired: true };
|
|
382
|
+
let ledgerRecorded = true, dropped = [];
|
|
383
|
+
try {
|
|
384
|
+
dropped = recordManagedSession(getProjectCwd(), s.data.id, e.data.id);
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
ledgerRecorded = false;
|
|
388
|
+
}
|
|
364
389
|
return {
|
|
365
390
|
success: true,
|
|
366
391
|
runtime: 'managed',
|
|
@@ -373,6 +398,8 @@ export const managedAgentTools = [
|
|
|
373
398
|
dynamicWorkflows: config.enabled,
|
|
374
399
|
budget: config.budget,
|
|
375
400
|
verification: 'unverified',
|
|
401
|
+
...(ledgerRecorded ? {} : { ledgerRecorded, warning: 'Session was not recorded locally; the other managed_agent_* tools refuse it until it is added to RUFLO_MANAGED_CONTROL_SESSIONS.' }),
|
|
402
|
+
...(dropped.length === 0 ? {} : { ledgerDropped: dropped.map(d => d.sessionId), warning: `The local session ledger is full (1000 sessions), so ${dropped.map(d => d.sessionId).join(', ')} was dropped from it and the other managed_agent_* tools now refuse it. A running session keeps billing: add it to RUFLO_MANAGED_CONTROL_SESSIONS to terminate it.` }),
|
|
376
403
|
note: 'Cloud agent provisioned. Send work with managed_agent_prompt({sessionId, message}); inspect with managed_agent_events; clean up with managed_agent_terminate (running sessions consume runtime and tokens).',
|
|
377
404
|
};
|
|
378
405
|
},
|
|
@@ -401,6 +428,8 @@ export const managedAgentTools = [
|
|
|
401
428
|
return { success: false, error: 'message is required' };
|
|
402
429
|
if (input.maxWaitMs !== undefined && (typeof input.maxWaitMs !== 'number' || !Number.isFinite(input.maxWaitMs) || input.maxWaitMs <= 0))
|
|
403
430
|
return { success: false, error: 'maxWaitMs must be finite and positive' };
|
|
431
|
+
if (!sessionAccess(sessionId))
|
|
432
|
+
return { success: false, sessionId, error: NOT_OWNED };
|
|
404
433
|
if (pendingPrompts.has(sessionId))
|
|
405
434
|
return { success: false, error: 'A prompt is already pending for this session' };
|
|
406
435
|
pendingPrompts.add(sessionId);
|
|
@@ -444,6 +473,8 @@ export const managedAgentTools = [
|
|
|
444
473
|
const sessionId = String(input.sessionId ?? '');
|
|
445
474
|
if (!sessionId)
|
|
446
475
|
return { error: 'sessionId is required' };
|
|
476
|
+
if (!sessionAccess(sessionId))
|
|
477
|
+
return { sessionId, error: NOT_OWNED };
|
|
447
478
|
const r = await maRequest('GET', `/sessions/${encodeURIComponent(sessionId)}`);
|
|
448
479
|
if (!r.ok)
|
|
449
480
|
return { sessionId, error: r.error };
|
|
@@ -469,6 +500,8 @@ export const managedAgentTools = [
|
|
|
469
500
|
const sessionId = String(input.sessionId ?? '');
|
|
470
501
|
if (!sessionId)
|
|
471
502
|
return { error: 'sessionId is required' };
|
|
503
|
+
if (!sessionAccess(sessionId))
|
|
504
|
+
return { success: false, sessionId, error: NOT_OWNED };
|
|
472
505
|
let events;
|
|
473
506
|
try {
|
|
474
507
|
events = typeof input.threadId === 'string' ? await fetchSessionEvents(sessionId, undefined, input.threadId) : (await observeSession(sessionId)).events;
|
|
@@ -549,19 +582,24 @@ export const managedAgentTools = [
|
|
|
549
582
|
const sessionId = String(input.sessionId ?? '');
|
|
550
583
|
if (!sessionId)
|
|
551
584
|
return { success: false, error: 'sessionId is required' };
|
|
552
|
-
//
|
|
553
|
-
// (RUFLO_MANAGED_CONTROL=1) this tool obeys the same session allowlist, and may delete only that session's own environment.
|
|
585
|
+
// Once the host has switched on the governed control plane (RUFLO_MANAGED_CONTROL=1) only the allowlist admits a session.
|
|
554
586
|
const governed = process.env.RUFLO_MANAGED_CONTROL === '1';
|
|
555
|
-
if (governed && !(
|
|
587
|
+
if (governed && !hostAllowlist().includes(sessionId)) {
|
|
556
588
|
return { success: false, error: 'Host managed control policy denies this session' };
|
|
557
589
|
}
|
|
590
|
+
const access = sessionAccess(sessionId);
|
|
591
|
+
if (!access)
|
|
592
|
+
return { success: false, sessionId, error: NOT_OWNED };
|
|
558
593
|
const wantsEnvironment = typeof input.environmentId === 'string' && input.environmentId.length > 0;
|
|
594
|
+
// The provider, not the local ledger, says which environment the session runs in; a ledger entry can be edited.
|
|
559
595
|
let ownEnvironment;
|
|
560
|
-
if (
|
|
596
|
+
if (wantsEnvironment) {
|
|
561
597
|
const g = await maRequest('GET', `/sessions/${encodeURIComponent(sessionId)}`);
|
|
562
598
|
if (!g.ok)
|
|
563
599
|
return { success: false, error: g.error };
|
|
564
|
-
ownEnvironment = g.data
|
|
600
|
+
ownEnvironment = g.data?.environment_id;
|
|
601
|
+
if (access.owned?.environmentId !== undefined && access.owned.environmentId !== ownEnvironment)
|
|
602
|
+
ownEnvironment = undefined;
|
|
565
603
|
}
|
|
566
604
|
const s = await maRequest('DELETE', `/sessions/${encodeURIComponent(sessionId)}`);
|
|
567
605
|
const result = { runtime: 'managed', sessionId, sessionDeleted: s.ok };
|
|
@@ -574,10 +612,16 @@ export const managedAgentTools = [
|
|
|
574
612
|
result.snapshotUpdated = false;
|
|
575
613
|
}
|
|
576
614
|
}
|
|
615
|
+
if (s.ok && access.owned) {
|
|
616
|
+
try {
|
|
617
|
+
forgetManagedSession(getProjectCwd(), sessionId);
|
|
618
|
+
}
|
|
619
|
+
catch { /* a stale entry names a deleted session */ }
|
|
620
|
+
}
|
|
577
621
|
if (!s.ok)
|
|
578
622
|
result.error = s.error;
|
|
579
623
|
if (s.ok && wantsEnvironment) {
|
|
580
|
-
if (
|
|
624
|
+
if (input.environmentId !== ownEnvironment) {
|
|
581
625
|
result.environmentDeleted = false;
|
|
582
626
|
result.environmentError = 'environmentId does not belong to this session';
|
|
583
627
|
}
|
|
@@ -8,10 +8,11 @@ import { randomUUID } from 'node:crypto';
|
|
|
8
8
|
import { gunzipSync } from 'node:zlib';
|
|
9
9
|
import { join } from 'node:path';
|
|
10
10
|
import { getProjectCwd } from './types.js';
|
|
11
|
-
import { containedWritePath } from './path-containment.js';
|
|
11
|
+
import { containedReadPath, containedWritePath, isLocalCliCall } from './path-containment.js';
|
|
12
12
|
import { MAX_IMPORT_BYTES, readImportFile } from './import-limits.js';
|
|
13
13
|
import { mkdirRestricted, readFileMaybeEncrypted, writeFileRestricted, } from '../fs-secure.js';
|
|
14
14
|
import { validateIdentifier, validateText } from './validate-input.js';
|
|
15
|
+
import { replaceJsonStore } from './locked-json-store.js';
|
|
15
16
|
function isRecord(value) {
|
|
16
17
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
17
18
|
}
|
|
@@ -466,17 +467,19 @@ export const sessionTools = [
|
|
|
466
467
|
if (input.restoreMemory !== false && session.data?.memory) {
|
|
467
468
|
memoryRestore = await restoreMemorySnapshot(session.data.memory);
|
|
468
469
|
}
|
|
470
|
+
// Same store locks as the task_* and agent_* tools, so a concurrent update
|
|
471
|
+
// cannot write a pre-restore copy over the restored store.
|
|
469
472
|
if (input.restoreTasks !== false && session.data?.tasks) {
|
|
470
473
|
const taskDir = join(getProjectCwd(), STORAGE_DIR, 'tasks');
|
|
471
474
|
if (!existsSync(taskDir))
|
|
472
475
|
mkdirRestricted(taskDir);
|
|
473
|
-
|
|
476
|
+
await replaceJsonStore(join(taskDir, 'store.json'), session.data.tasks, 'tasks');
|
|
474
477
|
}
|
|
475
478
|
if (input.restoreAgents !== false && session.data?.agents) {
|
|
476
479
|
const agentDir = join(getProjectCwd(), STORAGE_DIR, 'agents');
|
|
477
480
|
if (!existsSync(agentDir))
|
|
478
481
|
mkdirRestricted(agentDir);
|
|
479
|
-
|
|
482
|
+
await replaceJsonStore(join(agentDir, 'store.json'), session.data.agents, 'agents');
|
|
480
483
|
}
|
|
481
484
|
return {
|
|
482
485
|
sessionId: session.sessionId,
|
|
@@ -736,17 +739,23 @@ export const sessionTools = [
|
|
|
736
739
|
activate: { type: 'boolean', description: 'Restore the imported session into the active stores' },
|
|
737
740
|
},
|
|
738
741
|
},
|
|
739
|
-
handler: async (input) => {
|
|
742
|
+
handler: async (input, context) => {
|
|
740
743
|
let parsed;
|
|
741
744
|
if (input.data !== undefined && input.data !== null) {
|
|
742
745
|
parsed = input.data;
|
|
743
746
|
}
|
|
744
747
|
else {
|
|
745
|
-
const
|
|
746
|
-
if (!
|
|
748
|
+
const requestedPath = String(input.inputPath ?? '');
|
|
749
|
+
if (!requestedPath)
|
|
747
750
|
return { error: 'Provide inputPath (a session JSON file) or data (a session record)' };
|
|
748
|
-
|
|
749
|
-
|
|
751
|
+
// MCP callers may only read regular files inside the project, matching
|
|
752
|
+
// memory_import; the local CLI may name any file the operator chooses.
|
|
753
|
+
const local = isLocalCliCall(context);
|
|
754
|
+
const inputPath = local ? (existsSync(requestedPath) ? requestedPath : null) : containedReadPath(requestedPath);
|
|
755
|
+
if (!inputPath) {
|
|
756
|
+
return { error: local ? `File not found: ${requestedPath}`
|
|
757
|
+
: 'inputPath must be an existing regular file inside the project directory (not a symlink)' };
|
|
758
|
+
}
|
|
750
759
|
try {
|
|
751
760
|
const bytes = readImportFile(inputPath);
|
|
752
761
|
const content = bytes[0] === 0x1f && bytes[1] === 0x8b
|
|
@@ -754,7 +763,8 @@ export const sessionTools = [
|
|
|
754
763
|
parsed = JSON.parse(content.toString('utf-8'));
|
|
755
764
|
}
|
|
756
765
|
catch (e) {
|
|
757
|
-
|
|
766
|
+
// Never echo parser text: a SyntaxError message quotes the file's contents.
|
|
767
|
+
return { error: e instanceof SyntaxError ? 'Invalid session JSON (parse failed)' : `Invalid session JSON: ${e.message}` };
|
|
758
768
|
}
|
|
759
769
|
}
|
|
760
770
|
const validationError = validateImportedSession(parsed);
|