dsh-any-agent 0.3.9 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +153 -1
- package/README.md +75 -634
- package/README.zh.md +64 -649
- package/bin/dsh-any-agent.mjs +59 -0
- package/demo/mcp-client.mjs +130 -0
- package/demo/run.mjs +326 -0
- package/demo/transcript.json +47 -0
- package/docs/brand/README.md +58 -0
- package/docs/brand/header.jpg +0 -0
- package/docs/en/architecture.md +43 -0
- package/docs/en/compatibility.md +51 -0
- package/docs/en/demo.md +90 -0
- package/docs/en/install.md +257 -0
- package/docs/en/limits.md +27 -0
- package/docs/en/locking.md +24 -0
- package/docs/en/reference.md +40 -0
- package/docs/en/release.md +33 -0
- package/docs/en/security.md +59 -0
- package/docs/en/team.md +74 -0
- package/docs/en/tests.md +96 -0
- package/docs/en/usage.md +71 -0
- package/docs/zh/architecture.md +43 -0
- package/docs/zh/compatibility.md +49 -0
- package/docs/zh/demo.md +90 -0
- package/docs/zh/install.md +274 -0
- package/docs/zh/limits.md +30 -0
- package/docs/zh/locking.md +24 -0
- package/docs/zh/reference.md +40 -0
- package/docs/zh/release.md +38 -0
- package/docs/zh/security.md +59 -0
- package/docs/zh/team.md +71 -0
- package/docs/zh/tests.md +95 -0
- package/docs/zh/usage.md +69 -0
- package/package.json +5 -1
- package/scripts/check-release.mjs +73 -0
- package/src/acp.mjs +31 -3
- package/src/audit.mjs +32 -0
- package/src/bootstrap.mjs +26 -1
- package/src/config.mjs +178 -9
- package/src/host.mjs +148 -0
- package/src/hub.mjs +494 -73
- package/src/procstat.mjs +72 -0
- package/src/tools.mjs +561 -27
package/src/hub.mjs
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
copyFileSync,
|
|
18
18
|
cpSync,
|
|
19
19
|
mkdirSync,
|
|
20
|
+
mkdtempSync,
|
|
20
21
|
readFileSync,
|
|
21
22
|
writeFileSync,
|
|
22
23
|
existsSync,
|
|
@@ -29,12 +30,14 @@ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
|
29
30
|
import { homedir, tmpdir } from 'node:os';
|
|
30
31
|
import { spawnSync } from 'node:child_process';
|
|
31
32
|
import {
|
|
33
|
+
ALLOW_FULL_ACCESS,
|
|
32
34
|
APPROVAL_POLICIES,
|
|
33
35
|
DEFAULT_PERMISSION,
|
|
34
36
|
DEFAULT_REASONING_EFFORT,
|
|
35
37
|
IDLE_TTL_MS,
|
|
36
38
|
LIST_PROBE_TTL_MS,
|
|
37
39
|
MAX_LIVE,
|
|
40
|
+
MAX_RSS_MB,
|
|
38
41
|
PERMISSION_TIERS,
|
|
39
42
|
PROMPT_TIMEOUT_MS,
|
|
40
43
|
REAP_INTERVAL_MS,
|
|
@@ -42,6 +45,7 @@ import {
|
|
|
42
45
|
RUNS_DIR,
|
|
43
46
|
SENTINEL_INCLUDE_REASONING,
|
|
44
47
|
SENTINEL_TTL_MS,
|
|
48
|
+
SHARED_PROCESS,
|
|
45
49
|
STATE_FILE,
|
|
46
50
|
LEGACY_STATE_FILE,
|
|
47
51
|
USING_DEFAULT_STATE,
|
|
@@ -50,6 +54,8 @@ import {
|
|
|
50
54
|
defaultApprovalPolicy,
|
|
51
55
|
} from './config.mjs';
|
|
52
56
|
import { AcpProcess } from './acp.mjs';
|
|
57
|
+
import { SessionHost } from './host.mjs';
|
|
58
|
+
import { rssMb } from './procstat.mjs';
|
|
53
59
|
import { readConversationMeta } from './titles.mjs';
|
|
54
60
|
import { registerWorkspace, findSessionHeaderStatus } from './workspace.mjs';
|
|
55
61
|
import {
|
|
@@ -287,6 +293,8 @@ export class Conversation {
|
|
|
287
293
|
this.turnCount = state.turnCount ?? 0;
|
|
288
294
|
/** 建会话时给的提示词(仅在 DSH 还没生成原生标题前当兜底显示)。 */
|
|
289
295
|
this.titleHint = state.titleHint ?? null;
|
|
296
|
+
/** true = 不受空闲 TTL / MAX_LIVE 回收(用于"必须一直握住写锁"的长期会话)。 */
|
|
297
|
+
this.keepAlive = state.keepAlive === true;
|
|
290
298
|
/** 会话级 ACP 配置(思考深度 / 模型)。新进程不记得,resume 后要重套。 */
|
|
291
299
|
this.cfg = {
|
|
292
300
|
reasoningEffort: state.reasoningEffort ?? DEFAULT_REASONING_EFFORT,
|
|
@@ -302,11 +310,15 @@ export class Conversation {
|
|
|
302
310
|
|
|
303
311
|
this.proc = null;
|
|
304
312
|
this.busy = false;
|
|
313
|
+
/** 正在进行的进程回收(`proc.stop()` 的 promise)。非 null 时不得为同一会话再拉起进程。 */
|
|
314
|
+
this.recycling = null;
|
|
305
315
|
/** 本进程为这个会话拉起过的最后一个子进程 PID(登记被删后仍能归因锁的归属)。 */
|
|
306
316
|
this.lastChildPid = null;
|
|
307
317
|
/** 最近一次撞写锁的记录 `{at, holder_kind, reason, hint}`(见 snapshot())。 */
|
|
308
318
|
this.lockConflict = null;
|
|
309
319
|
this.pendingApprovals = new Map();
|
|
320
|
+
/** 正在跑的 run 记录(进程意外退出时要用它写 error 哨兵)。 */
|
|
321
|
+
this.currentRun = null;
|
|
310
322
|
/** 等待"当前回合结束"的回调队列,供插话排队使用。 */
|
|
311
323
|
this.idleWaiters = [];
|
|
312
324
|
|
|
@@ -329,6 +341,11 @@ export class Conversation {
|
|
|
329
341
|
*/
|
|
330
342
|
this.runs = [];
|
|
331
343
|
this.runSeq = 0;
|
|
344
|
+
/** 调用方提供的幂等键 → run_id(与 runs 同步淘汰)。 */
|
|
345
|
+
this.clientRuns = new Map();
|
|
346
|
+
/** 忙时入队的待执行任务(仅内存;重启丢失)。 */
|
|
347
|
+
this.queue = [];
|
|
348
|
+
this.draining = false;
|
|
332
349
|
/** 最近一次回合结果,仅内存(进程退出即消失),不落盘。 */
|
|
333
350
|
this.lastResult = null;
|
|
334
351
|
}
|
|
@@ -346,6 +363,7 @@ export class Conversation {
|
|
|
346
363
|
lastUsedAt: this.lastUsedAt,
|
|
347
364
|
turnCount: this.turnCount,
|
|
348
365
|
titleHint: this.titleHint,
|
|
366
|
+
keepAlive: this.keepAlive,
|
|
349
367
|
reasoningEffort: this.cfg.reasoningEffort,
|
|
350
368
|
provider: this.cfg.provider,
|
|
351
369
|
model: this.cfg.model,
|
|
@@ -385,6 +403,9 @@ export class Conversation {
|
|
|
385
403
|
on_approval: this.onApproval,
|
|
386
404
|
alive: !!this.proc?.alive,
|
|
387
405
|
busy: this.busy,
|
|
406
|
+
keep_alive: this.keepAlive,
|
|
407
|
+
/** 子进程 RSS(MB);量不到就是 null,不影响任何决策。 */
|
|
408
|
+
rss_mb: rssMb(this.proc?.pid),
|
|
388
409
|
/** running = 正在跑回合;idle = 进程活着但空闲;detached = 进程未打开(可 resume)。 */
|
|
389
410
|
state: this.state(),
|
|
390
411
|
current_tool: this.currentTool,
|
|
@@ -402,9 +423,13 @@ export class Conversation {
|
|
|
402
423
|
usage: meta?.usage?.totals ?? null,
|
|
403
424
|
context_pressure: meta?.pressure ?? null,
|
|
404
425
|
pending_approvals: [...this.pendingApprovals.keys()],
|
|
426
|
+
/** 忙时排队的任务(仅内存;重启丢失)。 */
|
|
427
|
+
queue_length: this.queue?.length ?? 0,
|
|
428
|
+
queue: this.queueList(),
|
|
405
429
|
// Keep the ID list compatible; details are ephemeral and excluded from toState().
|
|
406
430
|
pending_approval_details: [...this.pendingApprovals].map(([approvalId, pending]) => ({
|
|
407
431
|
approval_id: approvalId,
|
|
432
|
+
created_at: pending.createdAt ?? null,
|
|
408
433
|
...pending.params.details,
|
|
409
434
|
})),
|
|
410
435
|
/**
|
|
@@ -426,19 +451,30 @@ export class Conversation {
|
|
|
426
451
|
|
|
427
452
|
/** 确保有一个可用的 DSH 进程;必要时新建并 resume 回该会话。 */
|
|
428
453
|
async ensureAlive() {
|
|
454
|
+
// ★ 上一代进程正在回收时必须先等它停完:否则会为同一会话再拉起一个进程,
|
|
455
|
+
// 去抢一个**尚未释放**的写锁(reaper/release 里 await stop() 的那个窗口)。
|
|
456
|
+
if (this.recycling) await this.recycling;
|
|
429
457
|
if (this.proc?.alive) return this.proc;
|
|
430
|
-
const
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
458
|
+
const shared = SHARED_PROCESS;
|
|
459
|
+
let proc;
|
|
460
|
+
if (shared) {
|
|
461
|
+
proc = this.#hub.acquireHost(this.cwd, this.permission);
|
|
462
|
+
proc.attach(this);
|
|
463
|
+
this.proc = proc;
|
|
464
|
+
} else {
|
|
465
|
+
proc = new AcpProcess({
|
|
466
|
+
cwd: this.cwd,
|
|
467
|
+
permission: this.permission,
|
|
468
|
+
log: this.#hub.log,
|
|
469
|
+
onNotification: (params) => this.onUpdate(params),
|
|
470
|
+
onPermissionRequest: (params) => this.onPermissionRequest(params),
|
|
471
|
+
});
|
|
472
|
+
proc.start();
|
|
473
|
+
this.proc = proc;
|
|
474
|
+
}
|
|
475
|
+
// ★ lastChildPid **推迟到 resume 真正成功后**再写(见 writeMarker 处)。
|
|
476
|
+
// 若在这里就覆盖,一次注定撞锁失败的 resume 会把"上一代还活着的子进程"
|
|
477
|
+
// 这条抢占线索换成刚拉起、注定失败的新进程,takeover 就归因不到真正的持有者。
|
|
442
478
|
// ★ 登记**推迟到真正拿到写锁之后**(见下面 resume 成功处)。
|
|
443
479
|
// 登记的含义是"我正持有这个会话的写锁",不是"我拉起了一个进程"。
|
|
444
480
|
// 若在这里就写,一次注定撞锁失败的 resume 会先把"谁持有"的线索覆盖掉、
|
|
@@ -459,6 +495,8 @@ export class Conversation {
|
|
|
459
495
|
await this.verifyPermissionRecorded();
|
|
460
496
|
// 锁到手了,这时才登记;从此别人能查到"锁在我们手上"
|
|
461
497
|
writeMarker(this.id, { childPid: proc.pid, cwd: this.cwd });
|
|
498
|
+
// 只有真正拿到写锁后才更新"我拉起的最后一个子进程":失败路径需要保留上一代的 PID。
|
|
499
|
+
this.lastChildPid = proc.pid;
|
|
462
500
|
this.lockConflict = null; // 拿到锁了,之前的撞锁记录作废
|
|
463
501
|
this.#hub.log.info(`[conv ${this.id}] 已 resume`);
|
|
464
502
|
return proc;
|
|
@@ -466,12 +504,15 @@ export class Conversation {
|
|
|
466
504
|
// ★ 半死的进程必须作废:它 alive 但**没有加载这个会话**,一旦留在 this.proc 上,
|
|
467
505
|
// 下次调用会走上面 `this.proc?.alive` 的快路径,把 session/prompt 发给一个
|
|
468
506
|
// 不认识该会话的进程 —— 会话就永久卡死了(重派也不会自愈)。
|
|
469
|
-
|
|
507
|
+
// 只作废**自己这一次**拉起的进程:窄窗口里另一个调用可能已经换上了新一代。
|
|
508
|
+
if (this.proc === proc) this.proc = null;
|
|
470
509
|
// ★ 必须 **await**:不等它真的退出,紧接着的 classifyHolder 就会把"正在退出的自己人"
|
|
471
510
|
// 当成持锁者(表现为"上一代子进程还活着并握着锁"),于是每次失败都误报锁冲突 ——
|
|
472
511
|
// 更糟的是旧代码没有 lastChildPid 兜底,会把这种自伤报成"多半是你自己的 GUI",
|
|
473
512
|
// 而 dsh_takeover 对 none 又拒绝接管,会话就卡住了(test/cycle.mjs 实测抓到)。
|
|
474
|
-
const stopped =
|
|
513
|
+
const stopped = shared
|
|
514
|
+
? await proc.detach(this).catch(() => false)
|
|
515
|
+
: await proc.stop().catch(() => false);
|
|
475
516
|
// 只删**自己的**登记(removeMarker 会校验 token);进程没确认退出时保留登记,
|
|
476
517
|
// 让 classifyHolder/takeover 仍能归因。
|
|
477
518
|
if (stopped) removeMarker(this.id);
|
|
@@ -602,7 +643,23 @@ export class Conversation {
|
|
|
602
643
|
return report;
|
|
603
644
|
}
|
|
604
645
|
|
|
605
|
-
// 3)
|
|
646
|
+
// 3) 共享进程:杀它会连坐同组会话,先把代价说清楚,别让对方在不知情下按下去。
|
|
647
|
+
// 共享进程池(0.5.0 默认开启)让一个 PID 载着多个会话,takeover 只看"谁握着锁"
|
|
648
|
+
// 会做出一个很贵的决定 —— 杀掉持有者 = 同组所有会话的进行中回合一起断。
|
|
649
|
+
const sharedVictims = this.#hub.hostVictimsOf(killTarget, this.id);
|
|
650
|
+
if (sharedVictims.length > 0) {
|
|
651
|
+
report.shared_sessions = sharedVictims;
|
|
652
|
+
if (!force) {
|
|
653
|
+
report.message =
|
|
654
|
+
`抢占被拒绝:PID ${killTarget} 是共享进程,上面还挂着 ${sharedVictims.length} 个其它会话` +
|
|
655
|
+
`(${sharedVictims.map((id) => id.slice(0, 8)).join(', ')})。\n` +
|
|
656
|
+
'杀掉它会连坐这些会话:各自进行中的回合会中断(会话本体无损,之后照常 resume)。\n' +
|
|
657
|
+
'确认可以接受就带 force=true 重试;不想连坐就先 dsh_release 那些会话,或等它们空闲。';
|
|
658
|
+
return report;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// 4) 杀 + 重试(内核在持有者进程退出时释放信号量)
|
|
606
663
|
const kill = killHolderChild(killTarget, { expectedSpawnedAt: holder.marker?.spawned_at });
|
|
607
664
|
report.killed_pid = killTarget;
|
|
608
665
|
report.kill = kill;
|
|
@@ -622,7 +679,10 @@ export class Conversation {
|
|
|
622
679
|
report.ok = true;
|
|
623
680
|
report.message =
|
|
624
681
|
`已抢占:杀掉持有者 PID ${killTarget}(${holder.reason}),并成功接管会话。` +
|
|
625
|
-
`\n⚠️ 如果那个进程当时正在跑回合,那一轮的工作会中断(会话日志会记为 interrupted
|
|
682
|
+
`\n⚠️ 如果那个进程当时正在跑回合,那一轮的工作会中断(会话日志会记为 interrupted)。` +
|
|
683
|
+
(sharedVictims.length > 0
|
|
684
|
+
? `\n⚠️ 它是共享进程,另外 ${sharedVictims.length} 个会话也被一起断掉了(各自 resume 即可)。`
|
|
685
|
+
: '');
|
|
626
686
|
} catch (e) {
|
|
627
687
|
report.message = `杀掉 PID ${killTarget} 之后仍无法接管:${e.message}`;
|
|
628
688
|
}
|
|
@@ -733,6 +793,7 @@ export class Conversation {
|
|
|
733
793
|
}, this.#hub.approvalTimeoutMs);
|
|
734
794
|
this.pendingApprovals.set(approvalId, {
|
|
735
795
|
params: { tool: desc, details: approvalContext(params, toolCall, desc, options) },
|
|
796
|
+
createdAt: now(),
|
|
736
797
|
allowId,
|
|
737
798
|
rejectId,
|
|
738
799
|
resolve: (outcome) => {
|
|
@@ -749,8 +810,76 @@ export class Conversation {
|
|
|
749
810
|
if (!p) throw new Error(`没有待决审批: ${approvalId}`);
|
|
750
811
|
this.pendingApprovals.delete(approvalId);
|
|
751
812
|
const chosen = decision === 'allow' ? p.allowId : p.rejectId;
|
|
813
|
+
// ★ 没有对应 option 时实际发出的是 cancelled。必须把 effective 如实告诉调用方,
|
|
814
|
+
// 否则 dsh_approval_decide 会渲染成"已裁决为 allow",而 DSH 收到的是取消(假成功)。
|
|
815
|
+
const effective = chosen ? 'selected' : 'cancelled';
|
|
752
816
|
p.resolve(chosen ? { outcome: { outcome: 'selected', optionId: chosen } } : { outcome: { outcome: 'cancelled' } });
|
|
753
|
-
return {
|
|
817
|
+
return {
|
|
818
|
+
approval_id: approvalId,
|
|
819
|
+
decision,
|
|
820
|
+
effective,
|
|
821
|
+
...(chosen ? {} : { reason: 'no_option' }),
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* 起不来时的统一收尾:唤醒所有等本轮结束的插话请求,并落一条 error 哨兵。
|
|
827
|
+
*
|
|
828
|
+
* 这两件事必须都做、且互相独立:
|
|
829
|
+
* - 只写哨兵救不了 `dsh_interject`——它等的是 idleWaiters,不是文件;
|
|
830
|
+
* - 只唤醒不写哨兵,调用方事后 `dsh_get(run_id)` 就永远找不到这次失败。
|
|
831
|
+
*/
|
|
832
|
+
#settleFailedRun(runRecord, error) {
|
|
833
|
+
const waiters = this.idleWaiters;
|
|
834
|
+
this.idleWaiters = [];
|
|
835
|
+
for (const w of waiters) {
|
|
836
|
+
try {
|
|
837
|
+
w();
|
|
838
|
+
} catch {}
|
|
839
|
+
}
|
|
840
|
+
this.#scheduleDrain();
|
|
841
|
+
if (this.currentRun === runRecord) this.currentRun = null;
|
|
842
|
+
runRecord.ended_at = now();
|
|
843
|
+
runRecord.status = 'error';
|
|
844
|
+
runRecord.error = error?.message ?? String(error);
|
|
845
|
+
runRecord.elapsed_ms = 0;
|
|
846
|
+
runRecord.result = {
|
|
847
|
+
conversation_id: this.id,
|
|
848
|
+
run_id: runRecord.run_id,
|
|
849
|
+
stop_reason: 'error',
|
|
850
|
+
error: runRecord.error,
|
|
851
|
+
answer: '',
|
|
852
|
+
thinking_stats: { hidden: true, chars: 0, chunks: 0, ms: 0 },
|
|
853
|
+
tools_used: [],
|
|
854
|
+
workspace_changed: false,
|
|
855
|
+
elapsed_ms: 0,
|
|
856
|
+
};
|
|
857
|
+
try {
|
|
858
|
+
if (typeof this.#hub.writeRunSentinel === 'function') {
|
|
859
|
+
const file = this.#hub.writeRunSentinel(this.id, runRecord);
|
|
860
|
+
runRecord.result.sentinel_file = file ?? this.#hub.runSentinelPath?.(this.id, runRecord.run_id) ?? null;
|
|
861
|
+
if (!file) runRecord.result.sentinel_error = runRecord.sentinel_error ?? '哨兵文件写入失败';
|
|
862
|
+
}
|
|
863
|
+
} catch (e) {
|
|
864
|
+
runRecord.result.sentinel_error = `写完成哨兵失败: ${e.message}`;
|
|
865
|
+
}
|
|
866
|
+
try {
|
|
867
|
+
this.#hub.save?.();
|
|
868
|
+
} catch {}
|
|
869
|
+
return runRecord.result;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* 共享进程池的进程意外退出:把本会话在跑的回合标成失败并落哨兵,
|
|
874
|
+
* 然后解除 proc 引用,下次调用会重新 acquireHost + resume。
|
|
875
|
+
*/
|
|
876
|
+
onProcessExit(reason) {
|
|
877
|
+
this.proc = null;
|
|
878
|
+
this.recycling = null;
|
|
879
|
+
if (this.busy && this.currentRun) {
|
|
880
|
+
this.busy = false;
|
|
881
|
+
this.#settleFailedRun(this.currentRun, new Error(String(reason)));
|
|
882
|
+
}
|
|
754
883
|
}
|
|
755
884
|
|
|
756
885
|
// ── 跑任务 ──────────────────────────────────────────────────────
|
|
@@ -782,6 +911,7 @@ export class Conversation {
|
|
|
782
911
|
const runRecord = run ?? this.createRun(text);
|
|
783
912
|
runRecord.status = 'running';
|
|
784
913
|
runRecord.started_at = now();
|
|
914
|
+
this.currentRun = runRecord;
|
|
785
915
|
const before = gitStatus(this.cwd);
|
|
786
916
|
let proc;
|
|
787
917
|
// ★ `busy` 必须在 ensureAlive **之前**置位。
|
|
@@ -796,19 +926,13 @@ export class Conversation {
|
|
|
796
926
|
} catch (e) {
|
|
797
927
|
// 起不来(撞写锁 / 会话损坏)就**必须放开 busy**,否则这个会话被永久占住;
|
|
798
928
|
// 同时别留一条永远 "running" 的幽灵记录。
|
|
799
|
-
//
|
|
929
|
+
// ★ 与 finalize 对齐:失败也必须给等待者一个终态——唤醒插话队列 + 落 error 哨兵。
|
|
930
|
+
// 只写哨兵救不了 dsh_interject:它等的是 idleWaiters,不是文件(默认 timeout=0 无 timer)。
|
|
800
931
|
this.busy = false;
|
|
801
|
-
runRecord
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
runRecord.result
|
|
805
|
-
conversation_id: this.id,
|
|
806
|
-
run_id: runRecord.run_id,
|
|
807
|
-
stop_reason: 'error',
|
|
808
|
-
error: e.message,
|
|
809
|
-
answer: '',
|
|
810
|
-
elapsed_ms: 0,
|
|
811
|
-
};
|
|
932
|
+
this.#settleFailedRun(runRecord, e);
|
|
933
|
+
e.runId = runRecord.run_id;
|
|
934
|
+
e.status = 'error';
|
|
935
|
+
e.sentinelFile = runRecord.result?.sentinel_file ?? null;
|
|
812
936
|
throw e;
|
|
813
937
|
}
|
|
814
938
|
this.currentTurn += 1;
|
|
@@ -840,6 +964,7 @@ export class Conversation {
|
|
|
840
964
|
// 而且调用方会永远等不到哨兵。所以出错也要落一个"收尾异常"的哨兵。
|
|
841
965
|
try {
|
|
842
966
|
this.busy = false;
|
|
967
|
+
if (this.currentRun === runRecord) this.currentRun = null;
|
|
843
968
|
this.collector = null;
|
|
844
969
|
this.currentTool = null;
|
|
845
970
|
// 回合结束后,任何仍挂着的审批都已失效:统一取消并清空,避免状态里
|
|
@@ -862,6 +987,7 @@ export class Conversation {
|
|
|
862
987
|
const waiters = this.idleWaiters;
|
|
863
988
|
this.idleWaiters = [];
|
|
864
989
|
for (const w of waiters) w();
|
|
990
|
+
this.#scheduleDrain();
|
|
865
991
|
const after = gitStatus(this.cwd);
|
|
866
992
|
const result = {
|
|
867
993
|
conversation_id: this.id,
|
|
@@ -897,10 +1023,12 @@ export class Conversation {
|
|
|
897
1023
|
} catch (e) {
|
|
898
1024
|
this.#hub.log.info(`[conv ${this.id}] 回合收尾异常(已兜底): ${e.message}`);
|
|
899
1025
|
this.busy = false;
|
|
1026
|
+
if (this.currentRun === runRecord) this.currentRun = null;
|
|
900
1027
|
this.collector = null;
|
|
901
1028
|
const waiters = this.idleWaiters;
|
|
902
1029
|
this.idleWaiters = [];
|
|
903
1030
|
for (const w of waiters) w();
|
|
1031
|
+
this.#scheduleDrain();
|
|
904
1032
|
const fallback = {
|
|
905
1033
|
conversation_id: this.id,
|
|
906
1034
|
run_id: runRecord.run_id,
|
|
@@ -1024,10 +1152,11 @@ export class Conversation {
|
|
|
1024
1152
|
}
|
|
1025
1153
|
|
|
1026
1154
|
/** 建一条回合记录。派活时先建,好让调用方立刻拿到 run_id(异步模式的关键)。 */
|
|
1027
|
-
createRun(text) {
|
|
1155
|
+
createRun(text, { clientRunId = null } = {}) {
|
|
1028
1156
|
const run = {
|
|
1029
1157
|
run_id: `run-${Date.now().toString(36)}-${++this.runSeq}`,
|
|
1030
1158
|
conversation_id: this.id,
|
|
1159
|
+
client_run_id: clientRunId ?? null,
|
|
1031
1160
|
prompt_preview: text.length > MAX_RUN_PREVIEW ? `${text.slice(0, MAX_RUN_PREVIEW)}…` : text,
|
|
1032
1161
|
status: 'queued',
|
|
1033
1162
|
started_at: null,
|
|
@@ -1036,12 +1165,118 @@ export class Conversation {
|
|
|
1036
1165
|
result: null,
|
|
1037
1166
|
};
|
|
1038
1167
|
this.runs.push(run);
|
|
1039
|
-
if (
|
|
1168
|
+
if (clientRunId) this.clientRuns.set(clientRunId, run.run_id);
|
|
1169
|
+
if (this.runs.length > MAX_RUNS) {
|
|
1170
|
+
const evicted = this.runs.shift();
|
|
1171
|
+
// 幂等键必须跟着 run 记录一起淘汰,否则会指向一个已经查不到的 run。
|
|
1172
|
+
for (const [k, v] of this.clientRuns) {
|
|
1173
|
+
if (v === evicted.run_id) this.clientRuns.delete(k);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1040
1176
|
// 防御性清残留:正常情况下该 run_id 从未用过,但确保等待方不会被历史哨兵误触发。
|
|
1041
1177
|
this.#hub.clearRunSentinel(this.id, run.run_id);
|
|
1042
1178
|
return run;
|
|
1043
1179
|
}
|
|
1044
1180
|
|
|
1181
|
+
/** 按调用方幂等键取 run(不存在/已淘汰返回 null)。 */
|
|
1182
|
+
getRunByClientId(clientRunId) {
|
|
1183
|
+
if (!clientRunId) return null;
|
|
1184
|
+
const runId = this.clientRuns.get(clientRunId);
|
|
1185
|
+
if (!runId) return null;
|
|
1186
|
+
return this.runs.find((r) => r.run_id === runId) ?? null;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// ── 会话级队列(忙时非阻塞入队)────────────────────────────────
|
|
1190
|
+
|
|
1191
|
+
/** 入队;返回 run 记录与 1-based 位置。队列只在内存,重启丢失。 */
|
|
1192
|
+
enqueue(text, { reasoning = 'hide', clientRunId = null, preview = null } = {}) {
|
|
1193
|
+
const MAX_QUEUE = 8;
|
|
1194
|
+
if (clientRunId) {
|
|
1195
|
+
const existing = this.getRunByClientId(clientRunId);
|
|
1196
|
+
if (existing) return { run: existing, position: 0, deduped: true };
|
|
1197
|
+
}
|
|
1198
|
+
if (this.queue.length >= MAX_QUEUE) {
|
|
1199
|
+
throw new Error(`队列已满(最多 ${MAX_QUEUE} 条);先用 dsh_queue list 清理,或等当前回合结束`);
|
|
1200
|
+
}
|
|
1201
|
+
// 预览用调用方原文,执行用可能已注入团队前缀的 text。
|
|
1202
|
+
const run = this.createRun(preview ?? text, { clientRunId });
|
|
1203
|
+
run.status = 'queued';
|
|
1204
|
+
this.queue.push({ run, text, reasoning, clientRunId, enqueued_at: now() });
|
|
1205
|
+
return { run, position: this.queue.length, deduped: false };
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
queueList() {
|
|
1209
|
+
// 防御:snapshot 可能被测试用 prototype 替身调用(没有构造器初始化 queue)。
|
|
1210
|
+
return (this.queue ?? []).map((item, i) => ({
|
|
1211
|
+
position: i + 1,
|
|
1212
|
+
run_id: item.run.run_id,
|
|
1213
|
+
preview: item.run.prompt_preview,
|
|
1214
|
+
enqueued_at: item.enqueued_at,
|
|
1215
|
+
client_run_id: item.clientRunId ?? null,
|
|
1216
|
+
}));
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
queueRemove(runId, { cancel = true } = {}) {
|
|
1220
|
+
const i = this.queue.findIndex((x) => x.run.run_id === runId);
|
|
1221
|
+
if (i < 0) throw new Error(`队列里没有 ${runId}`);
|
|
1222
|
+
const [item] = this.queue.splice(i, 1);
|
|
1223
|
+
if (cancel) {
|
|
1224
|
+
const run = item.run;
|
|
1225
|
+
run.status = 'cancelled';
|
|
1226
|
+
run.ended_at = now();
|
|
1227
|
+
run.elapsed_ms = 0;
|
|
1228
|
+
run.result = {
|
|
1229
|
+
conversation_id: this.id,
|
|
1230
|
+
run_id: run.run_id,
|
|
1231
|
+
stop_reason: 'cancelled',
|
|
1232
|
+
error: 'queued run cancelled before it started',
|
|
1233
|
+
answer: '',
|
|
1234
|
+
thinking_stats: { hidden: true, chars: 0, chunks: 0, ms: 0 },
|
|
1235
|
+
tools_used: [],
|
|
1236
|
+
workspace_changed: false,
|
|
1237
|
+
elapsed_ms: 0,
|
|
1238
|
+
};
|
|
1239
|
+
// 取消也是终态 → 写哨兵,避免等待方永远空等。
|
|
1240
|
+
const file = this.#hub.writeRunSentinel(this.id, run);
|
|
1241
|
+
run.result.sentinel_file = file ?? this.#hub.runSentinelPath(this.id, run.run_id);
|
|
1242
|
+
}
|
|
1243
|
+
return { removed: true, run_id: runId };
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
queueUpdate(runId, text) {
|
|
1247
|
+
const item = this.queue.find((x) => x.run.run_id === runId);
|
|
1248
|
+
if (!item) throw new Error(`队列里没有 ${runId}`);
|
|
1249
|
+
item.text = text;
|
|
1250
|
+
item.run.prompt_preview =
|
|
1251
|
+
text.length > MAX_RUN_PREVIEW ? `${text.slice(0, MAX_RUN_PREVIEW)}…` : text;
|
|
1252
|
+
return { updated: true, run_id: runId };
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
queuePromote(runId) {
|
|
1256
|
+
const i = this.queue.findIndex((x) => x.run.run_id === runId);
|
|
1257
|
+
if (i < 0) throw new Error(`队列里没有 ${runId}`);
|
|
1258
|
+
const [item] = this.queue.splice(i, 1);
|
|
1259
|
+
this.queue.unshift(item);
|
|
1260
|
+
return { promoted: true, run_id: runId, position: 1 };
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** 空闲时取队首执行。失败也要继续下一条(否则一条坏任务卡死整条队列)。 */
|
|
1264
|
+
#scheduleDrain() {
|
|
1265
|
+
if (this.busy || this.draining || this.queue.length === 0) return;
|
|
1266
|
+
this.draining = true;
|
|
1267
|
+
const timer = setTimeout(() => {
|
|
1268
|
+
this.draining = false;
|
|
1269
|
+
if (this.busy || this.queue.length === 0) return;
|
|
1270
|
+
const item = this.queue.shift();
|
|
1271
|
+
const run = item.run;
|
|
1272
|
+
run.status = 'running';
|
|
1273
|
+
this.prompt(item.text, { reasoning: item.reasoning, run, wait: false })
|
|
1274
|
+
.catch(() => {})
|
|
1275
|
+
.finally(() => this.#scheduleDrain());
|
|
1276
|
+
}, 0);
|
|
1277
|
+
timer.unref?.();
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1045
1280
|
/** 取回合记录;不传 run_id 就是最近一条。 */
|
|
1046
1281
|
getRun(runId) {
|
|
1047
1282
|
if (runId) {
|
|
@@ -1092,9 +1327,11 @@ export class Conversation {
|
|
|
1092
1327
|
* 之所以无竞态:dsh-acp 在让 prompt 请求返回**之前**就清空了 inflight 槽位,
|
|
1093
1328
|
* 且只在 agent 完全 idle 后才 settle(lib/index.js:1003-1011)。
|
|
1094
1329
|
*/
|
|
1095
|
-
async interject(message, { mode = 'interject', reasoning = 'hide', timeoutMs = PROMPT_TIMEOUT_MS } = {}) {
|
|
1330
|
+
async interject(message, { mode = 'interject', reasoning = 'hide', timeoutMs = PROMPT_TIMEOUT_MS, clientRunId = null } = {}) {
|
|
1331
|
+
// 先建 run:幂等键要在"等待上一轮"之前就登记,否则重试会造出第二个 run。
|
|
1332
|
+
const run = this.createRun(message, { clientRunId });
|
|
1096
1333
|
if (!this.busy) {
|
|
1097
|
-
const r = await this.prompt(message, { reasoning, timeoutMs });
|
|
1334
|
+
const r = await this.prompt(message, { reasoning, timeoutMs, run });
|
|
1098
1335
|
return { ...r, interjected: 'idle', waited_ms: 0 };
|
|
1099
1336
|
}
|
|
1100
1337
|
const t0 = now();
|
|
@@ -1104,21 +1341,61 @@ export class Conversation {
|
|
|
1104
1341
|
// 排队等待的时长跟随调用方的 timeout_ms(0 = 一直等),不再固定 30 分钟。
|
|
1105
1342
|
const idle = await this.waitIdle(timeoutMs);
|
|
1106
1343
|
const waited = now() - t0;
|
|
1107
|
-
if (!idle)
|
|
1108
|
-
|
|
1344
|
+
if (!idle) {
|
|
1345
|
+
const err = new Error('等待当前回合结束超时,插话未发送');
|
|
1346
|
+
err.runId = run.run_id;
|
|
1347
|
+
run.status = 'cancelled';
|
|
1348
|
+
run.ended_at = now();
|
|
1349
|
+
run.elapsed_ms = 0;
|
|
1350
|
+
run.result = {
|
|
1351
|
+
conversation_id: this.id,
|
|
1352
|
+
run_id: run.run_id,
|
|
1353
|
+
stop_reason: 'cancelled',
|
|
1354
|
+
error: err.message,
|
|
1355
|
+
answer: '',
|
|
1356
|
+
thinking_stats: { hidden: true, chars: 0, chunks: 0, ms: 0 },
|
|
1357
|
+
tools_used: [],
|
|
1358
|
+
workspace_changed: false,
|
|
1359
|
+
elapsed_ms: 0,
|
|
1360
|
+
};
|
|
1361
|
+
const file = this.#hub.writeRunSentinel?.(this.id, run);
|
|
1362
|
+
run.result.sentinel_file = file ?? this.#hub.runSentinelPath?.(this.id, run.run_id) ?? null;
|
|
1363
|
+
throw err;
|
|
1364
|
+
}
|
|
1365
|
+
const r = await this.prompt(message, { reasoning, timeoutMs, run });
|
|
1109
1366
|
return { ...r, interjected: mode, waited_ms: waited };
|
|
1110
1367
|
}
|
|
1111
1368
|
|
|
1112
1369
|
/** 关闭会话(进程收尾;会话本体留在磁盘上,可再次 resume)。 */
|
|
1113
1370
|
async close({ forget = false } = {}) {
|
|
1371
|
+
if (this.recycling) await this.recycling;
|
|
1114
1372
|
const proc = this.proc;
|
|
1115
|
-
this.proc = null;
|
|
1116
1373
|
let stopped = true;
|
|
1117
1374
|
if (proc?.alive) {
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1375
|
+
if (typeof proc.detach === 'function') {
|
|
1376
|
+
// 共享进程:只把本会话摘出去(detach 内会 session/close);最后一个走了才停进程。
|
|
1377
|
+
this.recycling = proc.detach(this).finally(() => {
|
|
1378
|
+
if (this.proc === proc) this.proc = null;
|
|
1379
|
+
this.recycling = null;
|
|
1380
|
+
});
|
|
1381
|
+
stopped = await this.recycling;
|
|
1382
|
+
} else {
|
|
1383
|
+
try {
|
|
1384
|
+
await proc.request('session/close', { sessionId: this.id }, 10_000);
|
|
1385
|
+
} catch {}
|
|
1386
|
+
// 与 reaper 相同:stop 期间保持 proc 可见并登记 recycling,
|
|
1387
|
+
// 落定后再置空——否则并发 dsh_send 会拿到垂死进程或去抢尚未释放的锁。
|
|
1388
|
+
this.recycling = proc
|
|
1389
|
+
.stop()
|
|
1390
|
+
.catch(() => false)
|
|
1391
|
+
.finally(() => {
|
|
1392
|
+
if (this.proc === proc) this.proc = null;
|
|
1393
|
+
this.recycling = null;
|
|
1394
|
+
});
|
|
1395
|
+
stopped = await this.recycling;
|
|
1396
|
+
}
|
|
1397
|
+
} else if (this.proc === proc) {
|
|
1398
|
+
this.proc = null;
|
|
1122
1399
|
}
|
|
1123
1400
|
// 回合已经结束/进程正在关闭,任何仍挂着的审批都不再可裁决。
|
|
1124
1401
|
for (const [, p] of this.pendingApprovals) {
|
|
@@ -1204,13 +1481,38 @@ export function formatReasoning(c, mode) {
|
|
|
1204
1481
|
*
|
|
1205
1482
|
* @returns {string|null} null 表示没问题,否则返回一段可直接抛出的说明。
|
|
1206
1483
|
*/
|
|
1484
|
+
/**
|
|
1485
|
+
* 当前文件系统是否大小写不敏感(缓存一次)。
|
|
1486
|
+
*
|
|
1487
|
+
* 不能按平台猜:GitHub 的 `macos-latest` 是**大小写敏感的 APFS**,而普通 macOS
|
|
1488
|
+
* 默认又不敏感;Windows 一定不敏感;Linux 一定敏感。用临时文件探针最稳。
|
|
1489
|
+
*/
|
|
1490
|
+
let caseInsensitiveCache = null;
|
|
1491
|
+
export function fsCaseInsensitive() {
|
|
1492
|
+
if (caseInsensitiveCache !== null) return caseInsensitiveCache;
|
|
1493
|
+
if (process.platform === 'win32') {
|
|
1494
|
+
caseInsensitiveCache = true;
|
|
1495
|
+
return true;
|
|
1496
|
+
}
|
|
1497
|
+
try {
|
|
1498
|
+
const dir = mkdtempSync(join(tmpdir(), 'dsh-any-agent-case-'));
|
|
1499
|
+
writeFileSync(join(dir, 'probe'), '');
|
|
1500
|
+
caseInsensitiveCache = existsSync(join(dir, 'PROBE'));
|
|
1501
|
+
rmSync(dir, { recursive: true, force: true });
|
|
1502
|
+
} catch {
|
|
1503
|
+
caseInsensitiveCache = false;
|
|
1504
|
+
}
|
|
1505
|
+
return caseInsensitiveCache;
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1207
1508
|
export function homeWorkspaceProblem(cwd, permission) {
|
|
1208
1509
|
if (permission === 'read-only') return null;
|
|
1209
1510
|
const home = homedir();
|
|
1210
1511
|
if (!home) return null;
|
|
1512
|
+
const caseInsensitive = process.platform === 'win32' || fsCaseInsensitive();
|
|
1211
1513
|
const norm = (p) => {
|
|
1212
1514
|
const r = resolve(p);
|
|
1213
|
-
return
|
|
1515
|
+
return caseInsensitive ? r.toLowerCase() : r;
|
|
1214
1516
|
};
|
|
1215
1517
|
if (norm(cwd) !== norm(home)) return null;
|
|
1216
1518
|
|
|
@@ -1232,6 +1534,8 @@ export function homeWorkspaceProblem(cwd, permission) {
|
|
|
1232
1534
|
export class Hub {
|
|
1233
1535
|
constructor({ log } = {}) {
|
|
1234
1536
|
this.conversations = new Map();
|
|
1537
|
+
/** 共享 ACP 进程池:key = `${cwd}\0${permission}`(0.5.0 起默认启用,`DSH_MCP_SHARED_PROCESS=0` 关闭)。 */
|
|
1538
|
+
this.hosts = new Map();
|
|
1235
1539
|
this.log = log ?? NOOP_LOG;
|
|
1236
1540
|
/** 最近一次 dsh_list 磁盘探测的结果:{ok, error, cached, at}。 */
|
|
1237
1541
|
this.lastProbe = { ok: null, error: null, cached: false, at: 0 };
|
|
@@ -1344,6 +1648,7 @@ export class Hub {
|
|
|
1344
1648
|
const payload = {
|
|
1345
1649
|
conversation_id: conversationId,
|
|
1346
1650
|
run_id: run.run_id,
|
|
1651
|
+
client_run_id: run.client_run_id ?? null,
|
|
1347
1652
|
status: run.status ?? 'unknown',
|
|
1348
1653
|
ended_at: run.ended_at ?? Date.now(),
|
|
1349
1654
|
error: sanitizeApprovalContext(run.error ?? run.result?.error ?? null, 'error'),
|
|
@@ -1540,8 +1845,42 @@ export class Hub {
|
|
|
1540
1845
|
this.save();
|
|
1541
1846
|
}
|
|
1542
1847
|
|
|
1848
|
+
/** 取(或建)同 `(cwd, permission)` 的共享 ACP 进程宿主。 */
|
|
1849
|
+
acquireHost(cwd, permission) {
|
|
1850
|
+
const key = `${cwd}\u0000${permission}`;
|
|
1851
|
+
let host = this.hosts.get(key);
|
|
1852
|
+
if (!host) {
|
|
1853
|
+
host = new SessionHost({ cwd, permission, log: this.log, hub: this });
|
|
1854
|
+
this.hosts.set(key, host);
|
|
1855
|
+
}
|
|
1856
|
+
return host;
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1859
|
+
forgetHost(host) {
|
|
1860
|
+
for (const [k, v] of this.hosts) {
|
|
1861
|
+
if (v === host) this.hosts.delete(k);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
/**
|
|
1866
|
+
* 共享进程下,某个子进程 PID 上还挂着哪些**别的**会话。
|
|
1867
|
+
*
|
|
1868
|
+
* 用途只有一个:`takeover` 要杀这个 PID 之前,先看看会不会连坐 ——
|
|
1869
|
+
* 杀一个还载着三个会话的宿主,代价是那三个会话的进行中回合一起断。
|
|
1870
|
+
* 只有本服务自己的宿主池查得清这件事;别的实例的宿主编号外部,查不到就只能让调用方
|
|
1871
|
+
* 自己用 `force` 承担。
|
|
1872
|
+
*/
|
|
1873
|
+
hostVictimsOf(pid, exceptId) {
|
|
1874
|
+
if (!pid) return [];
|
|
1875
|
+
for (const host of this.hosts.values()) {
|
|
1876
|
+
if (host.pid !== pid) continue;
|
|
1877
|
+
return [...host.conversations.keys()].filter((id) => id !== exceptId);
|
|
1878
|
+
}
|
|
1879
|
+
return [];
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1543
1882
|
/** 新建一个会话:拉起进程 + ACP 初始化 + session/new。 */
|
|
1544
|
-
async create({ cwd, permission = DEFAULT_PERMISSION, onApproval, titleHint, reasoningEffort, provider, model } = {}) {
|
|
1883
|
+
async create({ cwd, permission = DEFAULT_PERMISSION, onApproval, titleHint, reasoningEffort, provider, model, keepAlive = false } = {}) {
|
|
1545
1884
|
if (!cwd) {
|
|
1546
1885
|
throw new Error(
|
|
1547
1886
|
'没有可用的工作目录。你既没传 cwd,客户端也没有提供当前打开的项目(MCP roots)。\n' +
|
|
@@ -1559,6 +1898,14 @@ export class Hub {
|
|
|
1559
1898
|
if (!PERMISSION_TIERS.includes(permission)) {
|
|
1560
1899
|
throw new Error(`permission 必须是 ${PERMISSION_TIERS.join(' | ')} 之一`);
|
|
1561
1900
|
}
|
|
1901
|
+
// ★ 0.5.0:danger-full-access 不再默认可用。它把整机写权限交给调用方,
|
|
1902
|
+
// 而本服务可能被任何 MCP 客户端拉起;必须由机器所有者显式放行。
|
|
1903
|
+
if (permission === 'danger-full-access' && !ALLOW_FULL_ACCESS) {
|
|
1904
|
+
throw new Error(
|
|
1905
|
+
'permission=danger-full-access 需要机器侧显式允许:设置 DSH_MCP_ALLOW_FULL_ACCESS=1 后重试。' +
|
|
1906
|
+
' 默认请用 workspace-write(写入限制在工作区内)或 read-only。',
|
|
1907
|
+
);
|
|
1908
|
+
}
|
|
1562
1909
|
const policy = onApproval ?? defaultApprovalPolicy(permission);
|
|
1563
1910
|
if (!APPROVAL_POLICIES.includes(policy)) {
|
|
1564
1911
|
throw new Error(`on_approval 必须是 ${APPROVAL_POLICIES.join(' | ')} 之一`);
|
|
@@ -1582,26 +1929,31 @@ export class Hub {
|
|
|
1582
1929
|
// 与其让用户以为服务坏了,不如在这里把原因和出路一起说清楚。
|
|
1583
1930
|
const homeProblem = homeWorkspaceProblem(cwd, permission);
|
|
1584
1931
|
if (homeProblem) throw new Error(homeProblem);
|
|
1585
|
-
const
|
|
1586
|
-
|
|
1587
|
-
permission
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1932
|
+
const shared = SHARED_PROCESS;
|
|
1933
|
+
const proc = shared
|
|
1934
|
+
? this.acquireHost(cwd, permission)
|
|
1935
|
+
: new AcpProcess({
|
|
1936
|
+
cwd,
|
|
1937
|
+
permission,
|
|
1938
|
+
log: this.log,
|
|
1939
|
+
onNotification: () => {},
|
|
1940
|
+
onPermissionRequest: () => ({ outcome: { outcome: 'cancelled' } }),
|
|
1941
|
+
});
|
|
1942
|
+
if (!shared) proc.start();
|
|
1593
1943
|
let createdSessionId = null;
|
|
1944
|
+
let conv = null;
|
|
1594
1945
|
try {
|
|
1595
1946
|
await proc.initialize();
|
|
1596
1947
|
const res = await proc.request('session/new', { cwd, mcpServers: [] });
|
|
1597
1948
|
createdSessionId = res.sessionId;
|
|
1598
|
-
|
|
1949
|
+
conv = new Conversation(
|
|
1599
1950
|
{
|
|
1600
1951
|
id: res.sessionId,
|
|
1601
1952
|
cwd,
|
|
1602
1953
|
permission,
|
|
1603
1954
|
onApproval: policy,
|
|
1604
1955
|
titleHint,
|
|
1956
|
+
keepAlive: keepAlive === true,
|
|
1605
1957
|
reasoningEffort: effort,
|
|
1606
1958
|
provider: provider ?? null,
|
|
1607
1959
|
model: model ?? null,
|
|
@@ -1613,10 +1965,13 @@ export class Hub {
|
|
|
1613
1965
|
// ★ 新建会话的进程也要登记持有者 —— 走的是 Hub.create 这条独立路径,
|
|
1614
1966
|
// 不登记的话 dsh_takeover 会把"本服务自己持有的会话"误判成 none 而拒绝抢占。
|
|
1615
1967
|
writeMarker(res.sessionId, { childPid: proc.pid, cwd });
|
|
1616
|
-
proc.
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1968
|
+
if (shared) proc.attach(conv);
|
|
1969
|
+
else {
|
|
1970
|
+
proc.attachRoutes({
|
|
1971
|
+
onNotification: (params) => conv.onUpdate(params),
|
|
1972
|
+
onPermissionRequest: (params) => conv.onPermissionRequest(params),
|
|
1973
|
+
});
|
|
1974
|
+
}
|
|
1620
1975
|
// 套用会话级配置(思考深度默认 max;ACP 自己的默认是 Provider default)
|
|
1621
1976
|
conv.lastConfigApplied = await applySessionConfig(proc, res.sessionId, conv.cfg);
|
|
1622
1977
|
// ★ 无效的 provider/model 必须 fail fast:旧行为是建出会话、静默回退
|
|
@@ -1651,7 +2006,11 @@ export class Hub {
|
|
|
1651
2006
|
// 失败路径也要清掉写锁登记:session/new 可能已经成功、登记已写入,
|
|
1652
2007
|
// 但会话最终没有注册(例如无效 provider/model 被 fail-fast)。留下 marker
|
|
1653
2008
|
// 会被 dsh_list/dsh_takeover 误报成“孤儿持有者”,也会在 locks 目录里积垃圾。
|
|
1654
|
-
const stopped =
|
|
2009
|
+
const stopped = shared
|
|
2010
|
+
? conv
|
|
2011
|
+
? await proc.detach(conv).catch(() => false)
|
|
2012
|
+
: await proc.stop().catch(() => false)
|
|
2013
|
+
: await proc.stop().catch(() => false);
|
|
1655
2014
|
if (createdSessionId && stopped) removeMarker(createdSessionId);
|
|
1656
2015
|
throw e;
|
|
1657
2016
|
}
|
|
@@ -1728,7 +2087,7 @@ export class Hub {
|
|
|
1728
2087
|
|
|
1729
2088
|
/** 空闲回收:停掉闲置进程,会话本身保留(可 resume 复活)。
|
|
1730
2089
|
*
|
|
1731
|
-
* ★ `DSH_MCP_IDLE_TTL_MS=0
|
|
2090
|
+
* ★ `DSH_MCP_IDLE_TTL_MS=0` = **永不回收**(0.4.0 起默认是 10 分钟,不再是默认值)。
|
|
1732
2091
|
* 理由(实测,见 USAGE-NOTES §3.10~3.12):空闲回收是写锁**唯一**会变空的时刻,
|
|
1733
2092
|
* 而只要锁一空,你在 web 里点开那条会话,`dsh web` 就会**永久**持有它
|
|
1734
2093
|
* (切走 ✗ 等待 ✗ 归档 ✗ 都不释放),本服务之后每一次 resume 都失败 ——
|
|
@@ -1768,30 +2127,75 @@ export class Hub {
|
|
|
1768
2127
|
reapable.push(c);
|
|
1769
2128
|
}
|
|
1770
2129
|
|
|
1771
|
-
// 回收哪些:① 空闲超过 TTL
|
|
2130
|
+
// 回收哪些:① 空闲超过 TTL;② 超过 MAX_LIVE;③ 超过全局 RSS 预算。
|
|
2131
|
+
// keep_alive 会话不受 ① ② 约束;③ 是系统级硬上限,最后仍可能回收它。
|
|
1772
2132
|
const victims = new Set();
|
|
2133
|
+
const reapableNormal = reapable.filter((c) => !c.keepAlive);
|
|
1773
2134
|
if (IDLE_TTL_MS > 0) {
|
|
1774
|
-
for (const c of
|
|
2135
|
+
for (const c of reapableNormal) if (c.lastUsedAt <= cutoff) victims.add(c);
|
|
1775
2136
|
}
|
|
1776
2137
|
if (MAX_LIVE > 0) {
|
|
1777
2138
|
// 保活窗口 = 最近用过的 MAX_LIVE 个;超出的按"最久没用"先回收
|
|
1778
|
-
const byAge =
|
|
2139
|
+
const byAge = reapableNormal.slice().sort((a, b) => a.lastUsedAt - b.lastUsedAt);
|
|
1779
2140
|
const excess = byAge.length - MAX_LIVE;
|
|
1780
2141
|
for (let i = 0; i < excess; i++) victims.add(byAge[i]);
|
|
1781
2142
|
}
|
|
2143
|
+
if (MAX_RSS_MB > 0) {
|
|
2144
|
+
// 按实际 RSS 而不是会话数:上下文大小差异很大,按个数限制经常低估。
|
|
2145
|
+
let total = 0;
|
|
2146
|
+
const rss = new Map();
|
|
2147
|
+
const seenPid = new Set();
|
|
2148
|
+
for (const c of this.conversations.values()) {
|
|
2149
|
+
if (!c.proc?.alive) continue;
|
|
2150
|
+
const pid = c.proc.pid;
|
|
2151
|
+
const mb = rssMb(pid) ?? 0;
|
|
2152
|
+
rss.set(c, mb);
|
|
2153
|
+
// 共享进程只算一次
|
|
2154
|
+
if (pid && seenPid.has(pid)) continue;
|
|
2155
|
+
if (pid) seenPid.add(pid);
|
|
2156
|
+
total += mb;
|
|
2157
|
+
}
|
|
2158
|
+
if (total > MAX_RSS_MB) {
|
|
2159
|
+
// 先收非 keep_alive 的最久未用者;仍然超预算才动 keep_alive。
|
|
2160
|
+
const pool = reapable
|
|
2161
|
+
.filter((c) => !victims.has(c))
|
|
2162
|
+
.sort((a, b) =>
|
|
2163
|
+
a.keepAlive === b.keepAlive ? a.lastUsedAt - b.lastUsedAt : a.keepAlive ? 1 : -1,
|
|
2164
|
+
);
|
|
2165
|
+
for (const c of pool) {
|
|
2166
|
+
victims.add(c);
|
|
2167
|
+
total -= rss.get(c) ?? 0;
|
|
2168
|
+
if (total <= MAX_RSS_MB) break;
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
1782
2172
|
|
|
1783
2173
|
for (const c of victims) {
|
|
2174
|
+
if (c.recycling) await c.recycling;
|
|
1784
2175
|
if (!c.proc?.alive) continue;
|
|
1785
2176
|
this.log.info(
|
|
1786
2177
|
`[hub] 回收会话 ${c.id} 的进程(${IDLE_TTL_MS > 0 && c.lastUsedAt <= cutoff ? '空闲超时' : `保活上限 ${MAX_LIVE}`};可 resume 复活)`,
|
|
1787
2178
|
);
|
|
1788
2179
|
const proc = c.proc;
|
|
1789
|
-
|
|
1790
|
-
//
|
|
1791
|
-
//
|
|
1792
|
-
//
|
|
1793
|
-
const
|
|
1794
|
-
|
|
2180
|
+
// ★ 先把 stop 登记成 recycling,再 await:stop 可能要几秒,这个窗口里到达的
|
|
2181
|
+
// dsh_send 会在 ensureAlive 里 await 它,而不是为同一会话再拉一个进程去抢
|
|
2182
|
+
// **尚未释放**的写锁。proc 也要等 stop 落定后才置空,否则快路径会拿到垂死进程。
|
|
2183
|
+
// 共享进程:detach 只摘掉这个会话(内部 session/close),最后一个离开才停进程。
|
|
2184
|
+
const stopping = typeof proc.detach === 'function' ? proc.detach(c) : proc.stop();
|
|
2185
|
+
c.recycling = stopping
|
|
2186
|
+
.catch(() => false)
|
|
2187
|
+
.then((stopped) => {
|
|
2188
|
+
// ★ 顺序要紧:**先确认子进程真的退出(写锁真的释放),再删登记**。
|
|
2189
|
+
// 反过来的话,一旦它没死透,锁的持有者就变成"无登记的未知进程" ——
|
|
2190
|
+
// 既报不清是谁,连 dsh_takeover 都会拒绝(判成 none)。
|
|
2191
|
+
if (stopped) removeMarker(c.id);
|
|
2192
|
+
return stopped;
|
|
2193
|
+
})
|
|
2194
|
+
.finally(() => {
|
|
2195
|
+
if (c.proc === proc) c.proc = null;
|
|
2196
|
+
c.recycling = null;
|
|
2197
|
+
});
|
|
2198
|
+
await c.recycling;
|
|
1795
2199
|
}
|
|
1796
2200
|
} catch (e) {
|
|
1797
2201
|
this.log.info(`[hub] 回收周期异常(已忽略,下个周期继续): ${e.message}`);
|
|
@@ -1811,6 +2215,7 @@ export class Hub {
|
|
|
1811
2215
|
const skippedBusy = [];
|
|
1812
2216
|
const failed = [];
|
|
1813
2217
|
for (const c of this.conversations.values()) {
|
|
2218
|
+
if (c.recycling) await c.recycling;
|
|
1814
2219
|
if (!c.proc?.alive) continue;
|
|
1815
2220
|
// ★ 默认不打断正在跑的回合:all=true 是"腾内存",不是"取消任务"。
|
|
1816
2221
|
// 确实要连跑着的也停掉时传 force=true。
|
|
@@ -1819,8 +2224,15 @@ export class Hub {
|
|
|
1819
2224
|
continue;
|
|
1820
2225
|
}
|
|
1821
2226
|
const proc = c.proc;
|
|
1822
|
-
|
|
1823
|
-
const
|
|
2227
|
+
// stop 期间保持 proc 可见 + recycling 屏障,落定后再置空。
|
|
2228
|
+
const stopping = typeof proc.detach === 'function' ? proc.detach(c) : proc.stop();
|
|
2229
|
+
c.recycling = stopping
|
|
2230
|
+
.catch(() => false)
|
|
2231
|
+
.finally(() => {
|
|
2232
|
+
if (c.proc === proc) c.proc = null;
|
|
2233
|
+
c.recycling = null;
|
|
2234
|
+
});
|
|
2235
|
+
const stopped = await c.recycling;
|
|
1824
2236
|
if (stopped) {
|
|
1825
2237
|
removeMarker(c.id);
|
|
1826
2238
|
released.push(c.id);
|
|
@@ -1838,12 +2250,21 @@ export class Hub {
|
|
|
1838
2250
|
if (this.#reaper) clearInterval(this.#reaper);
|
|
1839
2251
|
this.#reaper = null;
|
|
1840
2252
|
for (const c of this.conversations.values()) {
|
|
2253
|
+
if (c.recycling) await c.recycling;
|
|
1841
2254
|
const proc = c.proc;
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
2255
|
+
if (proc) {
|
|
2256
|
+
const stopping = typeof proc.detach === 'function' ? proc.detach(c) : proc.stop();
|
|
2257
|
+
c.recycling = stopping
|
|
2258
|
+
.catch(() => false)
|
|
2259
|
+
.finally(() => {
|
|
2260
|
+
if (c.proc === proc) c.proc = null;
|
|
2261
|
+
c.recycling = null;
|
|
2262
|
+
});
|
|
2263
|
+
const stopped = await c.recycling;
|
|
2264
|
+
// 只有确认子进程退出、锁真的释放后才删登记;否则留给下个实例归因。
|
|
2265
|
+
if (stopped) removeMarker(c.id);
|
|
2266
|
+
else this.log.info(`[hub] 关闭 ${c.id} 时进程未确认退出,保留写锁登记`);
|
|
2267
|
+
}
|
|
1847
2268
|
}
|
|
1848
2269
|
this.save();
|
|
1849
2270
|
}
|