dsh-desktop-enhance 0.6.13 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,819 @@ 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
+ if (input.latestCompaction === null) return { names: [] };
3174
+ const latestByName = new Map();
3175
+ for (const load of input.loads) {
3176
+ const previous = latestByName.get(load.name);
3177
+ if (previous === void 0 || load.seq >= previous.seq) latestByName.set(load.name, load);
3178
+ }
3179
+ return { names: [...latestByName.values()].filter((load) => !load.onSurface && input.available(load.name)).sort((left, right) => left.seq - right.seq || left.name.localeCompare(right.name)).map((load) => load.name) };
3180
+ }
3181
+ function renderSkillContentForRecovery(skill) {
3182
+ const base = skill.resourceBase;
3183
+ let resourceHint;
3184
+ if (base === void 0) resourceHint = [`Resources for this skill are managed by provider "${escapeText(skill.provider)}".`, "Load referenced resources only as needed."];
3185
+ 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."];
3186
+ 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."];
3187
+ else if (base.kind === "opaque" && typeof base.description === "string") resourceHint = [`Resources for this skill: ${escapeText(base.description)}`, "Load referenced resources only as needed."];
3188
+ else resourceHint = [`Resources for this skill are managed by provider "${escapeText(skill.provider)}".`, "Load referenced resources only as needed."];
3189
+ return [
3190
+ `<skill_content name="${escapeAttr(skill.name)}">`,
3191
+ "<skill_resources>",
3192
+ ...resourceHint,
3193
+ "</skill_resources>",
3194
+ "",
3195
+ "<skill_instructions>",
3196
+ skill.content,
3197
+ "</skill_instructions>",
3198
+ "</skill_content>"
3199
+ ].join("\n");
3200
+ }
3201
+ function escapeAttr(value) {
3202
+ return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3203
+ }
3204
+ function escapeText(value) {
3205
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3206
+ }
3207
+ //#endregion
3208
+ //#region src/skill-recovery/host.ts
3209
+ function projectRecoveryState(events, surfaceNodes) {
3210
+ const loads = [];
3211
+ let latestCompaction = null;
3212
+ const live = new Set(surfaceNodes);
3213
+ for (const event of events) {
3214
+ if (event.type === "compaction/summary") {
3215
+ const data = event.data;
3216
+ if (Array.isArray(data?.shadowedSeqs) && data.shadowedSeqs.length > 0 && typeof event.seq === "number") latestCompaction = { seq: event.seq };
3217
+ continue;
3218
+ }
3219
+ const load = readSkillLoad(event);
3220
+ if (load !== null && typeof event.seq === "number") loads.push({
3221
+ ...load,
3222
+ seq: event.seq,
3223
+ onSurface: live.has(event.seq)
3224
+ });
3225
+ }
3226
+ return {
3227
+ loads,
3228
+ latestCompaction
3229
+ };
3230
+ }
3231
+ function readSkillLoad(event) {
3232
+ const data = event.data;
3233
+ if (event.type === "user/message" && data?.source?.kind === "skill-invocation" && typeof data.source.name === "string") return { name: data.source.name };
3234
+ if (event.type !== "tool/result") return null;
3235
+ const blocks = data?.message?.content;
3236
+ if (!Array.isArray(blocks)) return null;
3237
+ const text = blocks.filter((block) => block.type === "text").map((block) => block.text ?? "").join("");
3238
+ const match = /^\s*<skill_content name="([^"]+)"/.exec(text);
3239
+ return match?.[1] === void 0 ? null : { name: match[1] };
3240
+ }
3241
+ function readSkillRecoveryEnabled(config) {
3242
+ if (config === null || typeof config !== "object") return true;
3243
+ const raw = config.skillRecovery;
3244
+ if (typeof raw === "boolean") return raw;
3245
+ if (raw !== null && typeof raw === "object" && typeof raw.get === "function") try {
3246
+ const value = raw.get();
3247
+ return typeof value === "boolean" ? value : true;
3248
+ } catch {
3249
+ return true;
3250
+ }
3251
+ return true;
3252
+ }
3253
+ function installSkillRecovery(ctx, options) {
3254
+ const on = ctx.on;
3255
+ if (typeof on !== "function") return () => {};
3256
+ const lifetime = new AbortController();
3257
+ const available = (name, agent) => options.available?.(name, agent.id) ?? true;
3258
+ async function recover(payload, pending = []) {
3259
+ if (!options.enabled() || lifetime.signal.aborted) return [];
3260
+ const { agent } = payload;
3261
+ const signal = AbortSignal.any([payload.signal, lifetime.signal]);
3262
+ signal.throwIfAborted();
3263
+ const projected = projectRecoveryState(agent.session.snapshotEvents(), agent.session.surface.nodes);
3264
+ const pendingNames = new Set(pending.filter((message) => message.source.kind === "skill-invocation").map((message) => message.source.name));
3265
+ const decision = decideRecovery({
3266
+ ...projected,
3267
+ available: (name) => !pendingNames.has(name) && available(name, agent)
3268
+ });
3269
+ if (decision.names.length === 0) return [];
3270
+ const skills = ctx.get("skills");
3271
+ if (skills === void 0) return [];
3272
+ const cwd = await ctx.get("workingDirectory")?.ensure(agent, signal);
3273
+ const messages = [];
3274
+ for (const name of decision.names) {
3275
+ signal.throwIfAborted();
3276
+ let skill;
3277
+ try {
3278
+ skill = await skills.get(name, {
3279
+ scope: agent,
3280
+ cwd,
3281
+ signal
3282
+ });
3283
+ } catch {
3284
+ signal.throwIfAborted();
3285
+ ctx.logger?.warn(`desktop-enhance: could not restore Skill ${name}; will retry at the next admission`);
3286
+ continue;
3287
+ }
3288
+ if (skill === void 0 || typeof skill.content !== "string" || skill.content === "") continue;
3289
+ messages.push({
3290
+ id: randomUUID(),
3291
+ role: "user",
3292
+ source: {
3293
+ kind: "skill-invocation",
3294
+ name,
3295
+ form: "instructions"
3296
+ },
3297
+ content: [{
3298
+ type: "text",
3299
+ text: renderSkillContentForRecovery({
3300
+ ...skill,
3301
+ provider: skill.provider ?? "",
3302
+ content: skill.content
3303
+ })
3304
+ }]
3305
+ });
3306
+ }
3307
+ signal.throwIfAborted();
3308
+ if (!options.enabled()) return [];
3309
+ return messages.filter((message) => available(message.source.name, agent));
3310
+ }
3311
+ const disposers = [on.call(ctx, "agent/pre-step", async (payload, next) => {
3312
+ const decision = await next();
3313
+ if (decision.kind === "reject" || payload.step === 1 && decision.messages.length === 0) return decision;
3314
+ const messages = await recover(payload, decision.messages);
3315
+ return messages.length === 0 ? decision : {
3316
+ ...decision,
3317
+ messages: [...decision.messages, ...messages]
3318
+ };
3319
+ }, { prepend: true }), on.call(ctx, "agent/request-error", async (payload, next) => {
3320
+ const decision = await next();
3321
+ if (decision?.kind !== "retry") return decision;
3322
+ const messages = await recover(payload);
3323
+ for (const message of messages) {
3324
+ payload.signal.throwIfAborted();
3325
+ lifetime.signal.throwIfAborted();
3326
+ if (!options.enabled() || !available(message.source.name, payload.agent)) continue;
3327
+ payload.agent.session.append("user/message", message, { surfaceOp: "append" });
3328
+ }
3329
+ return decision;
3330
+ }, { prepend: true })];
3331
+ return () => {
3332
+ lifetime.abort(new Error("Skill 恢复已卸载"));
3333
+ for (const dispose of disposers) dispose();
3334
+ };
3335
+ }
3336
+ //#endregion
2522
3337
  //#region src/index.ts
