@ashx-j/lunr 0.2.7 → 0.2.9
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/dist/builtin-extensions/ashxj-spinners.d.ts +7 -0
- package/dist/builtin-extensions/ashxj-spinners.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-spinners.js +40 -3
- package/dist/builtin-extensions/ashxj-spinners.js.map +1 -1
- package/dist/builtin-extensions/ashxj-tui.d.ts +4 -0
- package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-tui.js +44 -0
- package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
- package/dist/builtin-extensions/lunr-behavior.d.ts +2 -1
- package/dist/builtin-extensions/lunr-behavior.d.ts.map +1 -1
- package/dist/builtin-extensions/lunr-behavior.js +26 -14
- package/dist/builtin-extensions/lunr-behavior.js.map +1 -1
- package/dist/builtin-extensions/lunr-todos.d.ts +4 -7
- package/dist/builtin-extensions/lunr-todos.d.ts.map +1 -1
- package/dist/builtin-extensions/lunr-todos.js +18 -10
- package/dist/builtin-extensions/lunr-todos.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/agents/agent-management.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/agents/agent-management.js +3 -3
- package/dist/builtin-extensions/pi-subagents/src/agents/agent-management.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/control-notices.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/control-notices.js +2 -2
- package/dist/builtin-extensions/pi-subagents/src/extension/control-notices.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js +1 -7
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +2 -2
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +2 -2
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +3 -4
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +21 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +6 -18
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js +13 -5
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.d.ts +21 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.js +22 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.js.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +1 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js +2 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +10 -18
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +3 -0
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js +9 -11
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/render-search-error.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-web-access/render-search-error.js +1 -1
- package/dist/builtin-extensions/pi-web-access/render-search-error.js.map +1 -1
- package/dist/catalog/models.json +1 -1
- package/dist/catalog/providers/github-copilot.json +1 -1
- package/dist/catalog/providers/google-vertex.json +1 -1
- package/dist/catalog/providers/google.json +1 -1
- package/dist/catalog/providers/nvidia.json +1 -1
- package/dist/catalog/providers/opencode-go.json +1 -1
- package/dist/catalog/providers/opencode.json +1 -1
- package/dist/catalog/providers/openrouter.json +1 -1
- package/dist/catalog/providers/vercel-ai-gateway.json +1 -1
- package/dist/catalog/publication.json +3 -3
- package/dist/cli/update-cli.d.ts +16 -0
- package/dist/cli/update-cli.d.ts.map +1 -0
- package/dist/cli/update-cli.js +83 -0
- package/dist/cli/update-cli.js.map +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +6 -0
- package/dist/cli.js.map +1 -1
- package/dist/core/behavior-preset.d.ts +60 -0
- package/dist/core/behavior-preset.d.ts.map +1 -0
- package/dist/core/behavior-preset.js +257 -0
- package/dist/core/behavior-preset.js.map +1 -0
- package/dist/core/customize.d.ts +3 -0
- package/dist/core/customize.d.ts.map +1 -1
- package/dist/core/customize.js +9 -0
- package/dist/core/customize.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +12 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +70 -5
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/keybindings.d.ts +2 -2
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +1 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-tiers.d.ts +9 -0
- package/dist/core/model-tiers.d.ts.map +1 -1
- package/dist/core/model-tiers.js +16 -0
- package/dist/core/model-tiers.js.map +1 -1
- package/dist/core/rollback.d.ts +1 -1
- package/dist/core/rollback.d.ts.map +1 -1
- package/dist/core/rollback.js +1 -1
- package/dist/core/rollback.js.map +1 -1
- package/dist/core/settings-manager.d.ts +23 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +66 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +2 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +1 -3
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/update-check.d.ts +32 -0
- package/dist/core/update-check.d.ts.map +1 -0
- package/dist/core/update-check.js +112 -0
- package/dist/core/update-check.js.map +1 -0
- package/dist/core/usage-service.d.ts +24 -1
- package/dist/core/usage-service.d.ts.map +1 -1
- package/dist/core/usage-service.js +91 -14
- package/dist/core/usage-service.js.map +1 -1
- package/dist/gateway/agent-bridge.d.ts.map +1 -1
- package/dist/gateway/agent-bridge.js +5 -1
- package/dist/gateway/agent-bridge.js.map +1 -1
- package/dist/gateway/cron.d.ts.map +1 -1
- package/dist/gateway/cron.js +5 -1
- package/dist/gateway/cron.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +13 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +10 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +154 -68
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +13 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +157 -10
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-summary.d.ts +4 -4
- package/dist/modes/interactive/components/thinking-summary.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-summary.js +7 -5
- package/dist/modes/interactive/components/thinking-summary.js.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.js +5 -3
- package/dist/modes/interactive/components/thinking-tail.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +9 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +6 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +124 -43
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/keybindings.md +1 -1
- package/docs/providers.md +2 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Plan/subscription usage service. Per-provider adapters query provider quota
|
|
3
|
-
* endpoints (
|
|
3
|
+
* endpoints (60-second cache each) so /usage and the footer can show subscription windows
|
|
4
4
|
* alongside session/context totals.
|
|
5
5
|
*
|
|
6
6
|
* Deliberately absent adapters:
|
|
@@ -50,8 +50,33 @@ const ADAPTERS = {
|
|
|
50
50
|
zai: fetchZaiPlanUsage,
|
|
51
51
|
xai: fetchXaiPlanUsage,
|
|
52
52
|
};
|
|
53
|
-
export const PLAN_USAGE_CACHE_TTL_MS =
|
|
53
|
+
export const PLAN_USAGE_CACHE_TTL_MS = 60 * 1000;
|
|
54
|
+
export function isWeeklyPlanWindow(window) {
|
|
55
|
+
return /week/i.test(window.label);
|
|
56
|
+
}
|
|
57
|
+
export function isFiveHourPlanWindow(window) {
|
|
58
|
+
return /5h/i.test(window.label) || window.label === "5h";
|
|
59
|
+
}
|
|
60
|
+
/** Preferred window, falling back to the other, skipping Extra/on-demand. */
|
|
61
|
+
export function pickPlanWindow(usage, preferred) {
|
|
62
|
+
if (!usage?.windows.length)
|
|
63
|
+
return undefined;
|
|
64
|
+
const usable = usage.windows.filter((w) => !/extra/i.test(w.label));
|
|
65
|
+
const weekly = usable.find(isWeeklyPlanWindow);
|
|
66
|
+
const fiveH = usable.find(isFiveHourPlanWindow);
|
|
67
|
+
if (preferred === "5h")
|
|
68
|
+
return fiveH ?? weekly ?? usable[0] ?? usage.windows[0];
|
|
69
|
+
return weekly ?? fiveH ?? usable[0] ?? usage.windows[0];
|
|
70
|
+
}
|
|
71
|
+
export function footerPlanLabel(window) {
|
|
72
|
+
if (isFiveHourPlanWindow(window))
|
|
73
|
+
return "5h";
|
|
74
|
+
if (isWeeklyPlanWindow(window))
|
|
75
|
+
return "wk";
|
|
76
|
+
return window.label.length <= 4 ? window.label : window.label.slice(0, 4);
|
|
77
|
+
}
|
|
54
78
|
const cache = new Map();
|
|
79
|
+
const inflight = new Map();
|
|
55
80
|
/** Whether a plan-usage adapter exists for this provider. */
|
|
56
81
|
export function hasPlanUsageAdapter(providerId) {
|
|
57
82
|
return providerId in ADAPTERS;
|
|
@@ -69,24 +94,76 @@ export async function getPlanUsageResult(providerId, runtime) {
|
|
|
69
94
|
const cached = cache.get(providerId);
|
|
70
95
|
if (cached && cached.expiresAt > now)
|
|
71
96
|
return { usage: cached.value };
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
97
|
+
const pending = inflight.get(providerId);
|
|
98
|
+
if (pending)
|
|
99
|
+
return pending;
|
|
100
|
+
const task = (async () => {
|
|
101
|
+
try {
|
|
102
|
+
const value = await adapter(runtime);
|
|
103
|
+
cache.set(providerId, { expiresAt: Date.now() + PLAN_USAGE_CACHE_TTL_MS, value });
|
|
104
|
+
return { usage: value };
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
const authError = planUsageAuthError(error);
|
|
108
|
+
if (authError)
|
|
109
|
+
return { error: authError };
|
|
110
|
+
cache.set(providerId, { expiresAt: Date.now() + PLAN_USAGE_CACHE_TTL_MS, value: undefined });
|
|
111
|
+
return {};
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
inflight.delete(providerId);
|
|
115
|
+
}
|
|
116
|
+
})();
|
|
117
|
+
inflight.set(providerId, task);
|
|
118
|
+
return task;
|
|
119
|
+
}
|
|
120
|
+
/** Last fetched usage, including expired cache (footer can show stale while refetching). */
|
|
121
|
+
export function peekPlanUsage(providerId) {
|
|
122
|
+
return cache.get(providerId)?.value;
|
|
84
123
|
}
|
|
85
124
|
/** Clear the adapter cache (tests, /login changes). */
|
|
86
125
|
export function clearPlanUsageCache() {
|
|
87
126
|
cache.clear();
|
|
127
|
+
inflight.clear();
|
|
88
128
|
}
|
|
89
129
|
// ---------------------------------------------------------------------------
|
|
90
130
|
// Extension bridge
|
|
91
131
|
// ---------------------------------------------------------------------------
|
|
132
|
+
export const USAGE_SERVICE_BRIDGE_SYMBOL = Symbol.for("@lunr/usage-service");
|
|
133
|
+
let activeRuntime;
|
|
134
|
+
let activeUsageSettings;
|
|
135
|
+
let onUsageUpdate;
|
|
136
|
+
function preferredWindow() {
|
|
137
|
+
return activeUsageSettings?.getPlanUsageWindow() ?? "weekly";
|
|
138
|
+
}
|
|
139
|
+
const usageBridge = {
|
|
140
|
+
peek(providerId) {
|
|
141
|
+
return peekPlanUsage(providerId);
|
|
142
|
+
},
|
|
143
|
+
prefetch(providerId) {
|
|
144
|
+
if (!activeRuntime || !hasPlanUsageAdapter(providerId))
|
|
145
|
+
return;
|
|
146
|
+
void getPlanUsage(providerId, activeRuntime).then(() => onUsageUpdate?.());
|
|
147
|
+
},
|
|
148
|
+
setOnUpdate(fn) {
|
|
149
|
+
onUsageUpdate = fn;
|
|
150
|
+
},
|
|
151
|
+
getPreferredWindow() {
|
|
152
|
+
return preferredWindow();
|
|
153
|
+
},
|
|
154
|
+
pickForFooter(providerId) {
|
|
155
|
+
const window = pickPlanWindow(peekPlanUsage(providerId), preferredWindow());
|
|
156
|
+
if (!window)
|
|
157
|
+
return undefined;
|
|
158
|
+
return { label: footerPlanLabel(window), usedPercent: window.usedPercent };
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
export function registerUsageServiceBridge(runtime, settingsManager) {
|
|
162
|
+
activeRuntime = runtime;
|
|
163
|
+
activeUsageSettings = settingsManager;
|
|
164
|
+
globalThis[USAGE_SERVICE_BRIDGE_SYMBOL] = usageBridge;
|
|
165
|
+
}
|
|
166
|
+
export function getUsageServiceBridge() {
|
|
167
|
+
return globalThis[USAGE_SERVICE_BRIDGE_SYMBOL];
|
|
168
|
+
}
|
|
92
169
|
//# sourceMappingURL=usage-service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-service.js","sourceRoot":"","sources":["../../src/core/usage-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM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I,SAAS;YAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;QAC3C,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,GAAG,GAAG,uBAAuB,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;QACtF,OAAO,EAAE,CAAC;IACX,CAAC;AAAA,CACD;AAED,uDAAuD;AACvD,MAAM,UAAU,mBAAmB,GAAS;IAC3C,KAAK,CAAC,KAAK,EAAE,CAAC;AAAA,CACd;AAED,8EAA8E;AAC9E,mBAAmB;AACnB,8EAA8E","sourcesContent":["/**\n * Plan/subscription usage service. Per-provider adapters query provider quota\n * endpoints (5-minute cache each) so /usage can show subscription windows\n * alongside session/context totals.\n *\n * Deliberately absent adapters:\n * - anthropic: Anthropic policy prohibits subscription usage tracking in\n * third-party coding agents (2026-07-18 decision). OAuth Anthropic sessions\n * fall back to hiding the cost meter.\n * - ollama-cloud: no usage API exists.\n *\n * Adapter/network errors resolve to `undefined` (callers omit the plan UI).\n * Auth failures are different: they return `error` and are not cached as empty.\n */\n\nimport { ModelsError } from \"@ashx-j/lunr-ai\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport { fetchKimiPlanUsage } from \"./usage-adapters/kimi-coding.ts\";\nimport { fetchCodexPlanUsage } from \"./usage-adapters/openai-codex.ts\";\nimport { fetchXaiPlanUsage } from \"./usage-adapters/xai.ts\";\nimport { fetchZaiPlanUsage } from \"./usage-adapters/zai.ts\";\n\nexport interface PlanUsageWindow {\n\tlabel: string;\n\tusedPercent: number;\n\t/** Epoch ms when the window resets. */\n\tresetsAt?: number;\n}\n\nexport interface PlanUsage {\n\tprovider: string;\n\tplanLabel?: string;\n\twindows: PlanUsageWindow[];\n}\n\nexport interface PlanUsageResult {\n\tusage?: PlanUsage;\n\t/** Actionable auth failure. Not cached as an empty success. */\n\terror?: string;\n}\n\nconst XAI_RELOGIN = \"xAI login expired. Run /login xai.\";\n\nfunction errorChain(error: unknown): string {\n\tconst parts: string[] = [];\n\tlet current: unknown = error;\n\tconst seen = new Set<unknown>();\n\twhile (current && typeof current === \"object\" && !seen.has(current)) {\n\t\tseen.add(current);\n\t\tif (current instanceof Error) {\n\t\t\tparts.push(current.message);\n\t\t\tcurrent = current.cause;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn parts.join(\" \");\n}\n\n/** Classify adapter/getAuth failures that mean the SuperGrok session is dead. */\nexport function planUsageAuthError(error: unknown): string | undefined {\n\tconst chain = errorChain(error);\n\tif (/timed out|aborted|cancelled|ECONN|ENOTFOUND|network/i.test(chain)) return undefined;\n\t// 403 on billing is often entitlement, not a dead refresh token.\n\tif (/xai billing rejected the session \\(HTTP 401\\)/i.test(chain)) return XAI_RELOGIN;\n\tif (/invalid_grant|refresh token revoked/i.test(chain)) return XAI_RELOGIN;\n\treturn undefined;\n}\n\ntype UsageAdapter = (runtime: ModelRuntime) => Promise<PlanUsage | undefined>;\n\nconst ADAPTERS: Readonly<Record<string, UsageAdapter>> = {\n\t\"openai-codex\": fetchCodexPlanUsage,\n\t\"kimi-coding\": fetchKimiPlanUsage,\n\tzai: fetchZaiPlanUsage,\n\txai: fetchXaiPlanUsage,\n};\n\nexport const PLAN_USAGE_CACHE_TTL_MS = 5 * 60 * 1000;\n\nconst cache = new Map<string, { expiresAt: number; value: PlanUsage | undefined }>();\n\n/** Whether a plan-usage adapter exists for this provider. */\nexport function hasPlanUsageAdapter(providerId: string): boolean {\n\treturn providerId in ADAPTERS;\n}\n\n/** Plan usage for a provider, or undefined when unsupported/unavailable. Never throws. */\nexport async function getPlanUsage(providerId: string, runtime: ModelRuntime): Promise<PlanUsage | undefined> {\n\treturn (await getPlanUsageResult(providerId, runtime)).usage;\n}\n\n/** Like getPlanUsage, but surfaces SuperGrok/auth failures instead of hiding them. */\nexport async function getPlanUsageResult(providerId: string, runtime: ModelRuntime): Promise<PlanUsageResult> {\n\tconst adapter = ADAPTERS[providerId];\n\tif (!adapter) return {};\n\tconst now = Date.now();\n\tconst cached = cache.get(providerId);\n\tif (cached && cached.expiresAt > now) return { usage: cached.value };\n\ttry {\n\t\tconst value = await adapter(runtime);\n\t\tcache.set(providerId, { expiresAt: now + PLAN_USAGE_CACHE_TTL_MS, value });\n\t\treturn { usage: value };\n\t} catch (error) {\n\t\tconst authError = planUsageAuthError(error);\n\t\tif (authError) return { error: authError };\n\t\tcache.set(providerId, { expiresAt: now + PLAN_USAGE_CACHE_TTL_MS, value: undefined });\n\t\treturn {};\n\t}\n}\n\n/** Clear the adapter cache (tests, /login changes). */\nexport function clearPlanUsageCache(): void {\n\tcache.clear();\n}\n\n// ---------------------------------------------------------------------------\n// Extension bridge\n// ---------------------------------------------------------------------------\n"]}
|
|
1
|
+
{"version":3,"file":"usage-service.js","sourceRoot":"","sources":["../../src/core/usage-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAKH,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAqB5D,MAAM,WAAW,GAAG,oCAAoC,CAAC;AAEzD,SAAS,UAAU,CAAC,KAAc,EAAU;IAC3C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,OAAO,GAAY,KAAK,CAAC;IAC7B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAW,CAAC;IAChC,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QACrE,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAClB,IAAI,OAAO,YAAY,KAAK,EAAE,CAAC;YAC9B,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CA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AC;IAAA,CACzB;IACD,aAAa,CAAC,UAAkB,EAAiC;QAChE,MAAM,MAAM,GAAG,cAAc,CAAC,aAAa,CAAC,UAAU,CAAC,EAAE,eAAe,EAAE,CAAC,CAAC;QAC5E,IAAI,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC;QAC9B,OAAO,EAAE,KAAK,EAAE,eAAe,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,EAAE,CAAC;IAAA,CAC3E;CACD,CAAC;AAEF,MAAM,UAAU,0BAA0B,CAAC,OAAqB,EAAE,eAAgC,EAAQ;IACzG,aAAa,GAAG,OAAO,CAAC;IACxB,mBAAmB,GAAG,eAAe,CAAC;IACrC,UAAsC,CAAC,2BAA2B,CAAC,GAAG,WAAW,CAAC;AAAA,CACnF;AAED,MAAM,UAAU,qBAAqB,GAAmC;IACvE,OAAQ,UAAsC,CAAC,2BAA2B,CAAmC,CAAC;AAAA,CAC9G","sourcesContent":["/**\n * Plan/subscription usage service. Per-provider adapters query provider quota\n * endpoints (60-second cache each) so /usage and the footer can show subscription windows\n * alongside session/context totals.\n *\n * Deliberately absent adapters:\n * - anthropic: Anthropic policy prohibits subscription usage tracking in\n * third-party coding agents (2026-07-18 decision). OAuth Anthropic sessions\n * fall back to hiding the cost meter.\n * - ollama-cloud: no usage API exists.\n *\n * Adapter/network errors resolve to `undefined` (callers omit the plan UI).\n * Auth failures are different: they return `error` and are not cached as empty.\n */\n\nimport { ModelsError } from \"@ashx-j/lunr-ai\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { fetchKimiPlanUsage } from \"./usage-adapters/kimi-coding.ts\";\nimport { fetchCodexPlanUsage } from \"./usage-adapters/openai-codex.ts\";\nimport { fetchXaiPlanUsage } from \"./usage-adapters/xai.ts\";\nimport { fetchZaiPlanUsage } from \"./usage-adapters/zai.ts\";\n\nexport interface PlanUsageWindow {\n\tlabel: string;\n\tusedPercent: number;\n\t/** Epoch ms when the window resets. */\n\tresetsAt?: number;\n}\n\nexport interface PlanUsage {\n\tprovider: string;\n\tplanLabel?: string;\n\twindows: PlanUsageWindow[];\n}\n\nexport interface PlanUsageResult {\n\tusage?: PlanUsage;\n\t/** Actionable auth failure. Not cached as an empty success. */\n\terror?: string;\n}\n\nconst XAI_RELOGIN = \"xAI login expired. Run /login xai.\";\n\nfunction errorChain(error: unknown): string {\n\tconst parts: string[] = [];\n\tlet current: unknown = error;\n\tconst seen = new Set<unknown>();\n\twhile (current && typeof current === \"object\" && !seen.has(current)) {\n\t\tseen.add(current);\n\t\tif (current instanceof Error) {\n\t\t\tparts.push(current.message);\n\t\t\tcurrent = current.cause;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn parts.join(\" \");\n}\n\n/** Classify adapter/getAuth failures that mean the SuperGrok session is dead. */\nexport function planUsageAuthError(error: unknown): string | undefined {\n\tconst chain = errorChain(error);\n\tif (/timed out|aborted|cancelled|ECONN|ENOTFOUND|network/i.test(chain)) return undefined;\n\t// 403 on billing is often entitlement, not a dead refresh token.\n\tif (/xai billing rejected the session \\(HTTP 401\\)/i.test(chain)) return XAI_RELOGIN;\n\tif (/invalid_grant|refresh token revoked/i.test(chain)) return XAI_RELOGIN;\n\treturn undefined;\n}\n\ntype UsageAdapter = (runtime: ModelRuntime) => Promise<PlanUsage | undefined>;\n\nconst ADAPTERS: Readonly<Record<string, UsageAdapter>> = {\n\t\"openai-codex\": fetchCodexPlanUsage,\n\t\"kimi-coding\": fetchKimiPlanUsage,\n\tzai: fetchZaiPlanUsage,\n\txai: fetchXaiPlanUsage,\n};\n\nexport const PLAN_USAGE_CACHE_TTL_MS = 60 * 1000;\n\nexport type PlanUsageWindowPreference = \"5h\" | \"weekly\";\n\nexport function isWeeklyPlanWindow(window: PlanUsageWindow): boolean {\n\treturn /week/i.test(window.label);\n}\n\nexport function isFiveHourPlanWindow(window: PlanUsageWindow): boolean {\n\treturn /5h/i.test(window.label) || window.label === \"5h\";\n}\n\n/** Preferred window, falling back to the other, skipping Extra/on-demand. */\nexport function pickPlanWindow(\n\tusage: PlanUsage | undefined,\n\tpreferred: PlanUsageWindowPreference,\n): PlanUsageWindow | undefined {\n\tif (!usage?.windows.length) return undefined;\n\tconst usable = usage.windows.filter((w) => !/extra/i.test(w.label));\n\tconst weekly = usable.find(isWeeklyPlanWindow);\n\tconst fiveH = usable.find(isFiveHourPlanWindow);\n\tif (preferred === \"5h\") return fiveH ?? weekly ?? usable[0] ?? usage.windows[0];\n\treturn weekly ?? fiveH ?? usable[0] ?? usage.windows[0];\n}\n\nexport function footerPlanLabel(window: PlanUsageWindow): string {\n\tif (isFiveHourPlanWindow(window)) return \"5h\";\n\tif (isWeeklyPlanWindow(window)) return \"wk\";\n\treturn window.label.length <= 4 ? window.label : window.label.slice(0, 4);\n}\n\nconst cache = new Map<string, { expiresAt: number; value: PlanUsage | undefined }>();\nconst inflight = new Map<string, Promise<PlanUsageResult>>();\n\n/** Whether a plan-usage adapter exists for this provider. */\nexport function hasPlanUsageAdapter(providerId: string): boolean {\n\treturn providerId in ADAPTERS;\n}\n\n/** Plan usage for a provider, or undefined when unsupported/unavailable. Never throws. */\nexport async function getPlanUsage(providerId: string, runtime: ModelRuntime): Promise<PlanUsage | undefined> {\n\treturn (await getPlanUsageResult(providerId, runtime)).usage;\n}\n\n/** Like getPlanUsage, but surfaces SuperGrok/auth failures instead of hiding them. */\nexport async function getPlanUsageResult(providerId: string, runtime: ModelRuntime): Promise<PlanUsageResult> {\n\tconst adapter = ADAPTERS[providerId];\n\tif (!adapter) return {};\n\tconst now = Date.now();\n\tconst cached = cache.get(providerId);\n\tif (cached && cached.expiresAt > now) return { usage: cached.value };\n\tconst pending = inflight.get(providerId);\n\tif (pending) return pending;\n\tconst task = (async (): Promise<PlanUsageResult> => {\n\t\ttry {\n\t\t\tconst value = await adapter(runtime);\n\t\t\tcache.set(providerId, { expiresAt: Date.now() + PLAN_USAGE_CACHE_TTL_MS, value });\n\t\t\treturn { usage: value };\n\t\t} catch (error) {\n\t\t\tconst authError = planUsageAuthError(error);\n\t\t\tif (authError) return { error: authError };\n\t\t\tcache.set(providerId, { expiresAt: Date.now() + PLAN_USAGE_CACHE_TTL_MS, value: undefined });\n\t\t\treturn {};\n\t\t} finally {\n\t\t\tinflight.delete(providerId);\n\t\t}\n\t})();\n\tinflight.set(providerId, task);\n\treturn task;\n}\n\n/** Last fetched usage, including expired cache (footer can show stale while refetching). */\nexport function peekPlanUsage(providerId: string): PlanUsage | undefined {\n\treturn cache.get(providerId)?.value;\n}\n\n/** Clear the adapter cache (tests, /login changes). */\nexport function clearPlanUsageCache(): void {\n\tcache.clear();\n\tinflight.clear();\n}\n\n// ---------------------------------------------------------------------------\n// Extension bridge\n// ---------------------------------------------------------------------------\n\nexport const USAGE_SERVICE_BRIDGE_SYMBOL = Symbol.for(\"@lunr/usage-service\");\n\nexport interface FooterPlanSegment {\n\tlabel: string;\n\tusedPercent: number;\n}\n\nexport interface UsageServiceBridge {\n\tpeek(providerId: string): PlanUsage | undefined;\n\tprefetch(providerId: string): void;\n\tgetPreferredWindow(): PlanUsageWindowPreference;\n\tpickForFooter(providerId: string): FooterPlanSegment | undefined;\n\tsetOnUpdate(fn: (() => void) | undefined): void;\n}\n\nlet activeRuntime: ModelRuntime | undefined;\nlet activeUsageSettings: SettingsManager | undefined;\nlet onUsageUpdate: (() => void) | undefined;\n\nfunction preferredWindow(): PlanUsageWindowPreference {\n\treturn activeUsageSettings?.getPlanUsageWindow() ?? \"weekly\";\n}\n\nconst usageBridge: UsageServiceBridge = {\n\tpeek(providerId: string): PlanUsage | undefined {\n\t\treturn peekPlanUsage(providerId);\n\t},\n\tprefetch(providerId: string): void {\n\t\tif (!activeRuntime || !hasPlanUsageAdapter(providerId)) return;\n\t\tvoid getPlanUsage(providerId, activeRuntime).then(() => onUsageUpdate?.());\n\t},\n\tsetOnUpdate(fn: (() => void) | undefined): void {\n\t\tonUsageUpdate = fn;\n\t},\n\tgetPreferredWindow(): PlanUsageWindowPreference {\n\t\treturn preferredWindow();\n\t},\n\tpickForFooter(providerId: string): FooterPlanSegment | undefined {\n\t\tconst window = pickPlanWindow(peekPlanUsage(providerId), preferredWindow());\n\t\tif (!window) return undefined;\n\t\treturn { label: footerPlanLabel(window), usedPercent: window.usedPercent };\n\t},\n};\n\nexport function registerUsageServiceBridge(runtime: ModelRuntime, settingsManager: SettingsManager): void {\n\tactiveRuntime = runtime;\n\tactiveUsageSettings = settingsManager;\n\t(globalThis as Record<symbol, unknown>)[USAGE_SERVICE_BRIDGE_SYMBOL] = usageBridge;\n}\n\nexport function getUsageServiceBridge(): UsageServiceBridge | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[USAGE_SERVICE_BRIDGE_SYMBOL] as UsageServiceBridge | undefined;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-bridge.d.ts","sourceRoot":"","sources":["../../src/gateway/agent-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAoB,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,EAAgB,iBAAiB,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAC9F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAEpE,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAE7D,OAAO,KAAK,EAAE,sBAAsB,EAAuC,MAAM,4BAA4B,CAAC;AAG9G,OAAO,KAAK,EAAqB,YAAY,EAAiB,MAAM,YAAY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V,WAAW;YAsBX,WAAW;IAkBzB,OAAO,CAAC,gBAAgB;IAyBxB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,mBAAmB;CAK3B","sourcesContent":["/**\n * lunR: gateway agent bridge.\n *\n * Owns the sessionKey → AgentSession mapping: an LRU cache (cap 20) over\n * live sessions, backed by store.ts so conversations survive daemon restarts\n * (a stored sessionFile is reopened via SessionManager.open, which\n * createAgentSession restores history from; a missing file starts fresh with\n * a one-line warning).\n *\n * New sessions replicate main.ts's headless wiring: SettingsManager +\n * DefaultResourceLoader with the builtin extension factories + the three\n * lunr bridges, then bindExtensions({ mode: \"print\" }) like print-mode.\n *\n * Busy guard: one turn per session at a time. Messages arriving mid-turn are\n * queued (cap 5, oldest dropped with a notice) and drained FIFO as a single\n * concatenated follow-up turn once the running turn ends; runTurn returns\n * the QUEUED sentinel for those, and the follow-up turn's result is\n * delivered via callbacks.onFollowUpResult.\n *\n * Streaming: subscribes to session events and converts cumulative\n * message_update snapshots into deltas for callbacks.onDelta.\n *\n * isGatewayTurn()/runDepth: incremented around every prompt() so Phase 4\n * (cron↔gateway delivery) and extensions can detect they run inside a\n * gateway turn and refuse self-scheduling. Every prompt() also runs inside\n * runWithOrigin(source, ...) (core/cron/origin-context) so tools executing\n * during the turn — e.g. the `cron` tool's create action — can read the chat\n * the message came from and stamp it as the job's delivery origin.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { AgentMessage, ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { AssistantMessage, ImageContent } from \"@ashx-j/lunr-ai\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport type { AgentSession, AgentSessionEvent, SessionStats } from \"../core/agent-session.ts\";\nimport type { CompactionResult } from \"../core/compaction/index.ts\";\nimport { runWithOrigin } from \"../core/cron/origin-context.ts\";\nimport type { ContextUsage, ToolDefinition } from \"../core/extensions/types.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport { createPermissionContext, deletePermissionContext } from \"../core/permissions.ts\";\nimport type { ReadonlySessionManager, SessionManager, SessionMessageEntry } from \"../core/session-manager.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { getSession, putSession, removeSession, touchSession } from \"./store.ts\";\nimport type { InboundAttachment, MessageEvent, SessionSource } from \"./types.ts\";\n\nfunction isUserMessageEntry(entry: { type: string }): entry is SessionMessageEntry {\n\treturn entry.type === \"message\";\n}\n\n/** runTurn resolves with this when the message was queued behind a running turn. */\nexport const QUEUED = \"__lunr_gateway_queued__\";\n\nconst CACHE_CAP = 20;\nconst QUEUE_CAP = 5;\n\nlet runDepth = 0;\n\n/** True while a gateway turn's prompt() is in flight. */\nexport function isGatewayTurn(): boolean {\n\treturn runDepth > 0;\n}\n\nexport function gatewayRunDepth(): number {\n\treturn runDepth;\n}\n\nexport interface TurnCallbacks {\n\t/** Assistant text delta during streaming (converted from cumulative snapshots). */\n\tonDelta?: (delta: string) => void;\n\t/** Final text of a drained-queue follow-up turn (deliver it like a normal reply). */\n\tonFollowUpResult?: (text: string) => void;\n\t/** Error from a drained-queue follow-up turn. */\n\tonError?: (message: string) => void;\n}\n\nexport interface BridgeSessionStatus {\n\tbusy: boolean;\n\tqueueDepth: number;\n\tcreatedAt?: string;\n}\n\n/**\n * Structural session shape the bridge needs — satisfied by AgentSession,\n * fakeable in tests. Expanded to support gateway slash commands.\n */\nexport interface BridgeSession {\n\tprompt(text: string, options?: { source?: \"extension\"; images?: ImageContent[] }): Promise<void>;\n\tabort(): Promise<void> | void;\n\tsubscribe(listener: (event: AgentSessionEvent) => void): () => void;\n\treadonly state: { messages: AgentMessage[] };\n\tdispose?(): void;\n\treadonly isStreaming: boolean;\n\treadonly isCompacting?: boolean;\n\treadonly model?: Model<any>;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly messages: AgentMessage[];\n\treadonly systemPrompt: string;\n\treadonly sessionManager?: ReadonlySessionManager;\n\n\tgetActiveToolNames(): string[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tsetModel(model: Model<any>): Promise<void>;\n\tcompact(customInstructions?: string): Promise<CompactionResult>;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean }>;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetSessionStats(): SessionStats;\n\tsetSessionName(name: string): void;\n}\n\nexport type SessionFactory = (key: string, reopen: { sessionFile: string } | undefined) => Promise<BridgeSession>;\n\ninterface CacheEntry {\n\tsession: BridgeSession;\n\tbusy: boolean;\n\tqueue: MessageEvent[];\n\tdropped: number;\n\tunsubscribe?: () => void;\n}\n\n/**\n * Default factory: headless session with the builtin extensions, mirroring\n * main.ts (minus TUI) + print-mode's bindExtensions.\n *\n * The heavy wiring is imported LAZILY: a static import of\n * builtin-extensions/index.ts here would pull the whole extension + TUI\n * graph into every consumer of this module (router tests, `gateway status`)\n * and trip the known ashxj-tui ↔ package-barrel cycle (see AGENTS.md\n * \"Barrel-import guard\"). Loading it on first session creation keeps module\n * import light and matches how main.ts loads it in the real CLI.\n */\nasync function defaultSessionFactory(key: string, reopen: { sessionFile: string } | undefined): Promise<AgentSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t]);\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\t// Same bridges main.ts registers before extensions load.\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterCustomizeBridge(settingsManager);\n\n\tlet sessionManager: SessionManager;\n\tif (reopen && existsSync(reopen.sessionFile)) {\n\t\tsessionManager = SessionManager.open(reopen.sessionFile);\n\t} else {\n\t\tif (reopen) {\n\t\t\tconsole.warn(`[gateway] stored session file missing for ${key}; starting a fresh session`);\n\t\t}\n\t\tsessionManager = SessionManager.create(cwd);\n\t}\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider (this\n\t// exact bug sent gateway turns to openrouter with no key → 401).\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager });\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as AssistantMessage;\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content) {\n\t\tif (content.type === \"text\") text += content.text;\n\t}\n\treturn text;\n}\n\nexport class AgentBridge {\n\tprivate cap: number;\n\tprivate readonly sessionFactory: SessionFactory;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate readonly redoStack = new Map<string, string[]>();\n\tprivate readonly creating = new Map<string, Promise<CacheEntry>>();\n\n\tconstructor(options: { cacheCap?: number; sessionFactory?: SessionFactory } = {}) {\n\t\tthis.cap = options.cacheCap ?? CACHE_CAP;\n\t\tthis.sessionFactory = options.sessionFactory ?? defaultSessionFactory;\n\t}\n\n\t/**\n\t * Run one conversational turn. Resolves with the final assistant text, or\n\t * the QUEUED sentinel when the session was busy (router must not reply).\n\t */\n\tasync runTurn(key: string, event: MessageEvent, callbacks: TurnCallbacks = {}): Promise<string> {\n\t\tconst entry = await this.getOrCreate(key);\n\t\tif (entry.busy) {\n\t\t\tif (entry.queue.length >= QUEUE_CAP) {\n\t\t\t\tentry.queue.shift();\n\t\t\t\tentry.dropped++;\n\t\t\t}\n\t\t\tentry.queue.push(event);\n\t\t\treturn QUEUED;\n\t\t}\n\t\tentry.busy = true;\n\t\tlet result: string;\n\t\ttry {\n\t\t\tresult = await this.runPrompt(entry, event.text, callbacks, event.source, event.attachments);\n\t\t} catch (err) {\n\t\t\tentry.busy = false;\n\t\t\tthrow err;\n\t\t}\n\t\ttouchSession(key);\n\t\t// Drain queued messages as one follow-up turn, fire-and-forget. The busy\n\t\t// flag stays set until the queue is empty so turn ordering is strict;\n\t\t// the follow-up result arrives via callbacks.onFollowUpResult.\n\t\tvoid this.drainQueue(entry, callbacks).finally(() => {\n\t\t\tentry.busy = false;\n\t\t});\n\t\treturn result;\n\t}\n\n\tasync abort(key: string): Promise<void> {\n\t\tawait this.cache.get(key)?.session.abort();\n\t}\n\n\t/** Return the live session for a key, or null when none exists yet. */\n\tasync getSession(key: string): Promise<BridgeSession | null> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) return cached.session;\n\t\tif (!getSession(key)) return null;\n\t\treturn (await this.getOrCreate(key)).session;\n\t}\n\n\t/** Switch the chat to a different persisted session file. */\n\tasync switchSession(key: string, sessionFile: string): Promise<void> {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry?.busy) {\n\t\t\tthrow new Error(\"Session is busy — /stop first or wait\");\n\t\t}\n\t\tif (entry) {\n\t\t\tconst oldSessionId = entry.session.sessionManager?.getSessionId();\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t\tif (oldSessionId) deletePermissionContext(oldSessionId);\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\n\t\tconst session = await this.sessionFactory(key, { sessionFile });\n\t\tconst newFile = session.sessionManager?.getSessionFile();\n\t\tconst newSessionId = session.sessionManager?.getSessionId();\n\t\tif (newFile) {\n\t\t\tputSession(key, { sessionId: newSessionId ?? key, sessionFile: newFile });\n\t\t}\n\t\tif (newSessionId) {\n\t\t\tcreatePermissionContext(newSessionId);\n\t\t}\n\t\tconst newEntry: CacheEntry = { session, busy: false, queue: [], dropped: 0 };\n\t\tthis.cache.set(key, newEntry);\n\t\tthis._enforceCacheCap(key);\n\t\tnewEntry.unsubscribe = this._subscribeToSession(key, newEntry);\n\t}\n\n\t/** Undo the last user turn and push the previous leaf onto the redo stack. */\n\tasync undo(key: string): Promise<{ userText: string }> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst branch = session.sessionManager?.getBranch() ?? [];\n\t\tlet lastUserIndex = -1;\n\t\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branch[i];\n\t\t\tif (isUserMessageEntry(entry) && entry.message.role === \"user\") {\n\t\t\t\tlastUserIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (lastUserIndex === -1) throw new Error(\"Nothing to undo\");\n\t\tconst lastUser = branch[lastUserIndex];\n\t\tif (!isUserMessageEntry(lastUser)) throw new Error(\"Nothing to undo\");\n\n\t\tconst leafId = session.sessionManager?.getLeafId() ?? null;\n\t\tlet targetId: string;\n\t\tif (lastUser.id === leafId) {\n\t\t\tif (!lastUser.parentId) throw new Error(\"Nothing to undo\");\n\t\t\ttargetId = lastUser.parentId;\n\t\t} else {\n\t\t\ttargetId = lastUser.id;\n\t\t}\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) throw new Error(\"Navigation cancelled\");\n\n\t\tif (leafId) {\n\t\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\t\tstack.push(leafId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t}\n\n\t\treturn { userText: extractUserText(lastUser.message) };\n\t}\n\n\t/** Redo to the leaf saved by the most recent undo. */\n\tasync redo(key: string): Promise<void> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\tconst targetId = stack.pop();\n\t\tif (!targetId) throw new Error(\"Nothing to redo\");\n\t\tthis.redoStack.set(key, stack);\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) {\n\t\t\tstack.push(targetId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t\tthrow new Error(\"Navigation cancelled\");\n\t\t}\n\t}\n\n\t/** Test/debug hook: how many redo targets are saved for a key. */\n\tgetRedoStackLength(key: string): number {\n\t\treturn this.redoStack.get(key)?.length ?? 0;\n\t}\n\n\t/** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */\n\treset(key: string): void {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry) {\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\t}\n\n\tgetStatus(key: string): BridgeSessionStatus {\n\t\tconst entry = this.cache.get(key);\n\t\treturn {\n\t\t\tbusy: entry?.busy ?? false,\n\t\t\tqueueDepth: entry?.queue.length ?? 0,\n\t\t\tcreatedAt: getSession(key)?.createdAt,\n\t\t};\n\t}\n\n\t/** One prompt → final text. Increments runDepth; streams deltas when asked. */\n\tprivate async runPrompt(\n\t\tentry: CacheEntry,\n\t\ttext: string,\n\t\tcallbacks: TurnCallbacks,\n\t\tsource: SessionSource,\n\t\tattachments?: InboundAttachment[],\n\t): Promise<string> {\n\t\tconst { session } = entry;\n\t\tlet unsubscribe: (() => void) | undefined;\n\t\tif (callbacks.onDelta) {\n\t\t\tconst onDelta = callbacks.onDelta;\n\t\t\tlet streamedLen = 0;\n\t\t\tunsubscribe = session.subscribe((event: AgentSessionEvent) => {\n\t\t\t\tif (event.type !== \"message_update\") return;\n\t\t\t\tconst assistantEvent = event.assistantMessageEvent;\n\t\t\t\tif (assistantEvent.type !== \"text_delta\") return;\n\t\t\t\tlet full = \"\";\n\t\t\t\tfor (const content of assistantEvent.partial.content) {\n\t\t\t\t\tif (content.type === \"text\") full += content.text;\n\t\t\t\t}\n\t\t\t\tif (full.length < streamedLen) streamedLen = 0; // new assistant message (tool-call boundary)\n\t\t\t\tif (full.length > streamedLen) {\n\t\t\t\t\tonDelta(full.slice(streamedLen));\n\t\t\t\t\tstreamedLen = full.length;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\trunDepth++;\n\t\ttry {\n\t\t\t// lunr: convert inbound image attachments to ImageContent for the model.\n\t\t\t// processImage normalizes + resizes under the inline 4.5MB base64 limit;\n\t\t\t// failures become bracketed text notes so the model explains the gap.\n\t\t\tconst images: ImageContent[] = [];\n\t\t\tconst notes: string[] = [];\n\t\t\tfor (const attachment of attachments ?? []) {\n\t\t\t\tconst bytes = Buffer.from(attachment.data, \"base64\");\n\t\t\t\tconst processed = await processImage(new Uint8Array(bytes), attachment.mimeType);\n\t\t\t\tif (processed.ok) {\n\t\t\t\t\timages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\t\t\t\tfor (const hint of processed.hints) notes.push(hint);\n\t\t\t\t} else {\n\t\t\t\t\tnotes.push(processed.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst promptText = notes.length > 0 ? `${text}\\n\\n${notes.join(\" \")}` : text;\n\t\t\t// AsyncLocalStorage origin: tools executing during this turn (e.g. the\n\t\t\t// `cron` tool) can read the chat the message came from. Propagates\n\t\t\t// through the awaited prompt() call tree.\n\t\t\tawait runWithOrigin(\n\t\t\t\t{\n\t\t\t\t\tplatform: source.platform,\n\t\t\t\t\tchatId: source.chatId,\n\t\t\t\t\tthreadId: source.threadId,\n\t\t\t\t\tchatType: source.chatType,\n\t\t\t\t},\n\t\t\t\t() => session.prompt(promptText, { source: \"extension\", ...(images.length ? { images } : {}) }),\n\t\t\t);\n\t\t} finally {\n\t\t\trunDepth--;\n\t\t\tunsubscribe?.();\n\t\t}\n\t\treturn extractFinalText(session);\n\t}\n\n\t/** Drain the queue FIFO: all queued messages become one concatenated turn. */\n\tprivate async drainQueue(entry: CacheEntry, callbacks: TurnCallbacks): Promise<void> {\n\t\twhile (entry.queue.length > 0) {\n\t\t\tconst items = entry.queue.splice(0);\n\t\t\tconst parts = items.map((item) => item.text);\n\t\t\tconst attachments = items.flatMap((item) => item.attachments ?? []);\n\t\t\tif (entry.dropped > 0) {\n\t\t\t\tparts.unshift(`[gateway: ${entry.dropped} earlier message(s) were dropped — the queue was full]`);\n\t\t\t\tentry.dropped = 0;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t// Follow-up turns are final-only: no streaming callbacks. The origin\n\t\t\t\t// is the chat of the latest queued message.\n\t\t\t\tconst text = await this.runPrompt(\n\t\t\t\t\tentry,\n\t\t\t\t\tparts.join(\"\\n\\n\"),\n\t\t\t\t\t{},\n\t\t\t\t\titems[items.length - 1].source,\n\t\t\t\t\tattachments,\n\t\t\t\t);\n\t\t\t\tcallbacks.onFollowUpResult?.(text);\n\t\t\t} catch (err) {\n\t\t\t\tcallbacks.onError?.(err instanceof Error ? err.message : String(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async getOrCreate(key: string): Promise<CacheEntry> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\t// LRU refresh\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, cached);\n\t\t\treturn cached;\n\t\t}\n\t\t// Coalesce concurrent creation for the same key.\n\t\tlet pending = this.creating.get(key);\n\t\tif (!pending) {\n\t\t\tpending = this.createEntry(key);\n\t\t\tthis.creating.set(key, pending);\n\t\t\ttry {\n\t\t\t\tawait pending;\n\t\t\t} finally {\n\t\t\t\tthis.creating.delete(key);\n\t\t\t}\n\t\t}\n\t\treturn pending;\n\t}\n\n\tprivate async createEntry(key: string): Promise<CacheEntry> {\n\t\tconst stored = getSession(key);\n\t\tconst session = await this.sessionFactory(key, stored ? { sessionFile: stored.sessionFile } : undefined);\n\t\tconst sessionFile = session.sessionManager?.getSessionFile();\n\t\tconst sessionId = session.sessionManager?.getSessionId();\n\t\tif (sessionFile) {\n\t\t\tputSession(key, { sessionId: sessionId ?? key, sessionFile });\n\t\t}\n\t\tif (sessionId) {\n\t\t\tcreatePermissionContext(sessionId);\n\t\t}\n\t\tconst entry: CacheEntry = { session, busy: false, queue: [], dropped: 0, unsubscribe: undefined };\n\t\tthis.cache.set(key, entry);\n\t\tthis._enforceCacheCap(key);\n\t\tentry.unsubscribe = this._subscribeToSession(key, entry);\n\t\treturn entry;\n\t}\n\n\tprivate _enforceCacheCap(protectedKey?: string): void {\n\t\twhile (this.cache.size > this.cap) {\n\t\t\tlet oldestKey: string | undefined;\n\t\t\tlet oldest: CacheEntry | undefined;\n\t\t\tfor (const [key, entry] of this.cache) {\n\t\t\t\tif (key === protectedKey) continue;\n\t\t\t\tif (entry.busy) continue;\n\t\t\t\toldestKey = key;\n\t\t\t\toldest = entry;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!oldest || !oldestKey) {\n\t\t\t\t// Every cached session is busy (or is the protected new entry);\n\t\t\t\t// grow the cap temporarily rather than killing an in-flight turn.\n\t\t\t\tthis.cap = this.cache.size;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toldest.unsubscribe?.();\n\t\t\tthis.cache.delete(oldestKey);\n\t\t\toldest.session.dispose?.();\n\t\t\tconst evictedSessionId = oldest.session.sessionManager?.getSessionId();\n\t\t\tif (evictedSessionId) deletePermissionContext(evictedSessionId);\n\t\t}\n\t}\n\n\tprivate _subscribeToSession(key: string, entry: CacheEntry): () => void {\n\t\treturn entry.session.subscribe((event) => this._handleSessionEvent(key, event));\n\t}\n\n\tprivate _handleSessionEvent(key: string, event: AgentSessionEvent): void {\n\t\tif (event.type === \"message_start\" && event.message?.role === \"user\") {\n\t\t\tthis.redoStack.delete(key);\n\t\t}\n\t}\n}\n\nfunction extractUserText(message: AgentMessage): string {\n\tlet text = \"\";\n\tif (\"content\" in message && Array.isArray(message.content)) {\n\t\tfor (const block of message.content) {\n\t\t\tif (\n\t\t\t\tblock &&\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\"\n\t\t\t) {\n\t\t\t\ttext += block.text;\n\t\t\t}\n\t\t}\n\t}\n\treturn text;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-bridge.d.ts","sourceRoot":"","sources":["../../src/gateway/agent-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAoB,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAA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QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAoCrD;IAED,sDAAsD;IAChD,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAerC;IAED,kEAAkE;IAClE,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtC;IAED,wFAAwF;IACxF,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CASvB;IAED,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAO1C;YAGa,SAAS;YAiET,UAAU;YA2BV,WAAW;YAsBX,WAAW;IAkBzB,OAAO,CAAC,gBAAgB;IAyBxB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,mBAAmB;CAK3B","sourcesContent":["/**\n * lunR: gateway agent bridge.\n *\n * Owns the sessionKey → AgentSession mapping: an LRU cache (cap 20) over\n * live sessions, backed by store.ts so conversations survive daemon restarts\n * (a stored sessionFile is reopened via SessionManager.open, which\n * createAgentSession restores history from; a missing file starts fresh with\n * a one-line warning).\n *\n * New sessions replicate main.ts's headless wiring: SettingsManager +\n * DefaultResourceLoader with the builtin extension factories + the three\n * lunr bridges, then bindExtensions({ mode: \"print\" }) like print-mode.\n *\n * Busy guard: one turn per session at a time. Messages arriving mid-turn are\n * queued (cap 5, oldest dropped with a notice) and drained FIFO as a single\n * concatenated follow-up turn once the running turn ends; runTurn returns\n * the QUEUED sentinel for those, and the follow-up turn's result is\n * delivered via callbacks.onFollowUpResult.\n *\n * Streaming: subscribes to session events and converts cumulative\n * message_update snapshots into deltas for callbacks.onDelta.\n *\n * isGatewayTurn()/runDepth: incremented around every prompt() so Phase 4\n * (cron↔gateway delivery) and extensions can detect they run inside a\n * gateway turn and refuse self-scheduling. Every prompt() also runs inside\n * runWithOrigin(source, ...) (core/cron/origin-context) so tools executing\n * during the turn — e.g. the `cron` tool's create action — can read the chat\n * the message came from and stamp it as the job's delivery origin.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { AgentMessage, ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { AssistantMessage, ImageContent } from \"@ashx-j/lunr-ai\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport type { AgentSession, AgentSessionEvent, SessionStats } from \"../core/agent-session.ts\";\nimport type { CompactionResult } from \"../core/compaction/index.ts\";\nimport { runWithOrigin } from \"../core/cron/origin-context.ts\";\nimport type { ContextUsage, ToolDefinition } from \"../core/extensions/types.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport { createPermissionContext, deletePermissionContext } from \"../core/permissions.ts\";\nimport type { ReadonlySessionManager, SessionManager, SessionMessageEntry } from \"../core/session-manager.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { getSession, putSession, removeSession, touchSession } from \"./store.ts\";\nimport type { InboundAttachment, MessageEvent, SessionSource } from \"./types.ts\";\n\nfunction isUserMessageEntry(entry: { type: string }): entry is SessionMessageEntry {\n\treturn entry.type === \"message\";\n}\n\n/** runTurn resolves with this when the message was queued behind a running turn. */\nexport const QUEUED = \"__lunr_gateway_queued__\";\n\nconst CACHE_CAP = 20;\nconst QUEUE_CAP = 5;\n\nlet runDepth = 0;\n\n/** True while a gateway turn's prompt() is in flight. */\nexport function isGatewayTurn(): boolean {\n\treturn runDepth > 0;\n}\n\nexport function gatewayRunDepth(): number {\n\treturn runDepth;\n}\n\nexport interface TurnCallbacks {\n\t/** Assistant text delta during streaming (converted from cumulative snapshots). */\n\tonDelta?: (delta: string) => void;\n\t/** Final text of a drained-queue follow-up turn (deliver it like a normal reply). */\n\tonFollowUpResult?: (text: string) => void;\n\t/** Error from a drained-queue follow-up turn. */\n\tonError?: (message: string) => void;\n}\n\nexport interface BridgeSessionStatus {\n\tbusy: boolean;\n\tqueueDepth: number;\n\tcreatedAt?: string;\n}\n\n/**\n * Structural session shape the bridge needs — satisfied by AgentSession,\n * fakeable in tests. Expanded to support gateway slash commands.\n */\nexport interface BridgeSession {\n\tprompt(text: string, options?: { source?: \"extension\"; images?: ImageContent[] }): Promise<void>;\n\tabort(): Promise<void> | void;\n\tsubscribe(listener: (event: AgentSessionEvent) => void): () => void;\n\treadonly state: { messages: AgentMessage[] };\n\tdispose?(): void;\n\treadonly isStreaming: boolean;\n\treadonly isCompacting?: boolean;\n\treadonly model?: Model<any>;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly messages: AgentMessage[];\n\treadonly systemPrompt: string;\n\treadonly sessionManager?: ReadonlySessionManager;\n\n\tgetActiveToolNames(): string[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tsetModel(model: Model<any>): Promise<void>;\n\tcompact(customInstructions?: string): Promise<CompactionResult>;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean }>;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetSessionStats(): SessionStats;\n\tsetSessionName(name: string): void;\n}\n\nexport type SessionFactory = (key: string, reopen: { sessionFile: string } | undefined) => Promise<BridgeSession>;\n\ninterface CacheEntry {\n\tsession: BridgeSession;\n\tbusy: boolean;\n\tqueue: MessageEvent[];\n\tdropped: number;\n\tunsubscribe?: () => void;\n}\n\n/**\n * Default factory: headless session with the builtin extensions, mirroring\n * main.ts (minus TUI) + print-mode's bindExtensions.\n *\n * The heavy wiring is imported LAZILY: a static import of\n * builtin-extensions/index.ts here would pull the whole extension + TUI\n * graph into every consumer of this module (router tests, `gateway status`)\n * and trip the known ashxj-tui ↔ package-barrel cycle (see AGENTS.md\n * \"Barrel-import guard\"). Loading it on first session creation keeps module\n * import light and matches how main.ts loads it in the real CLI.\n */\nasync function defaultSessionFactory(key: string, reopen: { sessionFile: string } | undefined): Promise<AgentSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ reconcileBehaviorPreset, registerBehaviorPresetBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ getModelTiersBridge, registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/behavior-preset.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t]);\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\t// Same bridges main.ts registers before extensions load.\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterBehaviorPresetBridge(settingsManager);\n\treconcileBehaviorPreset(settingsManager, agentDir);\n\tregisterCustomizeBridge(settingsManager);\n\n\tlet sessionManager: SessionManager;\n\tif (reopen && existsSync(reopen.sessionFile)) {\n\t\tsessionManager = SessionManager.open(reopen.sessionFile);\n\t} else {\n\t\tif (reopen) {\n\t\t\tconsole.warn(`[gateway] stored session file missing for ${key}; starting a fresh session`);\n\t\t}\n\t\tsessionManager = SessionManager.create(cwd);\n\t}\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider (this\n\t// exact bug sent gateway turns to openrouter with no key → 401).\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager });\n\tgetModelTiersBridge()?.setParentThinkingProvider(() => session.thinkingLevel);\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as AssistantMessage;\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content) {\n\t\tif (content.type === \"text\") text += content.text;\n\t}\n\treturn text;\n}\n\nexport class AgentBridge {\n\tprivate cap: number;\n\tprivate readonly sessionFactory: SessionFactory;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate readonly redoStack = new Map<string, string[]>();\n\tprivate readonly creating = new Map<string, Promise<CacheEntry>>();\n\n\tconstructor(options: { cacheCap?: number; sessionFactory?: SessionFactory } = {}) {\n\t\tthis.cap = options.cacheCap ?? CACHE_CAP;\n\t\tthis.sessionFactory = options.sessionFactory ?? defaultSessionFactory;\n\t}\n\n\t/**\n\t * Run one conversational turn. Resolves with the final assistant text, or\n\t * the QUEUED sentinel when the session was busy (router must not reply).\n\t */\n\tasync runTurn(key: string, event: MessageEvent, callbacks: TurnCallbacks = {}): Promise<string> {\n\t\tconst entry = await this.getOrCreate(key);\n\t\tif (entry.busy) {\n\t\t\tif (entry.queue.length >= QUEUE_CAP) {\n\t\t\t\tentry.queue.shift();\n\t\t\t\tentry.dropped++;\n\t\t\t}\n\t\t\tentry.queue.push(event);\n\t\t\treturn QUEUED;\n\t\t}\n\t\tentry.busy = true;\n\t\tlet result: string;\n\t\ttry {\n\t\t\tresult = await this.runPrompt(entry, event.text, callbacks, event.source, event.attachments);\n\t\t} catch (err) {\n\t\t\tentry.busy = false;\n\t\t\tthrow err;\n\t\t}\n\t\ttouchSession(key);\n\t\t// Drain queued messages as one follow-up turn, fire-and-forget. The busy\n\t\t// flag stays set until the queue is empty so turn ordering is strict;\n\t\t// the follow-up result arrives via callbacks.onFollowUpResult.\n\t\tvoid this.drainQueue(entry, callbacks).finally(() => {\n\t\t\tentry.busy = false;\n\t\t});\n\t\treturn result;\n\t}\n\n\tasync abort(key: string): Promise<void> {\n\t\tawait this.cache.get(key)?.session.abort();\n\t}\n\n\t/** Return the live session for a key, or null when none exists yet. */\n\tasync getSession(key: string): Promise<BridgeSession | null> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) return cached.session;\n\t\tif (!getSession(key)) return null;\n\t\treturn (await this.getOrCreate(key)).session;\n\t}\n\n\t/** Switch the chat to a different persisted session file. */\n\tasync switchSession(key: string, sessionFile: string): Promise<void> {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry?.busy) {\n\t\t\tthrow new Error(\"Session is busy — /stop first or wait\");\n\t\t}\n\t\tif (entry) {\n\t\t\tconst oldSessionId = entry.session.sessionManager?.getSessionId();\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t\tif (oldSessionId) deletePermissionContext(oldSessionId);\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\n\t\tconst session = await this.sessionFactory(key, { sessionFile });\n\t\tconst newFile = session.sessionManager?.getSessionFile();\n\t\tconst newSessionId = session.sessionManager?.getSessionId();\n\t\tif (newFile) {\n\t\t\tputSession(key, { sessionId: newSessionId ?? key, sessionFile: newFile });\n\t\t}\n\t\tif (newSessionId) {\n\t\t\tcreatePermissionContext(newSessionId);\n\t\t}\n\t\tconst newEntry: CacheEntry = { session, busy: false, queue: [], dropped: 0 };\n\t\tthis.cache.set(key, newEntry);\n\t\tthis._enforceCacheCap(key);\n\t\tnewEntry.unsubscribe = this._subscribeToSession(key, newEntry);\n\t}\n\n\t/** Undo the last user turn and push the previous leaf onto the redo stack. */\n\tasync undo(key: string): Promise<{ userText: string }> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst branch = session.sessionManager?.getBranch() ?? [];\n\t\tlet lastUserIndex = -1;\n\t\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branch[i];\n\t\t\tif (isUserMessageEntry(entry) && entry.message.role === \"user\") {\n\t\t\t\tlastUserIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (lastUserIndex === -1) throw new Error(\"Nothing to undo\");\n\t\tconst lastUser = branch[lastUserIndex];\n\t\tif (!isUserMessageEntry(lastUser)) throw new Error(\"Nothing to undo\");\n\n\t\tconst leafId = session.sessionManager?.getLeafId() ?? null;\n\t\tlet targetId: string;\n\t\tif (lastUser.id === leafId) {\n\t\t\tif (!lastUser.parentId) throw new Error(\"Nothing to undo\");\n\t\t\ttargetId = lastUser.parentId;\n\t\t} else {\n\t\t\ttargetId = lastUser.id;\n\t\t}\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) throw new Error(\"Navigation cancelled\");\n\n\t\tif (leafId) {\n\t\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\t\tstack.push(leafId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t}\n\n\t\treturn { userText: extractUserText(lastUser.message) };\n\t}\n\n\t/** Redo to the leaf saved by the most recent undo. */\n\tasync redo(key: string): Promise<void> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\tconst targetId = stack.pop();\n\t\tif (!targetId) throw new Error(\"Nothing to redo\");\n\t\tthis.redoStack.set(key, stack);\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) {\n\t\t\tstack.push(targetId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t\tthrow new Error(\"Navigation cancelled\");\n\t\t}\n\t}\n\n\t/** Test/debug hook: how many redo targets are saved for a key. */\n\tgetRedoStackLength(key: string): number {\n\t\treturn this.redoStack.get(key)?.length ?? 0;\n\t}\n\n\t/** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */\n\treset(key: string): void {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry) {\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\t}\n\n\tgetStatus(key: string): BridgeSessionStatus {\n\t\tconst entry = this.cache.get(key);\n\t\treturn {\n\t\t\tbusy: entry?.busy ?? false,\n\t\t\tqueueDepth: entry?.queue.length ?? 0,\n\t\t\tcreatedAt: getSession(key)?.createdAt,\n\t\t};\n\t}\n\n\t/** One prompt → final text. Increments runDepth; streams deltas when asked. */\n\tprivate async runPrompt(\n\t\tentry: CacheEntry,\n\t\ttext: string,\n\t\tcallbacks: TurnCallbacks,\n\t\tsource: SessionSource,\n\t\tattachments?: InboundAttachment[],\n\t): Promise<string> {\n\t\tconst { session } = entry;\n\t\tlet unsubscribe: (() => void) | undefined;\n\t\tif (callbacks.onDelta) {\n\t\t\tconst onDelta = callbacks.onDelta;\n\t\t\tlet streamedLen = 0;\n\t\t\tunsubscribe = session.subscribe((event: AgentSessionEvent) => {\n\t\t\t\tif (event.type !== \"message_update\") return;\n\t\t\t\tconst assistantEvent = event.assistantMessageEvent;\n\t\t\t\tif (assistantEvent.type !== \"text_delta\") return;\n\t\t\t\tlet full = \"\";\n\t\t\t\tfor (const content of assistantEvent.partial.content) {\n\t\t\t\t\tif (content.type === \"text\") full += content.text;\n\t\t\t\t}\n\t\t\t\tif (full.length < streamedLen) streamedLen = 0; // new assistant message (tool-call boundary)\n\t\t\t\tif (full.length > streamedLen) {\n\t\t\t\t\tonDelta(full.slice(streamedLen));\n\t\t\t\t\tstreamedLen = full.length;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\trunDepth++;\n\t\ttry {\n\t\t\t// lunr: convert inbound image attachments to ImageContent for the model.\n\t\t\t// processImage normalizes + resizes under the inline 4.5MB base64 limit;\n\t\t\t// failures become bracketed text notes so the model explains the gap.\n\t\t\tconst images: ImageContent[] = [];\n\t\t\tconst notes: string[] = [];\n\t\t\tfor (const attachment of attachments ?? []) {\n\t\t\t\tconst bytes = Buffer.from(attachment.data, \"base64\");\n\t\t\t\tconst processed = await processImage(new Uint8Array(bytes), attachment.mimeType);\n\t\t\t\tif (processed.ok) {\n\t\t\t\t\timages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\t\t\t\tfor (const hint of processed.hints) notes.push(hint);\n\t\t\t\t} else {\n\t\t\t\t\tnotes.push(processed.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst promptText = notes.length > 0 ? `${text}\\n\\n${notes.join(\" \")}` : text;\n\t\t\t// AsyncLocalStorage origin: tools executing during this turn (e.g. the\n\t\t\t// `cron` tool) can read the chat the message came from. Propagates\n\t\t\t// through the awaited prompt() call tree.\n\t\t\tawait runWithOrigin(\n\t\t\t\t{\n\t\t\t\t\tplatform: source.platform,\n\t\t\t\t\tchatId: source.chatId,\n\t\t\t\t\tthreadId: source.threadId,\n\t\t\t\t\tchatType: source.chatType,\n\t\t\t\t},\n\t\t\t\t() => session.prompt(promptText, { source: \"extension\", ...(images.length ? { images } : {}) }),\n\t\t\t);\n\t\t} finally {\n\t\t\trunDepth--;\n\t\t\tunsubscribe?.();\n\t\t}\n\t\treturn extractFinalText(session);\n\t}\n\n\t/** Drain the queue FIFO: all queued messages become one concatenated turn. */\n\tprivate async drainQueue(entry: CacheEntry, callbacks: TurnCallbacks): Promise<void> {\n\t\twhile (entry.queue.length > 0) {\n\t\t\tconst items = entry.queue.splice(0);\n\t\t\tconst parts = items.map((item) => item.text);\n\t\t\tconst attachments = items.flatMap((item) => item.attachments ?? []);\n\t\t\tif (entry.dropped > 0) {\n\t\t\t\tparts.unshift(`[gateway: ${entry.dropped} earlier message(s) were dropped — the queue was full]`);\n\t\t\t\tentry.dropped = 0;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t// Follow-up turns are final-only: no streaming callbacks. The origin\n\t\t\t\t// is the chat of the latest queued message.\n\t\t\t\tconst text = await this.runPrompt(\n\t\t\t\t\tentry,\n\t\t\t\t\tparts.join(\"\\n\\n\"),\n\t\t\t\t\t{},\n\t\t\t\t\titems[items.length - 1].source,\n\t\t\t\t\tattachments,\n\t\t\t\t);\n\t\t\t\tcallbacks.onFollowUpResult?.(text);\n\t\t\t} catch (err) {\n\t\t\t\tcallbacks.onError?.(err instanceof Error ? err.message : String(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async getOrCreate(key: string): Promise<CacheEntry> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\t// LRU refresh\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, cached);\n\t\t\treturn cached;\n\t\t}\n\t\t// Coalesce concurrent creation for the same key.\n\t\tlet pending = this.creating.get(key);\n\t\tif (!pending) {\n\t\t\tpending = this.createEntry(key);\n\t\t\tthis.creating.set(key, pending);\n\t\t\ttry {\n\t\t\t\tawait pending;\n\t\t\t} finally {\n\t\t\t\tthis.creating.delete(key);\n\t\t\t}\n\t\t}\n\t\treturn pending;\n\t}\n\n\tprivate async createEntry(key: string): Promise<CacheEntry> {\n\t\tconst stored = getSession(key);\n\t\tconst session = await this.sessionFactory(key, stored ? { sessionFile: stored.sessionFile } : undefined);\n\t\tconst sessionFile = session.sessionManager?.getSessionFile();\n\t\tconst sessionId = session.sessionManager?.getSessionId();\n\t\tif (sessionFile) {\n\t\t\tputSession(key, { sessionId: sessionId ?? key, sessionFile });\n\t\t}\n\t\tif (sessionId) {\n\t\t\tcreatePermissionContext(sessionId);\n\t\t}\n\t\tconst entry: CacheEntry = { session, busy: false, queue: [], dropped: 0, unsubscribe: undefined };\n\t\tthis.cache.set(key, entry);\n\t\tthis._enforceCacheCap(key);\n\t\tentry.unsubscribe = this._subscribeToSession(key, entry);\n\t\treturn entry;\n\t}\n\n\tprivate _enforceCacheCap(protectedKey?: string): void {\n\t\twhile (this.cache.size > this.cap) {\n\t\t\tlet oldestKey: string | undefined;\n\t\t\tlet oldest: CacheEntry | undefined;\n\t\t\tfor (const [key, entry] of this.cache) {\n\t\t\t\tif (key === protectedKey) continue;\n\t\t\t\tif (entry.busy) continue;\n\t\t\t\toldestKey = key;\n\t\t\t\toldest = entry;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!oldest || !oldestKey) {\n\t\t\t\t// Every cached session is busy (or is the protected new entry);\n\t\t\t\t// grow the cap temporarily rather than killing an in-flight turn.\n\t\t\t\tthis.cap = this.cache.size;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toldest.unsubscribe?.();\n\t\t\tthis.cache.delete(oldestKey);\n\t\t\toldest.session.dispose?.();\n\t\t\tconst evictedSessionId = oldest.session.sessionManager?.getSessionId();\n\t\t\tif (evictedSessionId) deletePermissionContext(evictedSessionId);\n\t\t}\n\t}\n\n\tprivate _subscribeToSession(key: string, entry: CacheEntry): () => void {\n\t\treturn entry.session.subscribe((event) => this._handleSessionEvent(key, event));\n\t}\n\n\tprivate _handleSessionEvent(key: string, event: AgentSessionEvent): void {\n\t\tif (event.type === \"message_start\" && event.message?.role === \"user\") {\n\t\t\tthis.redoStack.delete(key);\n\t\t}\n\t}\n}\n\nfunction extractUserText(message: AgentMessage): string {\n\tlet text = \"\";\n\tif (\"content\" in message && Array.isArray(message.content)) {\n\t\tfor (const block of message.content) {\n\t\t\tif (\n\t\t\t\tblock &&\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\"\n\t\t\t) {\n\t\t\t\ttext += block.text;\n\t\t\t}\n\t\t}\n\t}\n\treturn text;\n}\n"]}
|
|
@@ -59,10 +59,11 @@ export function gatewayRunDepth() {
|
|
|
59
59
|
* import light and matches how main.ts loads it in the real CLI.
|
|
60
60
|
*/
|
|
61
61
|
async function defaultSessionFactory(key, reopen) {
|
|
62
|
-
const [{ loadAllBuiltinExtensions }, { getAgentDir }, { registerCustomizeBridge }, { registerMemoryCapBridge }, { registerModelTierBridge }, { createAgentSessionFromServices, createAgentSessionServices }, { SessionManager }, { SettingsManager },] = await Promise.all([
|
|
62
|
+
const [{ loadAllBuiltinExtensions }, { getAgentDir }, { registerCustomizeBridge }, { reconcileBehaviorPreset, registerBehaviorPresetBridge }, { registerMemoryCapBridge }, { getModelTiersBridge, registerModelTierBridge }, { createAgentSessionFromServices, createAgentSessionServices }, { SessionManager }, { SettingsManager },] = await Promise.all([
|
|
63
63
|
import("../builtin-extensions/index.js"),
|
|
64
64
|
import("../config.js"),
|
|
65
65
|
import("../core/customize.js"),
|
|
66
|
+
import("../core/behavior-preset.js"),
|
|
66
67
|
import("../core/memory-cap.js"),
|
|
67
68
|
import("../core/model-tiers.js"),
|
|
68
69
|
import("../core/agent-session-services.js"),
|
|
@@ -75,6 +76,8 @@ async function defaultSessionFactory(key, reopen) {
|
|
|
75
76
|
// Same bridges main.ts registers before extensions load.
|
|
76
77
|
registerModelTierBridge(settingsManager);
|
|
77
78
|
registerMemoryCapBridge(settingsManager);
|
|
79
|
+
registerBehaviorPresetBridge(settingsManager);
|
|
80
|
+
reconcileBehaviorPreset(settingsManager, agentDir);
|
|
78
81
|
registerCustomizeBridge(settingsManager);
|
|
79
82
|
let sessionManager;
|
|
80
83
|
if (reopen && existsSync(reopen.sessionFile)) {
|
|
@@ -98,6 +101,7 @@ async function defaultSessionFactory(key, reopen) {
|
|
|
98
101
|
resourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },
|
|
99
102
|
});
|
|
100
103
|
const { session } = await createAgentSessionFromServices({ services, sessionManager });
|
|
104
|
+
getModelTiersBridge()?.setParentThinkingProvider(() => session.thinkingLevel);
|
|
101
105
|
await session.bindExtensions({
|
|
102
106
|
mode: "print",
|
|
103
107
|
onError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-bridge.js","sourceRoot":"","sources":["../../src/gateway/agent-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAMrC,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAG/D,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAE1F,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAGjF,SAAS,kBAAkB,CAAC,KAAuB,EAAgC;IAClF,OAAO,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC;AAAA,CAChC;AAED,oFAAoF;AACpF,MAAM,CAAC,MAAM,MAAM,GAAG,yBAAyB,CAAC;AAEhD,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,SAAS,GAAG,CAAC,CAAC;AAEpB,IAAI,QAAQ,GAAG,CAAC,CAAC;AAEjB,yDAAyD;AACzD,MAAM,UAAU,aAAa,GAAY;IACxC,OAAO,QAAQ,GAAG,CAAC,CAAC;AAAA,CACpB;AAED,MAAM,UAAU,eAAe,GAAW;IACzC,OAAO,QAAQ,CAAC;AAAA,CAChB;AA8DD;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,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["/**\n * lunR: gateway agent bridge.\n *\n * Owns the sessionKey → AgentSession mapping: an LRU cache (cap 20) over\n * live sessions, backed by store.ts so conversations survive daemon restarts\n * (a stored sessionFile is reopened via SessionManager.open, which\n * createAgentSession restores history from; a missing file starts fresh with\n * a one-line warning).\n *\n * New sessions replicate main.ts's headless wiring: SettingsManager +\n * DefaultResourceLoader with the builtin extension factories + the three\n * lunr bridges, then bindExtensions({ mode: \"print\" }) like print-mode.\n *\n * Busy guard: one turn per session at a time. Messages arriving mid-turn are\n * queued (cap 5, oldest dropped with a notice) and drained FIFO as a single\n * concatenated follow-up turn once the running turn ends; runTurn returns\n * the QUEUED sentinel for those, and the follow-up turn's result is\n * delivered via callbacks.onFollowUpResult.\n *\n * Streaming: subscribes to session events and converts cumulative\n * message_update snapshots into deltas for callbacks.onDelta.\n *\n * isGatewayTurn()/runDepth: incremented around every prompt() so Phase 4\n * (cron↔gateway delivery) and extensions can detect they run inside a\n * gateway turn and refuse self-scheduling. Every prompt() also runs inside\n * runWithOrigin(source, ...) (core/cron/origin-context) so tools executing\n * during the turn — e.g. the `cron` tool's create action — can read the chat\n * the message came from and stamp it as the job's delivery origin.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { AgentMessage, ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { AssistantMessage, ImageContent } from \"@ashx-j/lunr-ai\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport type { AgentSession, AgentSessionEvent, SessionStats } from \"../core/agent-session.ts\";\nimport type { CompactionResult } from \"../core/compaction/index.ts\";\nimport { runWithOrigin } from \"../core/cron/origin-context.ts\";\nimport type { ContextUsage, ToolDefinition } from \"../core/extensions/types.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport { createPermissionContext, deletePermissionContext } from \"../core/permissions.ts\";\nimport type { ReadonlySessionManager, SessionManager, SessionMessageEntry } from \"../core/session-manager.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { getSession, putSession, removeSession, touchSession } from \"./store.ts\";\nimport type { InboundAttachment, MessageEvent, SessionSource } from \"./types.ts\";\n\nfunction isUserMessageEntry(entry: { type: string }): entry is SessionMessageEntry {\n\treturn entry.type === \"message\";\n}\n\n/** runTurn resolves with this when the message was queued behind a running turn. */\nexport const QUEUED = \"__lunr_gateway_queued__\";\n\nconst CACHE_CAP = 20;\nconst QUEUE_CAP = 5;\n\nlet runDepth = 0;\n\n/** True while a gateway turn's prompt() is in flight. */\nexport function isGatewayTurn(): boolean {\n\treturn runDepth > 0;\n}\n\nexport function gatewayRunDepth(): number {\n\treturn runDepth;\n}\n\nexport interface TurnCallbacks {\n\t/** Assistant text delta during streaming (converted from cumulative snapshots). */\n\tonDelta?: (delta: string) => void;\n\t/** Final text of a drained-queue follow-up turn (deliver it like a normal reply). */\n\tonFollowUpResult?: (text: string) => void;\n\t/** Error from a drained-queue follow-up turn. */\n\tonError?: (message: string) => void;\n}\n\nexport interface BridgeSessionStatus {\n\tbusy: boolean;\n\tqueueDepth: number;\n\tcreatedAt?: string;\n}\n\n/**\n * Structural session shape the bridge needs — satisfied by AgentSession,\n * fakeable in tests. Expanded to support gateway slash commands.\n */\nexport interface BridgeSession {\n\tprompt(text: string, options?: { source?: \"extension\"; images?: ImageContent[] }): Promise<void>;\n\tabort(): Promise<void> | void;\n\tsubscribe(listener: (event: AgentSessionEvent) => void): () => void;\n\treadonly state: { messages: AgentMessage[] };\n\tdispose?(): void;\n\treadonly isStreaming: boolean;\n\treadonly isCompacting?: boolean;\n\treadonly model?: Model<any>;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly messages: AgentMessage[];\n\treadonly systemPrompt: string;\n\treadonly sessionManager?: ReadonlySessionManager;\n\n\tgetActiveToolNames(): string[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tsetModel(model: Model<any>): Promise<void>;\n\tcompact(customInstructions?: string): Promise<CompactionResult>;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean }>;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetSessionStats(): SessionStats;\n\tsetSessionName(name: string): void;\n}\n\nexport type SessionFactory = (key: string, reopen: { sessionFile: string } | undefined) => Promise<BridgeSession>;\n\ninterface CacheEntry {\n\tsession: BridgeSession;\n\tbusy: boolean;\n\tqueue: MessageEvent[];\n\tdropped: number;\n\tunsubscribe?: () => void;\n}\n\n/**\n * Default factory: headless session with the builtin extensions, mirroring\n * main.ts (minus TUI) + print-mode's bindExtensions.\n *\n * The heavy wiring is imported LAZILY: a static import of\n * builtin-extensions/index.ts here would pull the whole extension + TUI\n * graph into every consumer of this module (router tests, `gateway status`)\n * and trip the known ashxj-tui ↔ package-barrel cycle (see AGENTS.md\n * \"Barrel-import guard\"). Loading it on first session creation keeps module\n * import light and matches how main.ts loads it in the real CLI.\n */\nasync function defaultSessionFactory(key: string, reopen: { sessionFile: string } | undefined): Promise<AgentSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t]);\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\t// Same bridges main.ts registers before extensions load.\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterCustomizeBridge(settingsManager);\n\n\tlet sessionManager: SessionManager;\n\tif (reopen && existsSync(reopen.sessionFile)) {\n\t\tsessionManager = SessionManager.open(reopen.sessionFile);\n\t} else {\n\t\tif (reopen) {\n\t\t\tconsole.warn(`[gateway] stored session file missing for ${key}; starting a fresh session`);\n\t\t}\n\t\tsessionManager = SessionManager.create(cwd);\n\t}\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider (this\n\t// exact bug sent gateway turns to openrouter with no key → 401).\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager });\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as AssistantMessage;\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content) {\n\t\tif (content.type === \"text\") text += content.text;\n\t}\n\treturn text;\n}\n\nexport class AgentBridge {\n\tprivate cap: number;\n\tprivate readonly sessionFactory: SessionFactory;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate readonly redoStack = new Map<string, string[]>();\n\tprivate readonly creating = new Map<string, Promise<CacheEntry>>();\n\n\tconstructor(options: { cacheCap?: number; sessionFactory?: SessionFactory } = {}) {\n\t\tthis.cap = options.cacheCap ?? CACHE_CAP;\n\t\tthis.sessionFactory = options.sessionFactory ?? defaultSessionFactory;\n\t}\n\n\t/**\n\t * Run one conversational turn. Resolves with the final assistant text, or\n\t * the QUEUED sentinel when the session was busy (router must not reply).\n\t */\n\tasync runTurn(key: string, event: MessageEvent, callbacks: TurnCallbacks = {}): Promise<string> {\n\t\tconst entry = await this.getOrCreate(key);\n\t\tif (entry.busy) {\n\t\t\tif (entry.queue.length >= QUEUE_CAP) {\n\t\t\t\tentry.queue.shift();\n\t\t\t\tentry.dropped++;\n\t\t\t}\n\t\t\tentry.queue.push(event);\n\t\t\treturn QUEUED;\n\t\t}\n\t\tentry.busy = true;\n\t\tlet result: string;\n\t\ttry {\n\t\t\tresult = await this.runPrompt(entry, event.text, callbacks, event.source, event.attachments);\n\t\t} catch (err) {\n\t\t\tentry.busy = false;\n\t\t\tthrow err;\n\t\t}\n\t\ttouchSession(key);\n\t\t// Drain queued messages as one follow-up turn, fire-and-forget. The busy\n\t\t// flag stays set until the queue is empty so turn ordering is strict;\n\t\t// the follow-up result arrives via callbacks.onFollowUpResult.\n\t\tvoid this.drainQueue(entry, callbacks).finally(() => {\n\t\t\tentry.busy = false;\n\t\t});\n\t\treturn result;\n\t}\n\n\tasync abort(key: string): Promise<void> {\n\t\tawait this.cache.get(key)?.session.abort();\n\t}\n\n\t/** Return the live session for a key, or null when none exists yet. */\n\tasync getSession(key: string): Promise<BridgeSession | null> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) return cached.session;\n\t\tif (!getSession(key)) return null;\n\t\treturn (await this.getOrCreate(key)).session;\n\t}\n\n\t/** Switch the chat to a different persisted session file. */\n\tasync switchSession(key: string, sessionFile: string): Promise<void> {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry?.busy) {\n\t\t\tthrow new Error(\"Session is busy — /stop first or wait\");\n\t\t}\n\t\tif (entry) {\n\t\t\tconst oldSessionId = entry.session.sessionManager?.getSessionId();\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t\tif (oldSessionId) deletePermissionContext(oldSessionId);\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\n\t\tconst session = await this.sessionFactory(key, { sessionFile });\n\t\tconst newFile = session.sessionManager?.getSessionFile();\n\t\tconst newSessionId = session.sessionManager?.getSessionId();\n\t\tif (newFile) {\n\t\t\tputSession(key, { sessionId: newSessionId ?? key, sessionFile: newFile });\n\t\t}\n\t\tif (newSessionId) {\n\t\t\tcreatePermissionContext(newSessionId);\n\t\t}\n\t\tconst newEntry: CacheEntry = { session, busy: false, queue: [], dropped: 0 };\n\t\tthis.cache.set(key, newEntry);\n\t\tthis._enforceCacheCap(key);\n\t\tnewEntry.unsubscribe = this._subscribeToSession(key, newEntry);\n\t}\n\n\t/** Undo the last user turn and push the previous leaf onto the redo stack. */\n\tasync undo(key: string): Promise<{ userText: string }> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst branch = session.sessionManager?.getBranch() ?? [];\n\t\tlet lastUserIndex = -1;\n\t\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branch[i];\n\t\t\tif (isUserMessageEntry(entry) && entry.message.role === \"user\") {\n\t\t\t\tlastUserIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (lastUserIndex === -1) throw new Error(\"Nothing to undo\");\n\t\tconst lastUser = branch[lastUserIndex];\n\t\tif (!isUserMessageEntry(lastUser)) throw new Error(\"Nothing to undo\");\n\n\t\tconst leafId = session.sessionManager?.getLeafId() ?? null;\n\t\tlet targetId: string;\n\t\tif (lastUser.id === leafId) {\n\t\t\tif (!lastUser.parentId) throw new Error(\"Nothing to undo\");\n\t\t\ttargetId = lastUser.parentId;\n\t\t} else {\n\t\t\ttargetId = lastUser.id;\n\t\t}\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) throw new Error(\"Navigation cancelled\");\n\n\t\tif (leafId) {\n\t\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\t\tstack.push(leafId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t}\n\n\t\treturn { userText: extractUserText(lastUser.message) };\n\t}\n\n\t/** Redo to the leaf saved by the most recent undo. */\n\tasync redo(key: string): Promise<void> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\tconst targetId = stack.pop();\n\t\tif (!targetId) throw new Error(\"Nothing to redo\");\n\t\tthis.redoStack.set(key, stack);\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) {\n\t\t\tstack.push(targetId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t\tthrow new Error(\"Navigation cancelled\");\n\t\t}\n\t}\n\n\t/** Test/debug hook: how many redo targets are saved for a key. */\n\tgetRedoStackLength(key: string): number {\n\t\treturn this.redoStack.get(key)?.length ?? 0;\n\t}\n\n\t/** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */\n\treset(key: string): void {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry) {\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\t}\n\n\tgetStatus(key: string): BridgeSessionStatus {\n\t\tconst entry = this.cache.get(key);\n\t\treturn {\n\t\t\tbusy: entry?.busy ?? false,\n\t\t\tqueueDepth: entry?.queue.length ?? 0,\n\t\t\tcreatedAt: getSession(key)?.createdAt,\n\t\t};\n\t}\n\n\t/** One prompt → final text. Increments runDepth; streams deltas when asked. */\n\tprivate async runPrompt(\n\t\tentry: CacheEntry,\n\t\ttext: string,\n\t\tcallbacks: TurnCallbacks,\n\t\tsource: SessionSource,\n\t\tattachments?: InboundAttachment[],\n\t): Promise<string> {\n\t\tconst { session } = entry;\n\t\tlet unsubscribe: (() => void) | undefined;\n\t\tif (callbacks.onDelta) {\n\t\t\tconst onDelta = callbacks.onDelta;\n\t\t\tlet streamedLen = 0;\n\t\t\tunsubscribe = session.subscribe((event: AgentSessionEvent) => {\n\t\t\t\tif (event.type !== \"message_update\") return;\n\t\t\t\tconst assistantEvent = event.assistantMessageEvent;\n\t\t\t\tif (assistantEvent.type !== \"text_delta\") return;\n\t\t\t\tlet full = \"\";\n\t\t\t\tfor (const content of assistantEvent.partial.content) {\n\t\t\t\t\tif (content.type === \"text\") full += content.text;\n\t\t\t\t}\n\t\t\t\tif (full.length < streamedLen) streamedLen = 0; // new assistant message (tool-call boundary)\n\t\t\t\tif (full.length > streamedLen) {\n\t\t\t\t\tonDelta(full.slice(streamedLen));\n\t\t\t\t\tstreamedLen = full.length;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\trunDepth++;\n\t\ttry {\n\t\t\t// lunr: convert inbound image attachments to ImageContent for the model.\n\t\t\t// processImage normalizes + resizes under the inline 4.5MB base64 limit;\n\t\t\t// failures become bracketed text notes so the model explains the gap.\n\t\t\tconst images: ImageContent[] = [];\n\t\t\tconst notes: string[] = [];\n\t\t\tfor (const attachment of attachments ?? []) {\n\t\t\t\tconst bytes = Buffer.from(attachment.data, \"base64\");\n\t\t\t\tconst processed = await processImage(new Uint8Array(bytes), attachment.mimeType);\n\t\t\t\tif (processed.ok) {\n\t\t\t\t\timages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\t\t\t\tfor (const hint of processed.hints) notes.push(hint);\n\t\t\t\t} else {\n\t\t\t\t\tnotes.push(processed.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst promptText = notes.length > 0 ? `${text}\\n\\n${notes.join(\" \")}` : text;\n\t\t\t// AsyncLocalStorage origin: tools executing during this turn (e.g. the\n\t\t\t// `cron` tool) can read the chat the message came from. Propagates\n\t\t\t// through the awaited prompt() call tree.\n\t\t\tawait runWithOrigin(\n\t\t\t\t{\n\t\t\t\t\tplatform: source.platform,\n\t\t\t\t\tchatId: source.chatId,\n\t\t\t\t\tthreadId: source.threadId,\n\t\t\t\t\tchatType: source.chatType,\n\t\t\t\t},\n\t\t\t\t() => session.prompt(promptText, { source: \"extension\", ...(images.length ? { images } : {}) }),\n\t\t\t);\n\t\t} finally {\n\t\t\trunDepth--;\n\t\t\tunsubscribe?.();\n\t\t}\n\t\treturn extractFinalText(session);\n\t}\n\n\t/** Drain the queue FIFO: all queued messages become one concatenated turn. */\n\tprivate async drainQueue(entry: CacheEntry, callbacks: TurnCallbacks): Promise<void> {\n\t\twhile (entry.queue.length > 0) {\n\t\t\tconst items = entry.queue.splice(0);\n\t\t\tconst parts = items.map((item) => item.text);\n\t\t\tconst attachments = items.flatMap((item) => item.attachments ?? []);\n\t\t\tif (entry.dropped > 0) {\n\t\t\t\tparts.unshift(`[gateway: ${entry.dropped} earlier message(s) were dropped — the queue was full]`);\n\t\t\t\tentry.dropped = 0;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t// Follow-up turns are final-only: no streaming callbacks. The origin\n\t\t\t\t// is the chat of the latest queued message.\n\t\t\t\tconst text = await this.runPrompt(\n\t\t\t\t\tentry,\n\t\t\t\t\tparts.join(\"\\n\\n\"),\n\t\t\t\t\t{},\n\t\t\t\t\titems[items.length - 1].source,\n\t\t\t\t\tattachments,\n\t\t\t\t);\n\t\t\t\tcallbacks.onFollowUpResult?.(text);\n\t\t\t} catch (err) {\n\t\t\t\tcallbacks.onError?.(err instanceof Error ? err.message : String(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async getOrCreate(key: string): Promise<CacheEntry> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\t// LRU refresh\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, cached);\n\t\t\treturn cached;\n\t\t}\n\t\t// Coalesce concurrent creation for the same key.\n\t\tlet pending = this.creating.get(key);\n\t\tif (!pending) {\n\t\t\tpending = this.createEntry(key);\n\t\t\tthis.creating.set(key, pending);\n\t\t\ttry {\n\t\t\t\tawait pending;\n\t\t\t} finally {\n\t\t\t\tthis.creating.delete(key);\n\t\t\t}\n\t\t}\n\t\treturn pending;\n\t}\n\n\tprivate async createEntry(key: string): Promise<CacheEntry> {\n\t\tconst stored = getSession(key);\n\t\tconst session = await this.sessionFactory(key, stored ? { sessionFile: stored.sessionFile } : undefined);\n\t\tconst sessionFile = session.sessionManager?.getSessionFile();\n\t\tconst sessionId = session.sessionManager?.getSessionId();\n\t\tif (sessionFile) {\n\t\t\tputSession(key, { sessionId: sessionId ?? key, sessionFile });\n\t\t}\n\t\tif (sessionId) {\n\t\t\tcreatePermissionContext(sessionId);\n\t\t}\n\t\tconst entry: CacheEntry = { session, busy: false, queue: [], dropped: 0, unsubscribe: undefined };\n\t\tthis.cache.set(key, entry);\n\t\tthis._enforceCacheCap(key);\n\t\tentry.unsubscribe = this._subscribeToSession(key, entry);\n\t\treturn entry;\n\t}\n\n\tprivate _enforceCacheCap(protectedKey?: string): void {\n\t\twhile (this.cache.size > this.cap) {\n\t\t\tlet oldestKey: string | undefined;\n\t\t\tlet oldest: CacheEntry | undefined;\n\t\t\tfor (const [key, entry] of this.cache) {\n\t\t\t\tif (key === protectedKey) continue;\n\t\t\t\tif (entry.busy) continue;\n\t\t\t\toldestKey = key;\n\t\t\t\toldest = entry;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!oldest || !oldestKey) {\n\t\t\t\t// Every cached session is busy (or is the protected new entry);\n\t\t\t\t// grow the cap temporarily rather than killing an in-flight turn.\n\t\t\t\tthis.cap = this.cache.size;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toldest.unsubscribe?.();\n\t\t\tthis.cache.delete(oldestKey);\n\t\t\toldest.session.dispose?.();\n\t\t\tconst evictedSessionId = oldest.session.sessionManager?.getSessionId();\n\t\t\tif (evictedSessionId) deletePermissionContext(evictedSessionId);\n\t\t}\n\t}\n\n\tprivate _subscribeToSession(key: string, entry: CacheEntry): () => void {\n\t\treturn entry.session.subscribe((event) => this._handleSessionEvent(key, event));\n\t}\n\n\tprivate _handleSessionEvent(key: string, event: AgentSessionEvent): void {\n\t\tif (event.type === \"message_start\" && event.message?.role === \"user\") {\n\t\t\tthis.redoStack.delete(key);\n\t\t}\n\t}\n}\n\nfunction extractUserText(message: AgentMessage): string {\n\tlet text = \"\";\n\tif (\"content\" in message && Array.isArray(message.content)) {\n\t\tfor (const block of message.content) {\n\t\t\tif (\n\t\t\t\tblock &&\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\"\n\t\t\t) {\n\t\t\t\ttext += block.text;\n\t\t\t}\n\t\t}\n\t}\n\treturn text;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-bridge.js","sourceRoot":"","sources":["../../src/gateway/agent-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAMrC,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAG/D,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAE1F,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,YA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AC;IAAA,CAChF;IAEO,mBAAmB,CAAC,GAAW,EAAE,KAAwB,EAAQ;QACxE,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,IAAI,KAAK,CAAC,OAAO,EAAE,IAAI,KAAK,MAAM,EAAE,CAAC;YACtE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC5B,CAAC;IAAA,CACD;CACD;AAED,SAAS,eAAe,CAAC,OAAqB,EAAU;IACvD,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,IAAI,SAAS,IAAI,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5D,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACrC,IACC,KAAK;gBACL,OAAO,KAAK,KAAK,QAAQ;gBACzB,MAAM,IAAI,KAAK;gBACf,KAAK,CAAC,IAAI,KAAK,MAAM;gBACrB,MAAM,IAAI,KAAK;gBACf,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,EAC7B,CAAC;gBACF,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC;YACpB,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["/**\n * lunR: gateway agent bridge.\n *\n * Owns the sessionKey → AgentSession mapping: an LRU cache (cap 20) over\n * live sessions, backed by store.ts so conversations survive daemon restarts\n * (a stored sessionFile is reopened via SessionManager.open, which\n * createAgentSession restores history from; a missing file starts fresh with\n * a one-line warning).\n *\n * New sessions replicate main.ts's headless wiring: SettingsManager +\n * DefaultResourceLoader with the builtin extension factories + the three\n * lunr bridges, then bindExtensions({ mode: \"print\" }) like print-mode.\n *\n * Busy guard: one turn per session at a time. Messages arriving mid-turn are\n * queued (cap 5, oldest dropped with a notice) and drained FIFO as a single\n * concatenated follow-up turn once the running turn ends; runTurn returns\n * the QUEUED sentinel for those, and the follow-up turn's result is\n * delivered via callbacks.onFollowUpResult.\n *\n * Streaming: subscribes to session events and converts cumulative\n * message_update snapshots into deltas for callbacks.onDelta.\n *\n * isGatewayTurn()/runDepth: incremented around every prompt() so Phase 4\n * (cron↔gateway delivery) and extensions can detect they run inside a\n * gateway turn and refuse self-scheduling. Every prompt() also runs inside\n * runWithOrigin(source, ...) (core/cron/origin-context) so tools executing\n * during the turn — e.g. the `cron` tool's create action — can read the chat\n * the message came from and stamp it as the job's delivery origin.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { AgentMessage, ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { AssistantMessage, ImageContent } from \"@ashx-j/lunr-ai\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport type { AgentSession, AgentSessionEvent, SessionStats } from \"../core/agent-session.ts\";\nimport type { CompactionResult } from \"../core/compaction/index.ts\";\nimport { runWithOrigin } from \"../core/cron/origin-context.ts\";\nimport type { ContextUsage, ToolDefinition } from \"../core/extensions/types.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport { createPermissionContext, deletePermissionContext } from \"../core/permissions.ts\";\nimport type { ReadonlySessionManager, SessionManager, SessionMessageEntry } from \"../core/session-manager.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { getSession, putSession, removeSession, touchSession } from \"./store.ts\";\nimport type { InboundAttachment, MessageEvent, SessionSource } from \"./types.ts\";\n\nfunction isUserMessageEntry(entry: { type: string }): entry is SessionMessageEntry {\n\treturn entry.type === \"message\";\n}\n\n/** runTurn resolves with this when the message was queued behind a running turn. */\nexport const QUEUED = \"__lunr_gateway_queued__\";\n\nconst CACHE_CAP = 20;\nconst QUEUE_CAP = 5;\n\nlet runDepth = 0;\n\n/** True while a gateway turn's prompt() is in flight. */\nexport function isGatewayTurn(): boolean {\n\treturn runDepth > 0;\n}\n\nexport function gatewayRunDepth(): number {\n\treturn runDepth;\n}\n\nexport interface TurnCallbacks {\n\t/** Assistant text delta during streaming (converted from cumulative snapshots). */\n\tonDelta?: (delta: string) => void;\n\t/** Final text of a drained-queue follow-up turn (deliver it like a normal reply). */\n\tonFollowUpResult?: (text: string) => void;\n\t/** Error from a drained-queue follow-up turn. */\n\tonError?: (message: string) => void;\n}\n\nexport interface BridgeSessionStatus {\n\tbusy: boolean;\n\tqueueDepth: number;\n\tcreatedAt?: string;\n}\n\n/**\n * Structural session shape the bridge needs — satisfied by AgentSession,\n * fakeable in tests. Expanded to support gateway slash commands.\n */\nexport interface BridgeSession {\n\tprompt(text: string, options?: { source?: \"extension\"; images?: ImageContent[] }): Promise<void>;\n\tabort(): Promise<void> | void;\n\tsubscribe(listener: (event: AgentSessionEvent) => void): () => void;\n\treadonly state: { messages: AgentMessage[] };\n\tdispose?(): void;\n\treadonly isStreaming: boolean;\n\treadonly isCompacting?: boolean;\n\treadonly model?: Model<any>;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly messages: AgentMessage[];\n\treadonly systemPrompt: string;\n\treadonly sessionManager?: ReadonlySessionManager;\n\n\tgetActiveToolNames(): string[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tsetModel(model: Model<any>): Promise<void>;\n\tcompact(customInstructions?: string): Promise<CompactionResult>;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean }>;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetSessionStats(): SessionStats;\n\tsetSessionName(name: string): void;\n}\n\nexport type SessionFactory = (key: string, reopen: { sessionFile: string } | undefined) => Promise<BridgeSession>;\n\ninterface CacheEntry {\n\tsession: BridgeSession;\n\tbusy: boolean;\n\tqueue: MessageEvent[];\n\tdropped: number;\n\tunsubscribe?: () => void;\n}\n\n/**\n * Default factory: headless session with the builtin extensions, mirroring\n * main.ts (minus TUI) + print-mode's bindExtensions.\n *\n * The heavy wiring is imported LAZILY: a static import of\n * builtin-extensions/index.ts here would pull the whole extension + TUI\n * graph into every consumer of this module (router tests, `gateway status`)\n * and trip the known ashxj-tui ↔ package-barrel cycle (see AGENTS.md\n * \"Barrel-import guard\"). Loading it on first session creation keeps module\n * import light and matches how main.ts loads it in the real CLI.\n */\nasync function defaultSessionFactory(key: string, reopen: { sessionFile: string } | undefined): Promise<AgentSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ reconcileBehaviorPreset, registerBehaviorPresetBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ getModelTiersBridge, registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/behavior-preset.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t]);\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\t// Same bridges main.ts registers before extensions load.\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterBehaviorPresetBridge(settingsManager);\n\treconcileBehaviorPreset(settingsManager, agentDir);\n\tregisterCustomizeBridge(settingsManager);\n\n\tlet sessionManager: SessionManager;\n\tif (reopen && existsSync(reopen.sessionFile)) {\n\t\tsessionManager = SessionManager.open(reopen.sessionFile);\n\t} else {\n\t\tif (reopen) {\n\t\t\tconsole.warn(`[gateway] stored session file missing for ${key}; starting a fresh session`);\n\t\t}\n\t\tsessionManager = SessionManager.create(cwd);\n\t}\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider (this\n\t// exact bug sent gateway turns to openrouter with no key → 401).\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager });\n\tgetModelTiersBridge()?.setParentThinkingProvider(() => session.thinkingLevel);\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as AssistantMessage;\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content) {\n\t\tif (content.type === \"text\") text += content.text;\n\t}\n\treturn text;\n}\n\nexport class AgentBridge {\n\tprivate cap: number;\n\tprivate readonly sessionFactory: SessionFactory;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate readonly redoStack = new Map<string, string[]>();\n\tprivate readonly creating = new Map<string, Promise<CacheEntry>>();\n\n\tconstructor(options: { cacheCap?: number; sessionFactory?: SessionFactory } = {}) {\n\t\tthis.cap = options.cacheCap ?? CACHE_CAP;\n\t\tthis.sessionFactory = options.sessionFactory ?? defaultSessionFactory;\n\t}\n\n\t/**\n\t * Run one conversational turn. Resolves with the final assistant text, or\n\t * the QUEUED sentinel when the session was busy (router must not reply).\n\t */\n\tasync runTurn(key: string, event: MessageEvent, callbacks: TurnCallbacks = {}): Promise<string> {\n\t\tconst entry = await this.getOrCreate(key);\n\t\tif (entry.busy) {\n\t\t\tif (entry.queue.length >= QUEUE_CAP) {\n\t\t\t\tentry.queue.shift();\n\t\t\t\tentry.dropped++;\n\t\t\t}\n\t\t\tentry.queue.push(event);\n\t\t\treturn QUEUED;\n\t\t}\n\t\tentry.busy = true;\n\t\tlet result: string;\n\t\ttry {\n\t\t\tresult = await this.runPrompt(entry, event.text, callbacks, event.source, event.attachments);\n\t\t} catch (err) {\n\t\t\tentry.busy = false;\n\t\t\tthrow err;\n\t\t}\n\t\ttouchSession(key);\n\t\t// Drain queued messages as one follow-up turn, fire-and-forget. The busy\n\t\t// flag stays set until the queue is empty so turn ordering is strict;\n\t\t// the follow-up result arrives via callbacks.onFollowUpResult.\n\t\tvoid this.drainQueue(entry, callbacks).finally(() => {\n\t\t\tentry.busy = false;\n\t\t});\n\t\treturn result;\n\t}\n\n\tasync abort(key: string): Promise<void> {\n\t\tawait this.cache.get(key)?.session.abort();\n\t}\n\n\t/** Return the live session for a key, or null when none exists yet. */\n\tasync getSession(key: string): Promise<BridgeSession | null> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) return cached.session;\n\t\tif (!getSession(key)) return null;\n\t\treturn (await this.getOrCreate(key)).session;\n\t}\n\n\t/** Switch the chat to a different persisted session file. */\n\tasync switchSession(key: string, sessionFile: string): Promise<void> {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry?.busy) {\n\t\t\tthrow new Error(\"Session is busy — /stop first or wait\");\n\t\t}\n\t\tif (entry) {\n\t\t\tconst oldSessionId = entry.session.sessionManager?.getSessionId();\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t\tif (oldSessionId) deletePermissionContext(oldSessionId);\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\n\t\tconst session = await this.sessionFactory(key, { sessionFile });\n\t\tconst newFile = session.sessionManager?.getSessionFile();\n\t\tconst newSessionId = session.sessionManager?.getSessionId();\n\t\tif (newFile) {\n\t\t\tputSession(key, { sessionId: newSessionId ?? key, sessionFile: newFile });\n\t\t}\n\t\tif (newSessionId) {\n\t\t\tcreatePermissionContext(newSessionId);\n\t\t}\n\t\tconst newEntry: CacheEntry = { session, busy: false, queue: [], dropped: 0 };\n\t\tthis.cache.set(key, newEntry);\n\t\tthis._enforceCacheCap(key);\n\t\tnewEntry.unsubscribe = this._subscribeToSession(key, newEntry);\n\t}\n\n\t/** Undo the last user turn and push the previous leaf onto the redo stack. */\n\tasync undo(key: string): Promise<{ userText: string }> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst branch = session.sessionManager?.getBranch() ?? [];\n\t\tlet lastUserIndex = -1;\n\t\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branch[i];\n\t\t\tif (isUserMessageEntry(entry) && entry.message.role === \"user\") {\n\t\t\t\tlastUserIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (lastUserIndex === -1) throw new Error(\"Nothing to undo\");\n\t\tconst lastUser = branch[lastUserIndex];\n\t\tif (!isUserMessageEntry(lastUser)) throw new Error(\"Nothing to undo\");\n\n\t\tconst leafId = session.sessionManager?.getLeafId() ?? null;\n\t\tlet targetId: string;\n\t\tif (lastUser.id === leafId) {\n\t\t\tif (!lastUser.parentId) throw new Error(\"Nothing to undo\");\n\t\t\ttargetId = lastUser.parentId;\n\t\t} else {\n\t\t\ttargetId = lastUser.id;\n\t\t}\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) throw new Error(\"Navigation cancelled\");\n\n\t\tif (leafId) {\n\t\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\t\tstack.push(leafId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t}\n\n\t\treturn { userText: extractUserText(lastUser.message) };\n\t}\n\n\t/** Redo to the leaf saved by the most recent undo. */\n\tasync redo(key: string): Promise<void> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\tconst targetId = stack.pop();\n\t\tif (!targetId) throw new Error(\"Nothing to redo\");\n\t\tthis.redoStack.set(key, stack);\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) {\n\t\t\tstack.push(targetId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t\tthrow new Error(\"Navigation cancelled\");\n\t\t}\n\t}\n\n\t/** Test/debug hook: how many redo targets are saved for a key. */\n\tgetRedoStackLength(key: string): number {\n\t\treturn this.redoStack.get(key)?.length ?? 0;\n\t}\n\n\t/** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */\n\treset(key: string): void {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry) {\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\t}\n\n\tgetStatus(key: string): BridgeSessionStatus {\n\t\tconst entry = this.cache.get(key);\n\t\treturn {\n\t\t\tbusy: entry?.busy ?? false,\n\t\t\tqueueDepth: entry?.queue.length ?? 0,\n\t\t\tcreatedAt: getSession(key)?.createdAt,\n\t\t};\n\t}\n\n\t/** One prompt → final text. Increments runDepth; streams deltas when asked. */\n\tprivate async runPrompt(\n\t\tentry: CacheEntry,\n\t\ttext: string,\n\t\tcallbacks: TurnCallbacks,\n\t\tsource: SessionSource,\n\t\tattachments?: InboundAttachment[],\n\t): Promise<string> {\n\t\tconst { session } = entry;\n\t\tlet unsubscribe: (() => void) | undefined;\n\t\tif (callbacks.onDelta) {\n\t\t\tconst onDelta = callbacks.onDelta;\n\t\t\tlet streamedLen = 0;\n\t\t\tunsubscribe = session.subscribe((event: AgentSessionEvent) => {\n\t\t\t\tif (event.type !== \"message_update\") return;\n\t\t\t\tconst assistantEvent = event.assistantMessageEvent;\n\t\t\t\tif (assistantEvent.type !== \"text_delta\") return;\n\t\t\t\tlet full = \"\";\n\t\t\t\tfor (const content of assistantEvent.partial.content) {\n\t\t\t\t\tif (content.type === \"text\") full += content.text;\n\t\t\t\t}\n\t\t\t\tif (full.length < streamedLen) streamedLen = 0; // new assistant message (tool-call boundary)\n\t\t\t\tif (full.length > streamedLen) {\n\t\t\t\t\tonDelta(full.slice(streamedLen));\n\t\t\t\t\tstreamedLen = full.length;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\trunDepth++;\n\t\ttry {\n\t\t\t// lunr: convert inbound image attachments to ImageContent for the model.\n\t\t\t// processImage normalizes + resizes under the inline 4.5MB base64 limit;\n\t\t\t// failures become bracketed text notes so the model explains the gap.\n\t\t\tconst images: ImageContent[] = [];\n\t\t\tconst notes: string[] = [];\n\t\t\tfor (const attachment of attachments ?? []) {\n\t\t\t\tconst bytes = Buffer.from(attachment.data, \"base64\");\n\t\t\t\tconst processed = await processImage(new Uint8Array(bytes), attachment.mimeType);\n\t\t\t\tif (processed.ok) {\n\t\t\t\t\timages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\t\t\t\tfor (const hint of processed.hints) notes.push(hint);\n\t\t\t\t} else {\n\t\t\t\t\tnotes.push(processed.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst promptText = notes.length > 0 ? `${text}\\n\\n${notes.join(\" \")}` : text;\n\t\t\t// AsyncLocalStorage origin: tools executing during this turn (e.g. the\n\t\t\t// `cron` tool) can read the chat the message came from. Propagates\n\t\t\t// through the awaited prompt() call tree.\n\t\t\tawait runWithOrigin(\n\t\t\t\t{\n\t\t\t\t\tplatform: source.platform,\n\t\t\t\t\tchatId: source.chatId,\n\t\t\t\t\tthreadId: source.threadId,\n\t\t\t\t\tchatType: source.chatType,\n\t\t\t\t},\n\t\t\t\t() => session.prompt(promptText, { source: \"extension\", ...(images.length ? { images } : {}) }),\n\t\t\t);\n\t\t} finally {\n\t\t\trunDepth--;\n\t\t\tunsubscribe?.();\n\t\t}\n\t\treturn extractFinalText(session);\n\t}\n\n\t/** Drain the queue FIFO: all queued messages become one concatenated turn. */\n\tprivate async drainQueue(entry: CacheEntry, callbacks: TurnCallbacks): Promise<void> {\n\t\twhile (entry.queue.length > 0) {\n\t\t\tconst items = entry.queue.splice(0);\n\t\t\tconst parts = items.map((item) => item.text);\n\t\t\tconst attachments = items.flatMap((item) => item.attachments ?? []);\n\t\t\tif (entry.dropped > 0) {\n\t\t\t\tparts.unshift(`[gateway: ${entry.dropped} earlier message(s) were dropped — the queue was full]`);\n\t\t\t\tentry.dropped = 0;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t// Follow-up turns are final-only: no streaming callbacks. The origin\n\t\t\t\t// is the chat of the latest queued message.\n\t\t\t\tconst text = await this.runPrompt(\n\t\t\t\t\tentry,\n\t\t\t\t\tparts.join(\"\\n\\n\"),\n\t\t\t\t\t{},\n\t\t\t\t\titems[items.length - 1].source,\n\t\t\t\t\tattachments,\n\t\t\t\t);\n\t\t\t\tcallbacks.onFollowUpResult?.(text);\n\t\t\t} catch (err) {\n\t\t\t\tcallbacks.onError?.(err instanceof Error ? err.message : String(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async getOrCreate(key: string): Promise<CacheEntry> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\t// LRU refresh\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, cached);\n\t\t\treturn cached;\n\t\t}\n\t\t// Coalesce concurrent creation for the same key.\n\t\tlet pending = this.creating.get(key);\n\t\tif (!pending) {\n\t\t\tpending = this.createEntry(key);\n\t\t\tthis.creating.set(key, pending);\n\t\t\ttry {\n\t\t\t\tawait pending;\n\t\t\t} finally {\n\t\t\t\tthis.creating.delete(key);\n\t\t\t}\n\t\t}\n\t\treturn pending;\n\t}\n\n\tprivate async createEntry(key: string): Promise<CacheEntry> {\n\t\tconst stored = getSession(key);\n\t\tconst session = await this.sessionFactory(key, stored ? { sessionFile: stored.sessionFile } : undefined);\n\t\tconst sessionFile = session.sessionManager?.getSessionFile();\n\t\tconst sessionId = session.sessionManager?.getSessionId();\n\t\tif (sessionFile) {\n\t\t\tputSession(key, { sessionId: sessionId ?? key, sessionFile });\n\t\t}\n\t\tif (sessionId) {\n\t\t\tcreatePermissionContext(sessionId);\n\t\t}\n\t\tconst entry: CacheEntry = { session, busy: false, queue: [], dropped: 0, unsubscribe: undefined };\n\t\tthis.cache.set(key, entry);\n\t\tthis._enforceCacheCap(key);\n\t\tentry.unsubscribe = this._subscribeToSession(key, entry);\n\t\treturn entry;\n\t}\n\n\tprivate _enforceCacheCap(protectedKey?: string): void {\n\t\twhile (this.cache.size > this.cap) {\n\t\t\tlet oldestKey: string | undefined;\n\t\t\tlet oldest: CacheEntry | undefined;\n\t\t\tfor (const [key, entry] of this.cache) {\n\t\t\t\tif (key === protectedKey) continue;\n\t\t\t\tif (entry.busy) continue;\n\t\t\t\toldestKey = key;\n\t\t\t\toldest = entry;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!oldest || !oldestKey) {\n\t\t\t\t// Every cached session is busy (or is the protected new entry);\n\t\t\t\t// grow the cap temporarily rather than killing an in-flight turn.\n\t\t\t\tthis.cap = this.cache.size;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toldest.unsubscribe?.();\n\t\t\tthis.cache.delete(oldestKey);\n\t\t\toldest.session.dispose?.();\n\t\t\tconst evictedSessionId = oldest.session.sessionManager?.getSessionId();\n\t\t\tif (evictedSessionId) deletePermissionContext(evictedSessionId);\n\t\t}\n\t}\n\n\tprivate _subscribeToSession(key: string, entry: CacheEntry): () => void {\n\t\treturn entry.session.subscribe((event) => this._handleSessionEvent(key, event));\n\t}\n\n\tprivate _handleSessionEvent(key: string, event: AgentSessionEvent): void {\n\t\tif (event.type === \"message_start\" && event.message?.role === \"user\") {\n\t\t\tthis.redoStack.delete(key);\n\t\t}\n\t}\n}\n\nfunction extractUserText(message: AgentMessage): string {\n\tlet text = \"\";\n\tif (\"content\" in message && Array.isArray(message.content)) {\n\t\tfor (const block of message.content) {\n\t\t\tif (\n\t\t\t\tblock &&\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\"\n\t\t\t) {\n\t\t\t\ttext += block.text;\n\t\t\t}\n\t\t}\n\t}\n\treturn text;\n}\n"]}
|