dsh-desktop-enhance 0.6.13 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1
- package/lib/client.js +832 -7
- package/lib/index.d.ts +214 -5
- package/lib/index.js +928 -1
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import Schema from "@deepseek-ai/schemastery";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import * as nodeInspector from "node:inspector";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
4
5
|
//#region src/shared/session-model.ts
|
|
5
6
|
const SESSION_MODEL_PROJECTION = "desktop-enhance.session-model";
|
|
6
7
|
//#endregion
|
|
@@ -133,6 +134,7 @@ const SUGGEST_EFFORTS_ROUTE = "/api/desktop-enhance/suggest-efforts";
|
|
|
133
134
|
const SESSION_INFO_ROUTE = "/api/desktop-enhance/session-info";
|
|
134
135
|
const TOOLS_ROUTE = "/api/desktop-enhance/tools";
|
|
135
136
|
const SKILLS_ROUTE = "/api/desktop-enhance/skills";
|
|
137
|
+
const CONTEXT_ROUTE = "/api/desktop-enhance/context";
|
|
136
138
|
//#endregion
|
|
137
139
|
//#region src/suggest/host.ts
|
|
138
140
|
const SUGGEST_PATH = SUGGEST_ROUTE;
|
|
@@ -2519,6 +2521,894 @@ function registerSkillsRoute(ctx) {
|
|
|
2519
2521
|
};
|
|
2520
2522
|
}
|
|
2521
2523
|
//#endregion
|
|
2524
|
+
//#region src/shared/context-policy.ts
|
|
2525
|
+
const DEFAULT_THRESHOLD_RATIO = .8;
|
|
2526
|
+
const DEFAULT_HEADROOM_TOKENS = 65536;
|
|
2527
|
+
function nativeThresholdOf(input) {
|
|
2528
|
+
const { contextWindow, reservedOutputTokens, headroomTokens, thresholdRatio } = input;
|
|
2529
|
+
if (!Number.isFinite(contextWindow) || contextWindow <= 0) return null;
|
|
2530
|
+
if (!Number.isFinite(reservedOutputTokens) || reservedOutputTokens < 0) return null;
|
|
2531
|
+
const headroom = Number.isFinite(headroomTokens) && headroomTokens >= 0 ? headroomTokens : DEFAULT_HEADROOM_TOKENS;
|
|
2532
|
+
const ratio = Number.isFinite(thresholdRatio) && thresholdRatio > 0 && thresholdRatio <= 1 ? thresholdRatio : DEFAULT_THRESHOLD_RATIO;
|
|
2533
|
+
const byConstraint = contextWindow - reservedOutputTokens - headroom;
|
|
2534
|
+
const byRatio = contextWindow * ratio;
|
|
2535
|
+
const threshold = Math.floor(Math.min(byRatio, byConstraint));
|
|
2536
|
+
return threshold > 0 ? threshold : null;
|
|
2537
|
+
}
|
|
2538
|
+
function resolvePolicy(input, cap) {
|
|
2539
|
+
const nativeThreshold = nativeThresholdOf(input);
|
|
2540
|
+
if (nativeThreshold === null) return null;
|
|
2541
|
+
if (cap === null) return {
|
|
2542
|
+
nativeThreshold,
|
|
2543
|
+
effectiveThreshold: nativeThreshold,
|
|
2544
|
+
capped: false
|
|
2545
|
+
};
|
|
2546
|
+
const normalized = clampCap(cap);
|
|
2547
|
+
if (normalized === null) return {
|
|
2548
|
+
nativeThreshold,
|
|
2549
|
+
effectiveThreshold: nativeThreshold,
|
|
2550
|
+
capped: false
|
|
2551
|
+
};
|
|
2552
|
+
return {
|
|
2553
|
+
nativeThreshold,
|
|
2554
|
+
effectiveThreshold: Math.min(normalized, nativeThreshold),
|
|
2555
|
+
capped: normalized > nativeThreshold
|
|
2556
|
+
};
|
|
2557
|
+
}
|
|
2558
|
+
function clampCap(cap) {
|
|
2559
|
+
if (cap === null || typeof cap !== "number" || !Number.isFinite(cap)) return null;
|
|
2560
|
+
const rounded = Math.round(cap);
|
|
2561
|
+
if (rounded < 8e3 || rounded > 4e6) return null;
|
|
2562
|
+
return rounded;
|
|
2563
|
+
}
|
|
2564
|
+
const CAPS_SEPARATOR = ";";
|
|
2565
|
+
const CAPS_PAIR = ":";
|
|
2566
|
+
function isValidSessionKey(value) {
|
|
2567
|
+
return value !== "" && !/[\s;:]/.test(value);
|
|
2568
|
+
}
|
|
2569
|
+
function decodeCaps(raw) {
|
|
2570
|
+
const out = new Map();
|
|
2571
|
+
if (typeof raw !== "string" || raw.trim() === "") return out;
|
|
2572
|
+
for (const entry of raw.split(CAPS_SEPARATOR)) {
|
|
2573
|
+
const trimmed = entry.trim();
|
|
2574
|
+
if (trimmed === "") continue;
|
|
2575
|
+
const index = trimmed.indexOf(CAPS_PAIR);
|
|
2576
|
+
if (index <= 0) continue;
|
|
2577
|
+
const sessionId = trimmed.slice(0, index).trim();
|
|
2578
|
+
if (!isValidSessionKey(sessionId)) continue;
|
|
2579
|
+
const normalized = clampCap(Number(trimmed.slice(index + 1).trim()));
|
|
2580
|
+
if (normalized === null) continue;
|
|
2581
|
+
out.delete(sessionId);
|
|
2582
|
+
out.set(sessionId, normalized);
|
|
2583
|
+
}
|
|
2584
|
+
return out;
|
|
2585
|
+
}
|
|
2586
|
+
function encodeCaps(map) {
|
|
2587
|
+
const entries = [];
|
|
2588
|
+
for (const [rawSessionId, rawTokens] of map.entries()) {
|
|
2589
|
+
const sessionId = typeof rawSessionId === "string" ? rawSessionId.trim() : "";
|
|
2590
|
+
if (!isValidSessionKey(sessionId)) continue;
|
|
2591
|
+
const tokens = clampCap(typeof rawTokens === "number" ? rawTokens : null);
|
|
2592
|
+
if (tokens === null) continue;
|
|
2593
|
+
entries.push([sessionId, tokens]);
|
|
2594
|
+
}
|
|
2595
|
+
entries.sort((left, right) => left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0);
|
|
2596
|
+
return (entries.length > 200 ? entries.slice(entries.length - 200) : entries).map(([sessionId, tokens]) => `${sessionId}${CAPS_PAIR}${String(tokens)}`).join(CAPS_SEPARATOR);
|
|
2597
|
+
}
|
|
2598
|
+
function capOf(raw, sessionId) {
|
|
2599
|
+
const sid = typeof sessionId === "string" ? sessionId.trim() : "";
|
|
2600
|
+
if (sid === "") return null;
|
|
2601
|
+
return decodeCaps(raw).get(sid) ?? null;
|
|
2602
|
+
}
|
|
2603
|
+
function withCap(raw, sessionId, cap) {
|
|
2604
|
+
const sid = typeof sessionId === "string" ? sessionId.trim() : "";
|
|
2605
|
+
const map = decodeCaps(raw);
|
|
2606
|
+
if (!isValidSessionKey(sid)) return encodeCaps(map);
|
|
2607
|
+
map.delete(sid);
|
|
2608
|
+
const normalized = clampCap(cap);
|
|
2609
|
+
if (normalized !== null) map.set(sid, normalized);
|
|
2610
|
+
return encodeCaps(map);
|
|
2611
|
+
}
|
|
2612
|
+
//#endregion
|
|
2613
|
+
//#region src/context-manager/host.ts
|
|
2614
|
+
const CONTEXT_PATH = CONTEXT_ROUTE;
|
|
2615
|
+
function unwrapFlag(cell) {
|
|
2616
|
+
if (cell === null || typeof cell !== "object") return typeof cell === "boolean" ? cell : true;
|
|
2617
|
+
const get = cell.get;
|
|
2618
|
+
if (typeof get !== "function") return true;
|
|
2619
|
+
try {
|
|
2620
|
+
const value = get.call(cell);
|
|
2621
|
+
return typeof value === "boolean" ? value : true;
|
|
2622
|
+
} catch {
|
|
2623
|
+
return true;
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
function unwrapText(cell) {
|
|
2627
|
+
if (typeof cell === "string") return cell;
|
|
2628
|
+
if (cell === null || typeof cell !== "object") return "";
|
|
2629
|
+
const get = cell.get;
|
|
2630
|
+
if (typeof get !== "function") return "";
|
|
2631
|
+
try {
|
|
2632
|
+
const value = get.call(cell);
|
|
2633
|
+
return typeof value === "string" ? value : "";
|
|
2634
|
+
} catch {
|
|
2635
|
+
return "";
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
function readCap(config, sessionId) {
|
|
2639
|
+
if (config === null || config === void 0 || typeof config !== "object") return null;
|
|
2640
|
+
const raw = config.sessionCompactionCaps;
|
|
2641
|
+
return capOf(unwrapText(raw), sessionId);
|
|
2642
|
+
}
|
|
2643
|
+
function readContextManagerEnabled(config) {
|
|
2644
|
+
if (config === null || config === void 0 || typeof config !== "object") return true;
|
|
2645
|
+
return unwrapFlag(config.contextManager);
|
|
2646
|
+
}
|
|
2647
|
+
async function resolveTargetAgent(ctx, sessionId) {
|
|
2648
|
+
const live = ctx.get("agents")?.get?.(sessionId);
|
|
2649
|
+
if (live !== void 0) return live;
|
|
2650
|
+
const controller = ctx.get("sessionController");
|
|
2651
|
+
const resolve = controller?.resolveAgent;
|
|
2652
|
+
if (typeof resolve !== "function") return void 0;
|
|
2653
|
+
try {
|
|
2654
|
+
const resolved = await resolve.call(controller, sessionId);
|
|
2655
|
+
if (resolved !== null && typeof resolved === "object" && "session" in resolved) return resolved;
|
|
2656
|
+
} catch {
|
|
2657
|
+
return;
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
function serviceFor(ctx, agent, name) {
|
|
2661
|
+
const scoped = ctx.get("agentPresets")?.serviceFor?.(agent, name);
|
|
2662
|
+
if (scoped !== void 0) return scoped;
|
|
2663
|
+
return ctx.get(name);
|
|
2664
|
+
}
|
|
2665
|
+
async function nativePolicyOf(ctx, agent, signal) {
|
|
2666
|
+
const session = agent.session;
|
|
2667
|
+
const contextWindow = session.requestContext?.()?.contextWindow;
|
|
2668
|
+
if (typeof contextWindow !== "number" || !Number.isFinite(contextWindow) || contextWindow <= 0) return null;
|
|
2669
|
+
const config = (session.requestHeader?.())?.config;
|
|
2670
|
+
let reservedOutputTokens = typeof config?.maxTokens === "number" && Number.isFinite(config.maxTokens) ? config.maxTokens : 0;
|
|
2671
|
+
if (reservedOutputTokens === 0 && typeof config?.provider === "string" && typeof config.model === "string") {
|
|
2672
|
+
const llm = serviceFor(ctx, agent, "llm");
|
|
2673
|
+
try {
|
|
2674
|
+
const info = await llm?.resolveModelInfo?.(config.provider, config.model, signal);
|
|
2675
|
+
if (typeof info?.defaultMaxTokens === "number" && Number.isFinite(info.defaultMaxTokens)) reservedOutputTokens = info.defaultMaxTokens;
|
|
2676
|
+
} catch {}
|
|
2677
|
+
}
|
|
2678
|
+
const policy = serviceFor(ctx, agent, "compaction")?.config;
|
|
2679
|
+
const exact = policy?.modelPolicies?.find((row) => row.provider === config?.provider && row.model === config?.model);
|
|
2680
|
+
const retainTokens = exact?.retainTokens !== void 0 ? exact.retainTokens : exact?.retainRatio !== void 0 ? Math.floor((contextWindow - reservedOutputTokens) * exact.retainRatio) : policy?.retainTokens ?? Math.floor((contextWindow - reservedOutputTokens) * (policy?.retainRatio ?? .16));
|
|
2681
|
+
return {
|
|
2682
|
+
contextWindow,
|
|
2683
|
+
reservedOutputTokens,
|
|
2684
|
+
headroomTokens: exact?.headroomTokens ?? policy?.headroomTokens ?? 65536,
|
|
2685
|
+
thresholdRatio: exact?.thresholdRatio ?? policy?.thresholdRatio ?? .8,
|
|
2686
|
+
retainTokens
|
|
2687
|
+
};
|
|
2688
|
+
}
|
|
2689
|
+
function measurePressure(ctx, agent) {
|
|
2690
|
+
const measurement = serviceFor(ctx, agent, "tokenMeter")?.measure?.(agent.session);
|
|
2691
|
+
const used = measurement?.projectedTokens ?? measurement?.totalTokens;
|
|
2692
|
+
const window = agent.session.requestContext?.()?.contextWindow;
|
|
2693
|
+
if (typeof used !== "number" || !Number.isFinite(used)) return null;
|
|
2694
|
+
if (typeof window !== "number" || !Number.isFinite(window) || window <= 0) return null;
|
|
2695
|
+
return {
|
|
2696
|
+
used: Math.max(0, Math.round(used)),
|
|
2697
|
+
window
|
|
2698
|
+
};
|
|
2699
|
+
}
|
|
2700
|
+
function failed(message) {
|
|
2701
|
+
return {
|
|
2702
|
+
state: "failed",
|
|
2703
|
+
prunedCount: 0,
|
|
2704
|
+
charsRemoved: 0,
|
|
2705
|
+
message
|
|
2706
|
+
};
|
|
2707
|
+
}
|
|
2708
|
+
const PRUNE_STATES = [
|
|
2709
|
+
"done",
|
|
2710
|
+
"queued",
|
|
2711
|
+
"noop",
|
|
2712
|
+
"failed"
|
|
2713
|
+
];
|
|
2714
|
+
function isPruneOutcome(value) {
|
|
2715
|
+
if (value === null || typeof value !== "object") return false;
|
|
2716
|
+
const state = value.state;
|
|
2717
|
+
return typeof state === "string" && PRUNE_STATES.includes(state);
|
|
2718
|
+
}
|
|
2719
|
+
function createContextControl(ctx, options) {
|
|
2720
|
+
const jobs = new Map();
|
|
2721
|
+
const results = new Map();
|
|
2722
|
+
let revision = 0;
|
|
2723
|
+
let disposed = false;
|
|
2724
|
+
function publish(job, outcome) {
|
|
2725
|
+
if (!disposed && jobs.get(job.agent.id) === job) results.set(job.agent.id, {
|
|
2726
|
+
outcome,
|
|
2727
|
+
revision: ++revision
|
|
2728
|
+
});
|
|
2729
|
+
return outcome;
|
|
2730
|
+
}
|
|
2731
|
+
function release(job) {
|
|
2732
|
+
job.cancelWait?.();
|
|
2733
|
+
if (jobs.get(job.agent.id) === job) jobs.delete(job.agent.id);
|
|
2734
|
+
}
|
|
2735
|
+
function pruneStatus(sessionId) {
|
|
2736
|
+
const result = results.get(sessionId);
|
|
2737
|
+
return result === void 0 ? { pruneRevision: 0 } : {
|
|
2738
|
+
pruneOutcome: result.outcome,
|
|
2739
|
+
pruneRevision: result.revision
|
|
2740
|
+
};
|
|
2741
|
+
}
|
|
2742
|
+
async function executePrune(agent) {
|
|
2743
|
+
const session = agent.session;
|
|
2744
|
+
const pruner = serviceFor(ctx, agent, "toolResultPruner");
|
|
2745
|
+
if (pruner === void 0 || typeof pruner.pruneSession !== "function") return failed("这个组合没有挂载工具输出剪枝服务");
|
|
2746
|
+
let result;
|
|
2747
|
+
let pruneError;
|
|
2748
|
+
const before = session.snapshotEvents?.() ?? [];
|
|
2749
|
+
try {
|
|
2750
|
+
result = pruner.pruneSession(session);
|
|
2751
|
+
} catch (error) {
|
|
2752
|
+
pruneError = error instanceof Error ? error.message : String(error);
|
|
2753
|
+
const originals = new Map(before.map((event) => [event.seq, event]));
|
|
2754
|
+
const replacements = (session.snapshotEvents?.() ?? []).slice(before.length).filter((event) => event.type === "tool/result" && typeof event.surfaceOp === "object" && event.surfaceOp.op === "replace" && event.sourceEventSeqs?.length === 1 && originals.get(event.sourceEventSeqs[0])?.type === "tool/result");
|
|
2755
|
+
const chars = (message) => (message?.content ?? []).reduce((sum, block) => sum + (block.type === "text" ? Array.from(block.text ?? "").length : 0), 0);
|
|
2756
|
+
result = {
|
|
2757
|
+
pruned: replacements,
|
|
2758
|
+
charsRemoved: replacements.reduce((sum, event) => sum + Math.max(0, chars(originals.get(event.sourceEventSeqs[0])?.data?.message) - chars(event.data?.message)), 0)
|
|
2759
|
+
};
|
|
2760
|
+
}
|
|
2761
|
+
const prunedCount = Array.isArray(result.pruned) ? result.pruned.length : 0;
|
|
2762
|
+
const charsRemoved = typeof result.charsRemoved === "number" && Number.isFinite(result.charsRemoved) ? result.charsRemoved : 0;
|
|
2763
|
+
if (prunedCount === 0) return pruneError === void 0 ? {
|
|
2764
|
+
state: "noop",
|
|
2765
|
+
prunedCount: 0,
|
|
2766
|
+
charsRemoved: 0,
|
|
2767
|
+
message: "没有超过长度阈值的工具输出"
|
|
2768
|
+
} : failed(pruneError);
|
|
2769
|
+
const sessions = serviceFor(ctx, agent, "sessions");
|
|
2770
|
+
try {
|
|
2771
|
+
if (sessions?.flush === void 0) throw new Error("没有可用的落盘服务");
|
|
2772
|
+
await sessions.flush(session);
|
|
2773
|
+
} catch (error) {
|
|
2774
|
+
return {
|
|
2775
|
+
state: "failed",
|
|
2776
|
+
prunedCount,
|
|
2777
|
+
charsRemoved,
|
|
2778
|
+
message: `剪枝已写入但落盘失败:${error instanceof Error ? error.message : String(error)}`
|
|
2779
|
+
};
|
|
2780
|
+
}
|
|
2781
|
+
return pruneError === void 0 ? {
|
|
2782
|
+
state: "done",
|
|
2783
|
+
prunedCount,
|
|
2784
|
+
charsRemoved
|
|
2785
|
+
} : {
|
|
2786
|
+
state: "failed",
|
|
2787
|
+
prunedCount,
|
|
2788
|
+
charsRemoved,
|
|
2789
|
+
message: pruneError
|
|
2790
|
+
};
|
|
2791
|
+
}
|
|
2792
|
+
function executeJob(job, signal) {
|
|
2793
|
+
if (job.task !== void 0) return job.task;
|
|
2794
|
+
job.cancelWait?.();
|
|
2795
|
+
job.task = Promise.resolve().then(async () => {
|
|
2796
|
+
if (disposed || jobs.get(job.agent.id) !== job) return failed("剪枝请求已取消");
|
|
2797
|
+
if (!readContextManagerEnabled(options.config())) return publish(job, failed("上下文管理已关闭"));
|
|
2798
|
+
if (signal?.aborted) return publish(job, failed("剪枝请求已取消"));
|
|
2799
|
+
return publish(job, await executePrune(job.agent));
|
|
2800
|
+
}).catch((error) => publish(job, failed(error instanceof Error ? error.message : String(error))));
|
|
2801
|
+
return job.task;
|
|
2802
|
+
}
|
|
2803
|
+
async function consumePending(sessionId) {
|
|
2804
|
+
const job = jobs.get(sessionId);
|
|
2805
|
+
if (job === void 0 || disposed) return;
|
|
2806
|
+
try {
|
|
2807
|
+
await executeJob(job);
|
|
2808
|
+
} finally {
|
|
2809
|
+
release(job);
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
async function afterIdle(job) {
|
|
2813
|
+
const agent = job.agent;
|
|
2814
|
+
if (agent.whenIdle === void 0 || agent.runMaintenance === void 0) {
|
|
2815
|
+
publish(job, failed("这个 Agent 没有可用的空闲维护接口"));
|
|
2816
|
+
release(job);
|
|
2817
|
+
return;
|
|
2818
|
+
}
|
|
2819
|
+
while (!disposed && jobs.get(agent.id) === job && job.task === void 0) {
|
|
2820
|
+
const ready = await new Promise((resolve, reject) => {
|
|
2821
|
+
job.cancelWait = () => resolve(false);
|
|
2822
|
+
agent.whenIdle?.().then(() => resolve(true), reject);
|
|
2823
|
+
}).catch((error) => {
|
|
2824
|
+
publish(job, failed(error instanceof Error ? error.message : String(error)));
|
|
2825
|
+
return false;
|
|
2826
|
+
});
|
|
2827
|
+
job.cancelWait = void 0;
|
|
2828
|
+
if (!ready) {
|
|
2829
|
+
if (job.task === void 0) release(job);
|
|
2830
|
+
return;
|
|
2831
|
+
}
|
|
2832
|
+
if (disposed || jobs.get(agent.id) !== job || job.task !== void 0) return;
|
|
2833
|
+
try {
|
|
2834
|
+
await agent.runMaintenance((signal) => executeJob(job, signal));
|
|
2835
|
+
release(job);
|
|
2836
|
+
return;
|
|
2837
|
+
} catch (error) {
|
|
2838
|
+
if (job.task !== void 0) {
|
|
2839
|
+
publish(job, failed(error instanceof Error ? error.message : String(error)));
|
|
2840
|
+
release(job);
|
|
2841
|
+
return;
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
}
|
|
2846
|
+
async function pruneOnce(sessionId) {
|
|
2847
|
+
if (disposed || !readContextManagerEnabled(options.config())) return failed("上下文管理已关闭");
|
|
2848
|
+
if (jobs.get(sessionId) !== void 0) return results.get(sessionId).outcome;
|
|
2849
|
+
const agent = await resolveTargetAgent(ctx, sessionId);
|
|
2850
|
+
if (agent === void 0) return failed("会话当前没有可用的 Agent");
|
|
2851
|
+
if (jobs.get(sessionId) !== void 0) return results.get(sessionId).outcome;
|
|
2852
|
+
if (disposed) return failed("上下文管理已关闭");
|
|
2853
|
+
const run = agent.runMaintenance;
|
|
2854
|
+
if (typeof run !== "function") return failed("这个 Agent 没有可用的维护接口");
|
|
2855
|
+
const job = { agent };
|
|
2856
|
+
jobs.set(sessionId, job);
|
|
2857
|
+
publish(job, {
|
|
2858
|
+
state: "queued",
|
|
2859
|
+
prunedCount: 0,
|
|
2860
|
+
charsRemoved: 0,
|
|
2861
|
+
message: "已排队,将在安全点执行"
|
|
2862
|
+
});
|
|
2863
|
+
try {
|
|
2864
|
+
const outcome = await run.call(agent, (signal) => executeJob(job, signal));
|
|
2865
|
+
return isPruneOutcome(outcome) ? outcome : publish(job, failed("维护区返回了无法识别的结果"));
|
|
2866
|
+
} catch (error) {
|
|
2867
|
+
if (job.task !== void 0) return publish(job, failed(error instanceof Error ? error.message : String(error)));
|
|
2868
|
+
afterIdle(job);
|
|
2869
|
+
return results.get(sessionId).outcome;
|
|
2870
|
+
} finally {
|
|
2871
|
+
if (job.task !== void 0) release(job);
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
function forgetAgent(agent) {
|
|
2875
|
+
const job = jobs.get(agent.id);
|
|
2876
|
+
if (job?.agent !== agent) return;
|
|
2877
|
+
publish(job, failed("Agent 已释放,剪枝请求已取消"));
|
|
2878
|
+
release(job);
|
|
2879
|
+
}
|
|
2880
|
+
async function dispose() {
|
|
2881
|
+
disposed = true;
|
|
2882
|
+
const tasks = [];
|
|
2883
|
+
for (const job of jobs.values()) {
|
|
2884
|
+
job.cancelWait?.();
|
|
2885
|
+
if (job.task !== void 0) tasks.push(job.task);
|
|
2886
|
+
}
|
|
2887
|
+
jobs.clear();
|
|
2888
|
+
results.clear();
|
|
2889
|
+
await Promise.allSettled(tasks);
|
|
2890
|
+
}
|
|
2891
|
+
async function snapshot(sessionId) {
|
|
2892
|
+
const agent = await resolveTargetAgent(ctx, sessionId);
|
|
2893
|
+
const cap = readCap(options.config(), sessionId);
|
|
2894
|
+
if (agent === void 0) return {
|
|
2895
|
+
...pruneStatus(sessionId),
|
|
2896
|
+
pressure: null,
|
|
2897
|
+
nativeThreshold: null,
|
|
2898
|
+
effectiveThreshold: null,
|
|
2899
|
+
capped: false,
|
|
2900
|
+
cap,
|
|
2901
|
+
measurement: "estimated",
|
|
2902
|
+
cannotCapReason: "会话当前没有可用的 Agent"
|
|
2903
|
+
};
|
|
2904
|
+
const pressure = measurePressure(ctx, agent);
|
|
2905
|
+
const input = await nativePolicyOf(ctx, agent);
|
|
2906
|
+
const resolved = input === null ? null : resolvePolicy(input, cap);
|
|
2907
|
+
if (resolved === null) return {
|
|
2908
|
+
...pruneStatus(sessionId),
|
|
2909
|
+
pressure,
|
|
2910
|
+
nativeThreshold: null,
|
|
2911
|
+
effectiveThreshold: null,
|
|
2912
|
+
capped: false,
|
|
2913
|
+
cap,
|
|
2914
|
+
measurement: "estimated",
|
|
2915
|
+
cannotCapReason: "这个模型没有声明上下文容量,无法计算压缩阈值"
|
|
2916
|
+
};
|
|
2917
|
+
return {
|
|
2918
|
+
...pruneStatus(sessionId),
|
|
2919
|
+
pressure,
|
|
2920
|
+
nativeThreshold: resolved.nativeThreshold,
|
|
2921
|
+
effectiveThreshold: resolved.effectiveThreshold,
|
|
2922
|
+
capped: resolved.capped,
|
|
2923
|
+
cap,
|
|
2924
|
+
measurement: "estimated"
|
|
2925
|
+
};
|
|
2926
|
+
}
|
|
2927
|
+
async function setCap(sessionId, cap) {
|
|
2928
|
+
await saveCap(sessionId, cap);
|
|
2929
|
+
return snapshot(sessionId);
|
|
2930
|
+
}
|
|
2931
|
+
function currentCapsRaw() {
|
|
2932
|
+
const config = options.config();
|
|
2933
|
+
if (config === null || typeof config !== "object") return "";
|
|
2934
|
+
const raw = config.sessionCompactionCaps;
|
|
2935
|
+
return unwrapText(raw);
|
|
2936
|
+
}
|
|
2937
|
+
async function saveCap(sessionId, cap) {
|
|
2938
|
+
const save = options.save;
|
|
2939
|
+
if (save !== void 0) {
|
|
2940
|
+
await save("sessionCompactionCaps", withCap(currentCapsRaw(), sessionId, cap));
|
|
2941
|
+
return;
|
|
2942
|
+
}
|
|
2943
|
+
const client = ctx.get("configEditor");
|
|
2944
|
+
if (typeof client?.entries !== "function" || typeof client.edit !== "function") throw new Error("这个部署没有可用的配置编辑器,阈值无法保存");
|
|
2945
|
+
const entry = client.entries().find((row) => row.options?.id === "desktop-enhance");
|
|
2946
|
+
if (entry === void 0) throw new Error("找不到 desktop-enhance 的配置行,阈值无法保存");
|
|
2947
|
+
await client.edit(entry, (current) => ({
|
|
2948
|
+
...current,
|
|
2949
|
+
sessionCompactionCaps: withCap(unwrapText(current.sessionCompactionCaps), sessionId, cap)
|
|
2950
|
+
}));
|
|
2951
|
+
}
|
|
2952
|
+
return {
|
|
2953
|
+
consumePending,
|
|
2954
|
+
forgetAgent,
|
|
2955
|
+
dispose,
|
|
2956
|
+
pruneOnce,
|
|
2957
|
+
snapshot,
|
|
2958
|
+
setCap
|
|
2959
|
+
};
|
|
2960
|
+
}
|
|
2961
|
+
function parseAction(body) {
|
|
2962
|
+
if (body === null || typeof body !== "object") return null;
|
|
2963
|
+
const raw = body;
|
|
2964
|
+
const sessionId = typeof raw.sessionId === "string" ? raw.sessionId.trim() : "";
|
|
2965
|
+
if (sessionId === "") return null;
|
|
2966
|
+
if (raw.action === "setCap") {
|
|
2967
|
+
const cap = raw.cap;
|
|
2968
|
+
if (cap === null) return {
|
|
2969
|
+
kind: "cap",
|
|
2970
|
+
sessionId,
|
|
2971
|
+
cap: null
|
|
2972
|
+
};
|
|
2973
|
+
if (typeof cap === "number" && Number.isFinite(cap)) return {
|
|
2974
|
+
kind: "cap",
|
|
2975
|
+
sessionId,
|
|
2976
|
+
cap
|
|
2977
|
+
};
|
|
2978
|
+
return null;
|
|
2979
|
+
}
|
|
2980
|
+
if (raw.action === "prune") return {
|
|
2981
|
+
kind: "prune",
|
|
2982
|
+
sessionId
|
|
2983
|
+
};
|
|
2984
|
+
return null;
|
|
2985
|
+
}
|
|
2986
|
+
async function handleContextRequest(control, request) {
|
|
2987
|
+
const sessionId = parseSessionIdFromRequest(request);
|
|
2988
|
+
if (sessionId === void 0) return jsonResponse({ error: "missing-session" }, 400);
|
|
2989
|
+
let body = null;
|
|
2990
|
+
try {
|
|
2991
|
+
body = await request?.json();
|
|
2992
|
+
} catch {
|
|
2993
|
+
body = null;
|
|
2994
|
+
}
|
|
2995
|
+
const action = parseAction(body);
|
|
2996
|
+
if (action === null) return jsonResponse({ snapshot: await control.snapshot(sessionId) });
|
|
2997
|
+
if (action.kind === "prune") return jsonResponse({
|
|
2998
|
+
outcome: await control.pruneOnce(action.sessionId),
|
|
2999
|
+
snapshot: await control.snapshot(action.sessionId)
|
|
3000
|
+
});
|
|
3001
|
+
return jsonResponse({ snapshot: await control.setCap(action.sessionId, action.cap) });
|
|
3002
|
+
}
|
|
3003
|
+
function registerContextRoute(ctx, control) {
|
|
3004
|
+
const connection = ctx.get("connection");
|
|
3005
|
+
const register = connection?.fetch?.register;
|
|
3006
|
+
if (typeof register !== "function") return () => {};
|
|
3007
|
+
const dispose = register.call(connection?.fetch, {
|
|
3008
|
+
path: CONTEXT_PATH,
|
|
3009
|
+
methods: ["GET", "POST"],
|
|
3010
|
+
requestBody: "buffered",
|
|
3011
|
+
fetch: (request) => handleContextRequest(control, request)
|
|
3012
|
+
});
|
|
3013
|
+
return () => {
|
|
3014
|
+
Promise.resolve().then(() => dispose()).catch(() => void 0);
|
|
3015
|
+
};
|
|
3016
|
+
}
|
|
3017
|
+
function installContextHooks(ctx, control, options) {
|
|
3018
|
+
const disposers = [];
|
|
3019
|
+
const admissions = new Map();
|
|
3020
|
+
const active = new Set();
|
|
3021
|
+
const lifetime = new AbortController();
|
|
3022
|
+
async function maintain(agent, retainTokens, signal) {
|
|
3023
|
+
const session = agent.session;
|
|
3024
|
+
const before = session.surface?.contentGeneration;
|
|
3025
|
+
serviceFor(ctx, agent, "toolResultPruner")?.pruneSession(session);
|
|
3026
|
+
if (session.surface?.contentGeneration === before) {
|
|
3027
|
+
const range = selectRange(agent, serviceFor(ctx, agent, "tokenMeter")?.measure(session), retainTokens);
|
|
3028
|
+
const compaction = serviceFor(ctx, agent, "compaction");
|
|
3029
|
+
if (range === null || compaction?.compactRegion === void 0) throw new Error("本会话压缩阈值已达到,但没有可安全压缩的历史;请提高阈值或恢复默认");
|
|
3030
|
+
await compaction.compactRegion(range.start, range.end, agent, signal);
|
|
3031
|
+
}
|
|
3032
|
+
if (before === void 0 || session.surface?.contentGeneration === before) throw new Error("上下文整理没有产生可重建的 surface 进展");
|
|
3033
|
+
const sessions = serviceFor(ctx, agent, "sessions");
|
|
3034
|
+
if (sessions?.flush === void 0) throw new Error("上下文整理缺少持久化服务,不能派发旧请求");
|
|
3035
|
+
await sessions.flush(session);
|
|
3036
|
+
signal.throwIfAborted();
|
|
3037
|
+
}
|
|
3038
|
+
async function* admit(request, next) {
|
|
3039
|
+
const agent = ctx.get("agents")?.get?.(request.sessionId ?? "");
|
|
3040
|
+
const state = agent === void 0 ? void 0 : admissions.get(agent);
|
|
3041
|
+
const messages = agent?.session.deriveMessages?.();
|
|
3042
|
+
if (agent === void 0 || state === void 0 || request.purpose !== void 0 || state.signal !== request.signal || !Object.isFrozen(request) || messages === void 0 || messages.length !== request.messages.length || messages.some((message, index) => message !== request.messages[index]) || !readContextManagerEnabled(options.config())) {
|
|
3043
|
+
yield* next();
|
|
3044
|
+
return;
|
|
3045
|
+
}
|
|
3046
|
+
const cap = readCap(options.config(), agent.id);
|
|
3047
|
+
if (cap === null) {
|
|
3048
|
+
yield* next();
|
|
3049
|
+
return;
|
|
3050
|
+
}
|
|
3051
|
+
const signal = AbortSignal.any([state.signal, lifetime.signal]);
|
|
3052
|
+
signal.throwIfAborted();
|
|
3053
|
+
const input = await nativePolicyOf(ctx, agent, signal);
|
|
3054
|
+
const policy = input === null ? null : resolvePolicy(input, cap);
|
|
3055
|
+
if (policy === null || input === null) {
|
|
3056
|
+
yield* next();
|
|
3057
|
+
return;
|
|
3058
|
+
}
|
|
3059
|
+
const used = (serviceFor(ctx, agent, "tokenMeter")?.measure(agent.session))?.totalTokens;
|
|
3060
|
+
if (typeof used !== "number" || !Number.isFinite(used)) throw new Error("无法计量本次完整请求,不能应用本会话压缩阈值");
|
|
3061
|
+
if (used < policy.effectiveThreshold) {
|
|
3062
|
+
yield* next();
|
|
3063
|
+
return;
|
|
3064
|
+
}
|
|
3065
|
+
if (state.attempts >= 3) throw new Error("本会话上下文整理已达到重建次数上限,请提高阈值或恢复默认");
|
|
3066
|
+
const work = maintain(agent, input.retainTokens, signal);
|
|
3067
|
+
active.add(work);
|
|
3068
|
+
try {
|
|
3069
|
+
await work;
|
|
3070
|
+
} finally {
|
|
3071
|
+
active.delete(work);
|
|
3072
|
+
}
|
|
3073
|
+
signal.throwIfAborted();
|
|
3074
|
+
state.attempts += 1;
|
|
3075
|
+
const failure = {
|
|
3076
|
+
code: `DESKTOP_ENHANCE_REBUILD_REQUIRED:${randomUUID()}`,
|
|
3077
|
+
message: "本地上下文整理已改变 surface;本次请求未派发,需从真实日志重新构建"
|
|
3078
|
+
};
|
|
3079
|
+
state.ticket = failure;
|
|
3080
|
+
yield {
|
|
3081
|
+
type: "finish",
|
|
3082
|
+
reason: {
|
|
3083
|
+
kind: "error",
|
|
3084
|
+
failure
|
|
3085
|
+
}
|
|
3086
|
+
};
|
|
3087
|
+
}
|
|
3088
|
+
function selectRange(agent, measurement, retainTokens) {
|
|
3089
|
+
const nodes = agent.session.surface?.nodes;
|
|
3090
|
+
const priced = measurement?.nodes;
|
|
3091
|
+
const events = agent.session.snapshotEvents?.();
|
|
3092
|
+
if (nodes === void 0 || nodes.length < 2 || priced === void 0 || events === void 0) return null;
|
|
3093
|
+
if (priced.length !== nodes.length || nodes.some((seq, index) => seq !== priced[index]?.seq)) throw new Error("上下文计量与当前 surface 不一致");
|
|
3094
|
+
const bySeq = new Map(events.map((event) => [event.seq, event]));
|
|
3095
|
+
const first = bySeq.get(nodes[0])?.type === "system/message" ? 1 : 0;
|
|
3096
|
+
const balanced = [true];
|
|
3097
|
+
let openCalls = 0;
|
|
3098
|
+
for (const seq of nodes) {
|
|
3099
|
+
const event = bySeq.get(seq);
|
|
3100
|
+
if (event === void 0) throw new Error(`surface seq ${seq} 缺少对应事件`);
|
|
3101
|
+
if (event.type === "assistant/message") openCalls += event.data?.message?.content?.filter((block) => block.type === "tool-call").length ?? 0;
|
|
3102
|
+
else if (event.type === "tool/result") openCalls -= 1;
|
|
3103
|
+
if (openCalls < 0) throw new Error("工具结果缺少对应调用,不能压缩不完整的 surface");
|
|
3104
|
+
balanced.push(openCalls === 0);
|
|
3105
|
+
}
|
|
3106
|
+
let retained = 0;
|
|
3107
|
+
let keepFrom = nodes.length;
|
|
3108
|
+
for (let index = priced.length - 1; index >= 0; index -= 1) {
|
|
3109
|
+
retained += priced[index].tokens;
|
|
3110
|
+
keepFrom = index;
|
|
3111
|
+
if (retained >= retainTokens) break;
|
|
3112
|
+
}
|
|
3113
|
+
while (keepFrom > first && !balanced[keepFrom]) keepFrom -= 1;
|
|
3114
|
+
if (keepFrom <= first) return null;
|
|
3115
|
+
return {
|
|
3116
|
+
start: nodes[first],
|
|
3117
|
+
end: nodes[keepFrom - 1]
|
|
3118
|
+
};
|
|
3119
|
+
}
|
|
3120
|
+
const on = ctx.on;
|
|
3121
|
+
if (typeof on === "function") {
|
|
3122
|
+
disposers.push(on.call(ctx, "agent/request", async (payload, next) => {
|
|
3123
|
+
const result = await next();
|
|
3124
|
+
const previous = admissions.get(payload.agent);
|
|
3125
|
+
admissions.set(payload.agent, previous?.turn === payload.turn && previous.step === payload.step && previous.signal === payload.signal ? {
|
|
3126
|
+
...previous,
|
|
3127
|
+
ticket: void 0
|
|
3128
|
+
} : {
|
|
3129
|
+
...payload,
|
|
3130
|
+
attempts: 0
|
|
3131
|
+
});
|
|
3132
|
+
return result;
|
|
3133
|
+
}, { prepend: true }));
|
|
3134
|
+
disposers.push(on.call(ctx, "llm/stream", admit, { prepend: true }));
|
|
3135
|
+
disposers.push(on.call(ctx, "agent/request-error", async (payload, next) => {
|
|
3136
|
+
const state = admissions.get(payload.agent);
|
|
3137
|
+
const ticket = state?.ticket;
|
|
3138
|
+
if (state === void 0 || ticket === void 0 || ticket.code !== payload.failure.code || ticket.message !== payload.failure.message) return next();
|
|
3139
|
+
state.ticket = void 0;
|
|
3140
|
+
if (payload.signal !== state.signal || payload.signal.aborted || lifetime.signal.aborted || state.turn !== payload.turn || state.step !== payload.step) return void 0;
|
|
3141
|
+
return { kind: "retry" };
|
|
3142
|
+
}, { prepend: true }));
|
|
3143
|
+
disposers.push(on.call(ctx, "agent/pre-step", async (payload, next) => {
|
|
3144
|
+
const agent = payload.agent;
|
|
3145
|
+
if (agent !== void 0) try {
|
|
3146
|
+
await control.consumePending(agent.id);
|
|
3147
|
+
} catch {}
|
|
3148
|
+
return next();
|
|
3149
|
+
}));
|
|
3150
|
+
disposers.push(on.call(ctx, "agent/turn-stopping", async (payload) => {
|
|
3151
|
+
const agent = payload.agent;
|
|
3152
|
+
if (agent !== void 0) await control.consumePending(agent.id);
|
|
3153
|
+
}));
|
|
3154
|
+
disposers.push(on.call(ctx, "agent/disposed", (payload) => {
|
|
3155
|
+
if (payload.agent !== void 0) {
|
|
3156
|
+
admissions.delete(payload.agent);
|
|
3157
|
+
control.forgetAgent(payload.agent);
|
|
3158
|
+
}
|
|
3159
|
+
}));
|
|
3160
|
+
}
|
|
3161
|
+
return async () => {
|
|
3162
|
+
lifetime.abort(new Error("上下文管理已卸载"));
|
|
3163
|
+
admissions.clear();
|
|
3164
|
+
for (const dispose of disposers) try {
|
|
3165
|
+
dispose();
|
|
3166
|
+
} catch {}
|
|
3167
|
+
await Promise.allSettled([...active, control.dispose()]);
|
|
3168
|
+
};
|
|
3169
|
+
}
|
|
3170
|
+
//#endregion
|
|
3171
|
+
//#region src/shared/skill-recovery.ts
|
|
3172
|
+
function decideRecovery(input) {
|
|
3173
|
+
const compaction = input.latestCompaction;
|
|
3174
|
+
if (compaction === null) return {
|
|
3175
|
+
names: [],
|
|
3176
|
+
compactionSeq: null
|
|
3177
|
+
};
|
|
3178
|
+
const latestByName = new Map();
|
|
3179
|
+
for (const load of input.loads) {
|
|
3180
|
+
const previous = latestByName.get(load.name);
|
|
3181
|
+
if (previous === void 0 || load.seq >= previous.seq) latestByName.set(load.name, load);
|
|
3182
|
+
}
|
|
3183
|
+
const retainedBodies = new Set();
|
|
3184
|
+
for (const record of input.recoveries) if (record.onSurface) retainedBodies.add(record.name);
|
|
3185
|
+
const candidates = [];
|
|
3186
|
+
for (const [name, load] of latestByName) {
|
|
3187
|
+
if (load.onSurface) continue;
|
|
3188
|
+
if (retainedBodies.has(name)) continue;
|
|
3189
|
+
if (!input.available(name)) continue;
|
|
3190
|
+
candidates.push({
|
|
3191
|
+
name,
|
|
3192
|
+
seq: load.seq
|
|
3193
|
+
});
|
|
3194
|
+
}
|
|
3195
|
+
candidates.sort((left, right) => left.seq - right.seq || (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
|
|
3196
|
+
return {
|
|
3197
|
+
names: candidates.map((candidate) => candidate.name),
|
|
3198
|
+
compactionSeq: compaction.seq
|
|
3199
|
+
};
|
|
3200
|
+
}
|
|
3201
|
+
function renderSkillContentForRecovery(skill) {
|
|
3202
|
+
const base = skill.resourceBase;
|
|
3203
|
+
let resourceHint;
|
|
3204
|
+
if (base === void 0) resourceHint = [`Resources for this skill are managed by provider "${escapeText(skill.provider)}".`, "Load referenced resources only as needed."];
|
|
3205
|
+
else if (base.kind === "directory" && typeof base.path === "string") resourceHint = [`Base directory for this skill: ${escapeText(base.path)}`, "Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed."];
|
|
3206
|
+
else if (base.kind === "url" && typeof base.url === "string") resourceHint = [`Base URL for this skill: ${escapeText(base.url)}`, "Resolve relative URLs mentioned by this skill against the base URL before using them. Load referenced resources only as needed."];
|
|
3207
|
+
else if (base.kind === "opaque" && typeof base.description === "string") resourceHint = [`Resources for this skill: ${escapeText(base.description)}`, "Load referenced resources only as needed."];
|
|
3208
|
+
else resourceHint = [`Resources for this skill are managed by provider "${escapeText(skill.provider)}".`, "Load referenced resources only as needed."];
|
|
3209
|
+
return [
|
|
3210
|
+
`<skill_content name="${escapeAttr(skill.name)}">`,
|
|
3211
|
+
"<skill_resources>",
|
|
3212
|
+
...resourceHint,
|
|
3213
|
+
"</skill_resources>",
|
|
3214
|
+
"",
|
|
3215
|
+
"<skill_instructions>",
|
|
3216
|
+
skill.content,
|
|
3217
|
+
"</skill_instructions>",
|
|
3218
|
+
"</skill_content>"
|
|
3219
|
+
].join("\n");
|
|
3220
|
+
}
|
|
3221
|
+
function escapeAttr(value) {
|
|
3222
|
+
return value.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
3223
|
+
}
|
|
3224
|
+
function escapeText(value) {
|
|
3225
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
3226
|
+
}
|
|
3227
|
+
function buildRecoveryText(skill) {
|
|
3228
|
+
return renderSkillContentForRecovery(skill);
|
|
3229
|
+
}
|
|
3230
|
+
//#endregion
|
|
3231
|
+
//#region src/skill-recovery/host.ts
|
|
3232
|
+
const RECOVERY_CONTEXT = "desktop-enhance-skill-recovery";
|
|
3233
|
+
function readUserSource(event) {
|
|
3234
|
+
if (event.type !== "user/message") return void 0;
|
|
3235
|
+
return event.data?.source;
|
|
3236
|
+
}
|
|
3237
|
+
function projectRecoveryState(events, surfaceNodes) {
|
|
3238
|
+
const loads = [];
|
|
3239
|
+
const recoveries = [];
|
|
3240
|
+
let latestCompaction = null;
|
|
3241
|
+
const live = new Set(surfaceNodes);
|
|
3242
|
+
let latestRuntimeSeq;
|
|
3243
|
+
for (const event of events) if (typeof event.seq === "number" && live.has(event.seq) && readUserSource(event)?.kind === "runtime-context") latestRuntimeSeq = event.seq;
|
|
3244
|
+
for (const event of events) {
|
|
3245
|
+
if (event.type === "compaction/summary") {
|
|
3246
|
+
const data = event.data;
|
|
3247
|
+
const shadowed = Array.isArray(data?.shadowedSeqs) ? data.shadowedSeqs : [];
|
|
3248
|
+
const seq = event.seq;
|
|
3249
|
+
if (shadowed.length > 0 && typeof seq === "number") latestCompaction = { seq };
|
|
3250
|
+
continue;
|
|
3251
|
+
}
|
|
3252
|
+
if (event.type !== "user/message" && event.type !== "tool/result") continue;
|
|
3253
|
+
const seq = event.seq;
|
|
3254
|
+
if (typeof seq !== "number") continue;
|
|
3255
|
+
const source = readUserSource(event);
|
|
3256
|
+
if (source?.kind === "runtime-context") {
|
|
3257
|
+
for (const body of readRecoveryBodies(source.sections)) recoveries.push({
|
|
3258
|
+
...body,
|
|
3259
|
+
source: {
|
|
3260
|
+
kind: "recovery",
|
|
3261
|
+
name: body.name
|
|
3262
|
+
},
|
|
3263
|
+
seq,
|
|
3264
|
+
onSurface: seq === latestRuntimeSeq
|
|
3265
|
+
});
|
|
3266
|
+
continue;
|
|
3267
|
+
}
|
|
3268
|
+
const parsed = readSkillLoad(event);
|
|
3269
|
+
if (parsed !== null) loads.push({
|
|
3270
|
+
name: parsed.name,
|
|
3271
|
+
source: {
|
|
3272
|
+
kind: parsed.kind,
|
|
3273
|
+
name: parsed.name
|
|
3274
|
+
},
|
|
3275
|
+
seq,
|
|
3276
|
+
onSurface: live.has(seq)
|
|
3277
|
+
});
|
|
3278
|
+
}
|
|
3279
|
+
return {
|
|
3280
|
+
loads,
|
|
3281
|
+
recoveries,
|
|
3282
|
+
latestCompaction
|
|
3283
|
+
};
|
|
3284
|
+
}
|
|
3285
|
+
function readRecoveryBodies(sections) {
|
|
3286
|
+
if (!Array.isArray(sections)) return [];
|
|
3287
|
+
const bodies = [];
|
|
3288
|
+
for (const section of sections) {
|
|
3289
|
+
if (section?.name !== RECOVERY_CONTEXT || typeof section.text !== "string") continue;
|
|
3290
|
+
const blocks = section.text.matchAll(/(?:^|\n\n)(<skill_content name="([^"]+)">[\s\S]*?<\/skill_content>)(?=\n\n<skill_content name="|$)/g);
|
|
3291
|
+
for (const match of blocks) if (match[1] !== void 0 && match[2] !== void 0) bodies.push({
|
|
3292
|
+
name: match[2],
|
|
3293
|
+
text: match[1]
|
|
3294
|
+
});
|
|
3295
|
+
}
|
|
3296
|
+
return bodies;
|
|
3297
|
+
}
|
|
3298
|
+
function readSkillLoad(event) {
|
|
3299
|
+
const data = event.data;
|
|
3300
|
+
const source = readUserSource(event);
|
|
3301
|
+
if (source?.kind === "skill-invocation" && typeof source.name === "string") return {
|
|
3302
|
+
kind: "user",
|
|
3303
|
+
name: source.name
|
|
3304
|
+
};
|
|
3305
|
+
const blocks = event.type === "tool/result" ? data?.message?.content : data?.content;
|
|
3306
|
+
if (!Array.isArray(blocks)) return null;
|
|
3307
|
+
let text = "";
|
|
3308
|
+
for (const block of blocks) if (block?.type === "text" && typeof block.text === "string") text += block.text;
|
|
3309
|
+
if (text === "") return null;
|
|
3310
|
+
if (event.type === "tool/result" && text.trimStart().startsWith("<skill_content")) {
|
|
3311
|
+
const match = /<skill_content name="([^"]+)"/.exec(text);
|
|
3312
|
+
if (match?.[1] === void 0) return null;
|
|
3313
|
+
return {
|
|
3314
|
+
kind: "tool",
|
|
3315
|
+
name: match[1]
|
|
3316
|
+
};
|
|
3317
|
+
}
|
|
3318
|
+
return null;
|
|
3319
|
+
}
|
|
3320
|
+
function readSkillRecoveryEnabled(config) {
|
|
3321
|
+
if (config === null || typeof config !== "object") return true;
|
|
3322
|
+
const raw = config.skillRecovery;
|
|
3323
|
+
if (typeof raw === "boolean") return raw;
|
|
3324
|
+
if (raw !== null && typeof raw === "object" && typeof raw.get === "function") try {
|
|
3325
|
+
const value = raw.get();
|
|
3326
|
+
return typeof value === "boolean" ? value : true;
|
|
3327
|
+
} catch {
|
|
3328
|
+
return true;
|
|
3329
|
+
}
|
|
3330
|
+
return true;
|
|
3331
|
+
}
|
|
3332
|
+
function installSkillRecovery(ctx, options) {
|
|
3333
|
+
const disposers = [];
|
|
3334
|
+
const pendingByAgent = new WeakMap();
|
|
3335
|
+
const on = ctx.on;
|
|
3336
|
+
if (typeof on !== "function") return () => {};
|
|
3337
|
+
async function prepare(agent) {
|
|
3338
|
+
pendingByAgent.delete(agent);
|
|
3339
|
+
const projected = projectRecoveryState(typeof agent.session.snapshotEvents === "function" ? agent.session.snapshotEvents() : [], agent.session.surface?.nodes ?? []);
|
|
3340
|
+
const available = options.available === void 0 ? () => true : (name) => options.available?.(name, agent.id) === true;
|
|
3341
|
+
const decision = decideRecovery({
|
|
3342
|
+
loads: projected.loads,
|
|
3343
|
+
recoveries: projected.recoveries,
|
|
3344
|
+
latestCompaction: projected.latestCompaction,
|
|
3345
|
+
available
|
|
3346
|
+
});
|
|
3347
|
+
const sections = new Map();
|
|
3348
|
+
for (const body of projected.recoveries) if (body.onSurface && !projected.loads.some((load) => load.name === body.name && load.onSurface)) sections.set(body.name, body);
|
|
3349
|
+
pendingByAgent.set(agent, [...sections.values()]);
|
|
3350
|
+
if (decision.names.length === 0 || decision.compactionSeq === null) return;
|
|
3351
|
+
const skills = ctx.get("skills");
|
|
3352
|
+
if (skills?.get === void 0) return;
|
|
3353
|
+
const workingDir = ctx.get("workingDirectory");
|
|
3354
|
+
let cwd;
|
|
3355
|
+
try {
|
|
3356
|
+
const resolved = await workingDir?.ensure?.(agent);
|
|
3357
|
+
if (typeof resolved === "string" && resolved.trim() !== "") cwd = resolved.trim();
|
|
3358
|
+
} catch {}
|
|
3359
|
+
const lookup = {
|
|
3360
|
+
scope: agent,
|
|
3361
|
+
...cwd === void 0 ? {} : { cwd }
|
|
3362
|
+
};
|
|
3363
|
+
for (const name of decision.names) try {
|
|
3364
|
+
const skill = await skills.get(name, lookup);
|
|
3365
|
+
if (skill === void 0 || typeof skill.content !== "string" || skill.content === "") continue;
|
|
3366
|
+
sections.set(name, {
|
|
3367
|
+
name,
|
|
3368
|
+
text: buildRecoveryText({
|
|
3369
|
+
name: skill.name,
|
|
3370
|
+
provider: typeof skill.provider === "string" ? skill.provider : "",
|
|
3371
|
+
content: skill.content,
|
|
3372
|
+
...skill.resourceBase === void 0 ? {} : { resourceBase: skill.resourceBase }
|
|
3373
|
+
})
|
|
3374
|
+
});
|
|
3375
|
+
} catch {}
|
|
3376
|
+
pendingByAgent.set(agent, [...sections.values()]);
|
|
3377
|
+
}
|
|
3378
|
+
disposers.push(on.call(ctx, "agent/request", async (payload, next) => {
|
|
3379
|
+
if (options.enabled()) {
|
|
3380
|
+
const agent = payload.agent;
|
|
3381
|
+
if (agent !== void 0) try {
|
|
3382
|
+
await prepare(agent);
|
|
3383
|
+
} catch {}
|
|
3384
|
+
}
|
|
3385
|
+
return next();
|
|
3386
|
+
}));
|
|
3387
|
+
const systemPrompt = ctx.get("systemPrompt");
|
|
3388
|
+
const register = systemPrompt?.context;
|
|
3389
|
+
if (typeof register === "function") try {
|
|
3390
|
+
disposers.push(register.call(systemPrompt, {
|
|
3391
|
+
name: RECOVERY_CONTEXT,
|
|
3392
|
+
order: 900,
|
|
3393
|
+
required: false,
|
|
3394
|
+
interpolate: false,
|
|
3395
|
+
text: (context) => {
|
|
3396
|
+
if (!options.enabled()) return "";
|
|
3397
|
+
const agent = context?.agent;
|
|
3398
|
+
if (agent === null || agent === void 0 || typeof agent !== "object") return "";
|
|
3399
|
+
const pending = pendingByAgent.get(agent);
|
|
3400
|
+
if (pending === void 0) return "";
|
|
3401
|
+
return pending.filter((body) => options.available === void 0 || options.available(body.name, agent.id) === true).map((body) => body.text).join("\n\n");
|
|
3402
|
+
}
|
|
3403
|
+
}));
|
|
3404
|
+
} catch {}
|
|
3405
|
+
return () => {
|
|
3406
|
+
for (const dispose of disposers) try {
|
|
3407
|
+
dispose();
|
|
3408
|
+
} catch {}
|
|
3409
|
+
};
|
|
3410
|
+
}
|
|
3411
|
+
//#endregion
|
|
2522
3412
|
//#region src/index.ts
|
|
2523
3413
|
const Config = Schema.object({
|
|
2524
3414
|
findBar: Schema.boolean().default(true).volatile(),
|
|
@@ -2539,7 +3429,10 @@ const Config = Schema.object({
|
|
|
2539
3429
|
disabledTools: Schema.string().default("").volatile(),
|
|
2540
3430
|
sessionToolOverrides: Schema.string().default("").volatile(),
|
|
2541
3431
|
disabledSkills: Schema.string().default("").volatile(),
|
|
2542
|
-
sessionSkillOverrides: Schema.string().default("").volatile()
|
|
3432
|
+
sessionSkillOverrides: Schema.string().default("").volatile(),
|
|
3433
|
+
contextManager: Schema.boolean().default(true).volatile(),
|
|
3434
|
+
skillRecovery: Schema.boolean().default(true).volatile(),
|
|
3435
|
+
sessionCompactionCaps: Schema.string().default("").volatile()
|
|
2543
3436
|
});
|
|
2544
3437
|
function apply(ctx, config) {
|
|
2545
3438
|
ctx.inject(["sessionProjections"], (serviceCtx) => {
|
|
@@ -2576,10 +3469,44 @@ function apply(ctx, config) {
|
|
|
2576
3469
|
} catch (error) {
|
|
2577
3470
|
serviceCtx.logger?.warn(`desktop-enhance: skills policy not installed: ${String(error)}`);
|
|
2578
3471
|
}
|
|
3472
|
+
try {
|
|
3473
|
+
const control = createContextControl(serviceCtx, { config: () => config });
|
|
3474
|
+
serviceCtx.effect(() => registerContextRoute(serviceCtx, control), "desktop-enhance: context route");
|
|
3475
|
+
serviceCtx.effect(() => installContextHooks(serviceCtx, control, { config: () => config }), "desktop-enhance: context hooks");
|
|
3476
|
+
} catch (error) {
|
|
3477
|
+
serviceCtx.logger?.warn(`desktop-enhance: context manager not installed: ${String(error)}`);
|
|
3478
|
+
}
|
|
3479
|
+
try {
|
|
3480
|
+
serviceCtx.effect(() => installSkillRecovery(serviceCtx, {
|
|
3481
|
+
enabled: () => readSkillRecoveryEnabled(config),
|
|
3482
|
+
available: (name, sessionId) => !readSkillsConfig(config, sessionId).disabled.has(name)
|
|
3483
|
+
}), "desktop-enhance: skill recovery");
|
|
3484
|
+
} catch (error) {
|
|
3485
|
+
serviceCtx.logger?.warn(`desktop-enhance: skill recovery not installed: ${String(error)}`);
|
|
3486
|
+
}
|
|
2579
3487
|
});
|
|
2580
3488
|
}
|
|
2581
3489
|
const __test = {
|
|
2582
3490
|
sessionModelProjection,
|
|
3491
|
+
CONTEXT_PATH,
|
|
3492
|
+
createContextControl,
|
|
3493
|
+
handleContextRequest,
|
|
3494
|
+
installContextHooks,
|
|
3495
|
+
readCap,
|
|
3496
|
+
readContextManagerEnabled,
|
|
3497
|
+
registerContextRoute,
|
|
3498
|
+
resolveTargetAgent,
|
|
3499
|
+
capOf,
|
|
3500
|
+
decodeCaps,
|
|
3501
|
+
encodeCaps,
|
|
3502
|
+
resolvePolicy,
|
|
3503
|
+
withCap,
|
|
3504
|
+
buildRecoveryText,
|
|
3505
|
+
decideRecovery,
|
|
3506
|
+
renderSkillContentForRecovery,
|
|
3507
|
+
installSkillRecovery,
|
|
3508
|
+
projectRecoveryState,
|
|
3509
|
+
readSkillRecoveryEnabled,
|
|
2583
3510
|
SUGGEST_PATH,
|
|
2584
3511
|
SUGGEST_MODELS_PATH,
|
|
2585
3512
|
SUGGEST_EFFORTS_PATH,
|