2523
3338
  const Config = Schema.object({
2524
3339
  findBar: Schema.boolean().default(true).volatile(),
@@ -2539,7 +3354,10 @@ const Config = Schema.object({
2539
3354
  disabledTools: Schema.string().default("").volatile(),
2540
3355
  sessionToolOverrides: Schema.string().default("").volatile(),
2541
3356
  disabledSkills: Schema.string().default("").volatile(),
2542
- sessionSkillOverrides: Schema.string().default("").volatile()
3357
+ sessionSkillOverrides: Schema.string().default("").volatile(),
3358
+ contextManager: Schema.boolean().default(true).volatile(),
3359
+ skillRecovery: Schema.boolean().default(true).volatile(),
3360
+ sessionCompactionCaps: Schema.string().default("").volatile()
2543
3361
  });
2544
3362
  function apply(ctx, config) {
2545
3363
  ctx.inject(["sessionProjections"], (serviceCtx) => {
@@ -2576,10 +3394,43 @@ function apply(ctx, config) {
2576
3394
  } catch (error) {
2577
3395
  serviceCtx.logger?.warn(`desktop-enhance: skills policy not installed: ${String(error)}`);
2578
3396
  }
3397
+ try {
3398
+ const control = createContextControl(serviceCtx, { config: () => config });
3399
+ serviceCtx.effect(() => registerContextRoute(serviceCtx, control), "desktop-enhance: context route");
3400
+ serviceCtx.effect(() => installContextHooks(serviceCtx, control, { config: () => config }), "desktop-enhance: context hooks");
3401
+ } catch (error) {
3402
+ serviceCtx.logger?.warn(`desktop-enhance: context manager not installed: ${String(error)}`);
3403
+ }
3404
+ try {
3405
+ serviceCtx.effect(() => installSkillRecovery(serviceCtx, {
3406
+ enabled: () => readSkillRecoveryEnabled(config),
3407
+ available: (name, sessionId) => !readSkillsConfig(config, sessionId).disabled.has(name)
3408
+ }), "desktop-enhance: skill recovery");
3409
+ } catch (error) {
3410
+ serviceCtx.logger?.warn(`desktop-enhance: skill recovery not installed: ${String(error)}`);
3411
+ }
2579
3412
  });
2580
3413
  }
2581
3414
  const __test = {
2582
3415
  sessionModelProjection,
3416
+ CONTEXT_PATH,
3417
+ createContextControl,
3418
+ handleContextRequest,
3419
+ installContextHooks,
3420
+ readCap,
3421
+ readContextManagerEnabled,
3422
+ registerContextRoute,
3423
+ resolveTargetAgent,
3424
+ capOf,
3425
+ decodeCaps,
3426
+ encodeCaps,
3427
+ resolvePolicy,
3428
+ withCap,
3429
+ decideRecovery,
3430
+ renderSkillContentForRecovery,
3431
+ installSkillRecovery,
3432
+ projectRecoveryState,
3433
+ readSkillRecoveryEnabled,
2583
3434
  SUGGEST_PATH,
2584
3435
  SUGGEST_MODELS_PATH,
2585
3436
  SUGGEST_EFFORTS_PATH,