@surfishs/dsh-prompt-enhance 0.0.9 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -126,25 +126,18 @@ function resolveReasoningEffort(value) {
126
126
  function resolveConfig(config) {
127
127
  if (config === null || typeof config !== "object") throw new Error("dsh-prompt-enhance: configuration is required");
128
128
  if (typeof config.enabled !== "boolean") throw new Error("dsh-prompt-enhance: enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
129
- const hasProvider = config.provider !== void 0 && config.provider !== "";
130
- const hasModel = config.model !== void 0 && config.model !== "";
131
- if (hasProvider !== hasModel) {
132
- throw new Error("dsh-prompt-enhance: provider \u4E0E model \u5FC5\u987B\u6210\u5BF9\u586B\u5199\uFF08\u8981\u4E48\u90FD\u586B\uFF0C\u8981\u4E48\u90FD\u7559\u7A7A\u4EE5\u8DDF\u968F\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B\uFF09");
133
- }
134
- const provider = hasProvider ? (config.provider ?? "").trim() : config.provider;
135
- const model = hasModel ? (config.model ?? "").trim() : config.model;
136
- if (hasProvider && provider === "" || hasModel && model === "") {
137
- throw new Error("dsh-prompt-enhance: provider/model \u8986\u76D6\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");
138
- }
139
- const temperature = config.temperature;
140
- if (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < TEMPERATURE.min || temperature > TEMPERATURE.max) {
141
- throw new Error(`dsh-prompt-enhance: temperature \u5FC5\u987B\u662F ${TEMPERATURE.min}\u2013${TEMPERATURE.max} \u4E4B\u95F4\u7684\u6709\u9650\u6570\u5B57`);
142
- }
143
129
  const pairOrUndefined = (value) => {
144
- if (value === void 0) return void 0;
130
+ if (typeof value !== "string") return void 0;
145
131
  const trimmed = value.trim();
146
132
  return trimmed === "" ? void 0 : trimmed;
147
133
  };
134
+ const provider = pairOrUndefined(config.provider);
135
+ const model = pairOrUndefined(config.model);
136
+ const override = provider !== void 0 && model !== void 0 ? { provider, model } : {};
137
+ const temperature = config.temperature;
138
+ if (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < TEMPERATURE.min || temperature > TEMPERATURE.max) {
139
+ throw new Error(`dsh-prompt-enhance: temperature \u5FC5\u987B\u662F ${TEMPERATURE.min}\u2013${TEMPERATURE.max} \u4E4B\u95F4\u7684\u6709\u9650\u6570\u5B57`);
140
+ }
148
141
  const intInRange = (value, name2, range) => {
149
142
  if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
150
143
  throw new Error(`dsh-prompt-enhance: ${name2} \u5FC5\u987B\u662F ${range.min}\u2013${range.max} \u4E4B\u95F4\u7684\u6574\u6570`);
@@ -153,8 +146,8 @@ function resolveConfig(config) {
153
146
  };
154
147
  return {
155
148
  enabled: config.enabled,
156
- provider: pairOrUndefined(provider),
157
- model: pairOrUndefined(model),
149
+ provider: override.provider,
150
+ model: override.model,
158
151
  temperature,
159
152
  // Ids are adapter-owned, so the stored string is kept as-is; a blank or
160
153
  // absent value degrades to the cheapest shipped default. An id the route
@@ -190,6 +183,69 @@ ${custom}` : custom;
190
183
  ${INVARIANT_CONTRACT}`;
191
184
  }
192
185
 
186
+ // src/admission.ts
187
+ var FAILURE_STREAK_LIMIT = 3;
188
+ var FAILURE_COOLDOWN_MS = 3e4;
189
+ var NON_BREAKER_CODES = /* @__PURE__ */ new Set(["unconfigured", "effort-unsupported"]);
190
+ function breakerOutcome(aborted, code) {
191
+ if (aborted) return "aborted";
192
+ return NON_BREAKER_CODES.has(code) ? "neutral" : "failure";
193
+ }
194
+ var AdmissionGate = class {
195
+ stamps = [];
196
+ active = 0;
197
+ failures = 0;
198
+ cooldownUntil = 0;
199
+ /**
200
+ * Ask for a slot.
201
+ * @param now - epoch millis of the admission attempt.
202
+ * @param limits - the live caps.
203
+ * @returns the decision; a refusal carries the wire error, plus the
204
+ * advertised wait when the gate can predict one.
205
+ */
206
+ admit(now, limits) {
207
+ if (now < this.cooldownUntil) {
208
+ const retryAfterSeconds = Math.max(1, Math.ceil((this.cooldownUntil - now) / 1e3));
209
+ return { ok: false, error: { code: "cooldown", params: { retryAfterSeconds, failures: FAILURE_STREAK_LIMIT } }, retryAfterSeconds };
210
+ }
211
+ const cut = now - 6e4;
212
+ let validFrom = 0;
213
+ while (validFrom < this.stamps.length && (this.stamps[validFrom] ?? cut) < cut) validFrom++;
214
+ if (validFrom > 0) this.stamps.splice(0, validFrom);
215
+ if (this.stamps.length >= limits.rateLimitPerMinute) {
216
+ const oldest = this.stamps[0] ?? now;
217
+ const retryAfterSeconds = Math.max(1, Math.ceil((6e4 - (now - oldest)) / 1e3));
218
+ return { ok: false, error: { code: "rate-limit", params: { limit: limits.rateLimitPerMinute, retryAfterSeconds } }, retryAfterSeconds };
219
+ }
220
+ if (this.active >= limits.maxConcurrent) {
221
+ return { ok: false, error: { code: "concurrency-limit", params: { max: limits.maxConcurrent } } };
222
+ }
223
+ this.active += 1;
224
+ return { ok: true };
225
+ }
226
+ /**
227
+ * Release the slot one admitted call held and record how it ended.
228
+ * @param outcome - success, failure, or neither (a cancellation, or a neutral
229
+ * failure that is not the route's fault).
230
+ * @param now - epoch millis when the call settled.
231
+ */
232
+ settle(outcome, now) {
233
+ if (this.active > 0) this.active -= 1;
234
+ if (outcome === "success") {
235
+ this.stamps.push(now);
236
+ this.failures = 0;
237
+ return;
238
+ }
239
+ if (outcome === "failure") {
240
+ this.failures += 1;
241
+ if (this.failures >= FAILURE_STREAK_LIMIT) {
242
+ this.cooldownUntil = now + FAILURE_COOLDOWN_MS;
243
+ this.failures = 0;
244
+ }
245
+ }
246
+ }
247
+ };
248
+
193
249
  // src/settings-source.ts
194
250
  function rowsOf(value) {
195
251
  return Array.isArray(value) ? value.filter((row) => row !== null && typeof row === "object") : [];
@@ -427,26 +483,32 @@ function formatInputCheckZh(check) {
427
483
  return `\u5185\u5BB9\u5171 ${check.count} \u4E2A\u5B57\u7B26\uFF0C\u8D85\u8FC7 ${check.max} \u4E2A\u5B57\u7B26\u4E0A\u9650\uFF08\u6309 Unicode \u5B57\u7B26\u6570\u7EDF\u8BA1\uFF0C\u4E0D\u662F token \u6570\uFF09\u3002\u4E3A\u907F\u514D\u6539\u53D8\u539F\u610F\u4E0D\u4F1A\u81EA\u52A8\u622A\u65AD\uFF0C\u8BF7\u7CBE\u7B80\u540E\u518D\u8BD5\u3002`;
428
484
  }
429
485
 
430
- // src/enhancer.ts
431
- import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
432
-
433
486
  // src/shared/normalize.ts
434
487
  var EXCESS_BLANK_LINES = /\n{3,}/g;
488
+ var FENCE = "```";
435
489
  function normalizeOutput(raw) {
436
490
  let text = raw.trim();
437
491
  const fenceMarkCount = (text.match(/```/g) ?? []).length;
438
- if (text.startsWith("```") && /```[\s]*$/.test(text) && fenceMarkCount === 2) {
439
- if (text.includes("\n")) {
440
- text = text.slice(text.indexOf("\n") + 1).replace(/```[\s]*$/, "").trim();
441
- } else {
442
- text = text.slice(3, -3).trim();
443
- }
492
+ if (fenceMarkCount === 2 && /```[\s]*$/.test(text)) {
493
+ const open = text.indexOf(FENCE);
494
+ const close = text.indexOf(FENCE, open + FENCE.length);
495
+ const lead = text.slice(0, open).trim();
496
+ const afterFence = text.slice(open + FENCE.length, close);
497
+ const firstNewline = afterFence.indexOf("\n");
498
+ const body = (firstNewline === -1 ? afterFence : afterFence.slice(firstNewline + 1)).trim();
499
+ text = lead === "" ? body : `${lead}
500
+ ${body}`;
444
501
  }
445
502
  text = text.replace(EXCESS_BLANK_LINES, "\n\n");
446
503
  return text.trim();
447
504
  }
448
505
 
449
506
  // src/enhancer.ts
507
+ var llmRuntimePromise;
508
+ function loadLlmRuntime() {
509
+ llmRuntimePromise ??= import("@deepseek-ai/dsh-llm");
510
+ return llmRuntimePromise;
511
+ }
450
512
  var EnhanceFailure = class extends Error {
451
513
  constructor(detail) {
452
514
  super(detail.message ?? detail.code);
@@ -486,8 +548,16 @@ async function enhanceText(llm, options) {
486
548
  };
487
549
  try {
488
550
  signal.throwIfAborted();
551
+ let runtime;
552
+ try {
553
+ runtime = await loadLlmRuntime();
554
+ } catch (error) {
555
+ return fail({ code: "internal", message: `harness LLM module unavailable: ${describe(error)}` });
556
+ }
557
+ const createMessage = runtime.createUserMessage;
558
+ const BlockAssemblerClass = runtime.BlockAssembler;
489
559
  const messages = [
490
- createUserMessage({
560
+ createMessage({
491
561
  content: [{ type: "text", text: frameUserPrompt(options.text, options.context) }],
492
562
  source: { kind: "dsh-prompt-enhance" }
493
563
  })
@@ -507,7 +577,7 @@ async function enhanceText(llm, options) {
507
577
  ...effort === "inherit" ? {} : { reasoningEffort: effort },
508
578
  ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
509
579
  };
510
- const assembler = new BlockAssembler();
580
+ const assembler = new BlockAssemblerClass();
511
581
  const iterator = llm.stream(generate)[Symbol.asyncIterator]();
512
582
  let onAbort;
513
583
  const aborted = new Promise((_, reject) => {
@@ -529,12 +599,12 @@ async function enhanceText(llm, options) {
529
599
  break;
530
600
  }
531
601
  assembler.push(next.value);
532
- if (next.value.type === "text-delta" && options.onDelta !== void 0) {
533
- try {
534
- void Promise.resolve(options.onDelta(next.value.text)).catch(() => {
535
- });
536
- } catch {
537
- }
602
+ const onDelta = options.onDelta;
603
+ if (next.value.type === "text-delta" && onDelta !== void 0) {
604
+ const delta = next.value.text;
605
+ const sink = Promise.resolve().then(() => onDelta(delta)).catch(() => {
606
+ });
607
+ await Promise.race([sink, aborted]);
538
608
  }
539
609
  }
540
610
  } finally {
@@ -822,16 +892,20 @@ function buildConversationContext(messages, options, draft) {
822
892
  }
823
893
 
824
894
  // src/reasoning-cache.ts
825
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
895
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
826
896
  import { homedir } from "node:os";
827
897
  import { dirname, join } from "node:path";
828
898
  var CACHE_VERSION = 1;
899
+ var CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
829
900
  function harnessHome() {
830
901
  const configured = (process.env.DSH_HOME ?? "").trim();
831
902
  return configured === "" ? join(homedir(), ".dsh") : configured;
832
903
  }
833
- function cacheFilePath() {
834
- return join(harnessHome(), "dsh-prompt-enhance", "reasoning-efforts.json");
904
+ function cacheDirectory() {
905
+ return join(harnessHome(), "dsh-prompt-enhance", "reasoning-efforts");
906
+ }
907
+ function cacheFilePath(provider, model) {
908
+ return join(cacheDirectory(), encodeURIComponent(provider), `${encodeURIComponent(model)}.json`);
835
909
  }
836
910
  function entryKey(provider, model) {
837
911
  return `${provider}/${model}`;
@@ -846,54 +920,70 @@ function effortOf(value) {
846
920
  ...typeof record.description === "string" && record.description !== "" ? { description: record.description } : {}
847
921
  };
848
922
  }
849
- async function readDocument() {
923
+ var memo = /* @__PURE__ */ new Map();
924
+ var memoHome;
925
+ function memoFor() {
926
+ const home = harnessHome();
927
+ if (memoHome !== home) {
928
+ memo.clear();
929
+ memoHome = home;
930
+ }
931
+ return memo;
932
+ }
933
+ async function dropExpired(path) {
850
934
  try {
851
- const raw = await readFile(cacheFilePath(), "utf8");
852
- const parsed = JSON.parse(raw);
853
- if (parsed === null || typeof parsed !== "object") return { version: CACHE_VERSION, entries: {} };
854
- const record = parsed;
855
- if (record.version !== CACHE_VERSION || record.entries === null || typeof record.entries !== "object") {
856
- return { version: CACHE_VERSION, entries: {} };
857
- }
858
- return { version: CACHE_VERSION, entries: record.entries };
935
+ await rm(path, { force: true });
859
936
  } catch {
860
- return { version: CACHE_VERSION, entries: {} };
861
937
  }
862
938
  }
863
- async function writeDocument(document) {
864
- const path = cacheFilePath();
939
+ async function readEntryFile(provider, model) {
940
+ const path = cacheFilePath(provider, model);
865
941
  try {
866
- await mkdir(dirname(path), { recursive: true });
867
- const temporary = `${path}.${process.pid}.tmp`;
868
- await writeFile(temporary, JSON.stringify(document), "utf8");
869
- await rename(temporary, path);
942
+ const entry = JSON.parse(await readFile(path, "utf8"));
943
+ if (entry === null || typeof entry !== "object") return void 0;
944
+ if (entry.version !== CACHE_VERSION || entry.provider !== provider || entry.model !== model) return void 0;
945
+ if (typeof entry.savedAt !== "number" || Date.now() - entry.savedAt > CACHE_TTL_MS) {
946
+ await dropExpired(path);
947
+ return void 0;
948
+ }
949
+ if (entry.noEfforts === true) return { efforts: [], noEfforts: true };
950
+ if (!Array.isArray(entry.efforts) || entry.efforts.length === 0) return void 0;
951
+ const efforts = entry.efforts.map(effortOf).filter((effort) => effort !== void 0);
952
+ if (efforts.length !== entry.efforts.length) return void 0;
953
+ return {
954
+ efforts,
955
+ ...typeof entry.defaultEffort === "string" && entry.defaultEffort !== "" ? { defaultEffort: entry.defaultEffort } : {}
956
+ };
870
957
  } catch {
958
+ return void 0;
871
959
  }
872
960
  }
873
961
  async function readCachedCapabilities(provider, model) {
874
- const document = await readDocument();
875
- const entry = document.entries[entryKey(provider, model)];
876
- if (entry === void 0 || entry.provider !== provider || entry.model !== model) return void 0;
877
- if (entry.noEfforts === true) return { efforts: [], noEfforts: true };
878
- if (!Array.isArray(entry.efforts) || entry.efforts.length === 0) return void 0;
879
- const efforts = entry.efforts.map(effortOf).filter((effort) => effort !== void 0);
880
- if (efforts.length !== entry.efforts.length) return void 0;
881
- return {
882
- efforts,
883
- ...typeof entry.defaultEffort === "string" && entry.defaultEffort !== "" ? { defaultEffort: entry.defaultEffort } : {}
884
- };
962
+ const known = memoFor().get(entryKey(provider, model));
963
+ if (known !== void 0) return known;
964
+ const answer = await readEntryFile(provider, model);
965
+ if (answer !== void 0) memoFor().set(entryKey(provider, model), answer);
966
+ return answer;
885
967
  }
886
968
  async function writeCachedCapabilities(provider, model, efforts, defaultEffort, noEfforts = false) {
887
- const document = await readDocument();
888
- document.entries[entryKey(provider, model)] = {
889
- provider,
890
- model,
891
- efforts,
892
- ...defaultEffort === void 0 ? {} : { defaultEffort },
893
- ...noEfforts ? { noEfforts: true } : {},
894
- savedAt: Date.now()
895
- };
896
- await writeDocument(document);
969
+ const path = cacheFilePath(provider, model);
970
+ try {
971
+ await mkdir(dirname(path), { recursive: true });
972
+ const entry = {
973
+ version: CACHE_VERSION,
974
+ provider,
975
+ model,
976
+ efforts,
977
+ ...defaultEffort === void 0 ? {} : { defaultEffort },
978
+ ...noEfforts ? { noEfforts: true } : {},
979
+ savedAt: Date.now()
980
+ };
981
+ const temporary = `${path}.${process.pid}.tmp`;
982
+ await writeFile(temporary, JSON.stringify(entry), "utf8");
983
+ await rename(temporary, path);
984
+ } catch {
985
+ }
986
+ memoFor().set(entryKey(provider, model), noEfforts ? { efforts: [], noEfforts: true } : { efforts, ...defaultEffort === void 0 ? {} : { defaultEffort } });
897
987
  }
898
988
 
899
989
  // src/orchestrate.ts
@@ -1092,13 +1182,21 @@ function isTrustedRequest(req) {
1092
1182
  }
1093
1183
 
1094
1184
  // src/http.ts
1185
+ var BodyTooLargeError = class extends Error {
1186
+ /** Stable discriminant for `instanceof`-free checks across realms. */
1187
+ code = "body-too-large";
1188
+ constructor() {
1189
+ super("body too large");
1190
+ this.name = "BodyTooLargeError";
1191
+ }
1192
+ };
1095
1193
  async function readBoundedJson(req, maxBytes) {
1096
1194
  const chunks = [];
1097
1195
  let size = 0;
1098
1196
  for await (const chunk of req) {
1099
1197
  const buffer = chunk;
1100
1198
  size += buffer.length;
1101
- if (size > maxBytes) throw new Error("body too large");
1199
+ if (size > maxBytes) throw new BodyTooLargeError();
1102
1200
  chunks.push(buffer);
1103
1201
  }
1104
1202
  return JSON.parse(Buffer.concat(chunks).toString("utf8"));
@@ -1351,8 +1449,6 @@ async function serveCatalog(ctx, req, res, pathname) {
1351
1449
 
1352
1450
  // src/enhance-routes.ts
1353
1451
  var bodyCapOf = (maxInputChars) => maxInputChars * 6 + 4096;
1354
- var FAILURE_STREAK_LIMIT = 3;
1355
- var FAILURE_COOLDOWN_MS = 3e4;
1356
1452
  async function serveEnhance(ctx, readConfig, gate, pathname, req, res, stream) {
1357
1453
  if (!isTrustedRequest(req)) {
1358
1454
  writeJson(res, 403, { ok: false, error: { code: "internal", message: "forbidden: loopback-only" } });
@@ -1393,7 +1489,8 @@ async function serveEnhance(ctx, readConfig, gate, pathname, req, res, stream) {
1393
1489
  try {
1394
1490
  body = await readBoundedJson(req, cap);
1395
1491
  } catch (error) {
1396
- const tooLarge = error instanceof Error && error.message === "body too large";
1492
+ const tooLarge = error instanceof BodyTooLargeError;
1493
+ if (tooLarge) res.setHeader("connection", "close");
1397
1494
  writeJson(res, tooLarge ? 413 : 422, {
1398
1495
  ok: false,
1399
1496
  error: { code: "rejected", message: tooLarge ? "\u8BF7\u6C42\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\u3002" : "\u8BF7\u6C42\u4F53\u4E0D\u662F\u6709\u6548\u7684 JSON\u3002" }
@@ -1414,44 +1511,18 @@ async function serveEnhance(ctx, readConfig, gate, pathname, req, res, stream) {
1414
1511
  });
1415
1512
  return;
1416
1513
  }
1417
- const now = Date.now();
1418
- if (now < gate.cooldownUntil) {
1419
- const retryAfterSeconds = Math.max(1, Math.ceil((gate.cooldownUntil - now) / 1e3));
1420
- res.setHeader("Retry-After", String(retryAfterSeconds));
1421
- writeJson(res, 429, {
1422
- ok: false,
1423
- error: { code: "cooldown", params: { retryAfterSeconds, failures: FAILURE_STREAK_LIMIT } }
1424
- });
1425
- return;
1426
- }
1427
- const stamps = gate.stamps;
1428
- const cut = now - 6e4;
1429
- let validFrom = 0;
1430
- while (validFrom < stamps.length && (stamps[validFrom] ?? cut) < cut) validFrom++;
1431
- if (validFrom > 0) stamps.splice(0, validFrom);
1432
- if (stamps.length >= config.rateLimitPerMinute) {
1433
- const oldest = stamps[0] ?? now;
1434
- const retryAfterSeconds = Math.max(1, Math.ceil((6e4 - (now - oldest)) / 1e3));
1435
- res.setHeader("Retry-After", String(retryAfterSeconds));
1436
- writeJson(res, 429, {
1437
- ok: false,
1438
- error: { code: "rate-limit", params: { limit: config.rateLimitPerMinute, retryAfterSeconds } }
1439
- });
1440
- return;
1441
- }
1442
- if (gate.active >= config.maxConcurrent) {
1443
- writeJson(res, 429, {
1444
- ok: false,
1445
- error: { code: "concurrency-limit", params: { max: config.maxConcurrent } }
1446
- });
1514
+ const decision = gate.admit(Date.now(), { rateLimitPerMinute: config.rateLimitPerMinute, maxConcurrent: config.maxConcurrent });
1515
+ if (!decision.ok) {
1516
+ if (decision.retryAfterSeconds !== void 0) res.setHeader("Retry-After", String(decision.retryAfterSeconds));
1517
+ writeJson(res, 429, { ok: false, error: decision.error });
1447
1518
  return;
1448
1519
  }
1449
- gate.active += 1;
1450
1520
  const callerAbort = new AbortController();
1451
1521
  const onConnectionClosed = () => {
1452
1522
  if (!res.writableEnded) callerAbort.abort();
1453
1523
  };
1454
1524
  res.on("close", onConnectionClosed);
1525
+ let outcome = "aborted";
1455
1526
  try {
1456
1527
  const runOptions = {
1457
1528
  text: record.text,
@@ -1494,17 +1565,10 @@ data: ${JSON.stringify({ type: "done", value })}
1494
1565
  const value = await runEnhance(ctx, config, runOptions);
1495
1566
  writeJson(res, 200, { ok: true, value });
1496
1567
  }
1497
- stamps.push(Date.now());
1498
- gate.failures = 0;
1568
+ outcome = "success";
1499
1569
  } catch (error) {
1500
- if (!callerAbort.signal.aborted) {
1501
- gate.failures += 1;
1502
- if (gate.failures >= FAILURE_STREAK_LIMIT) {
1503
- gate.cooldownUntil = Date.now() + FAILURE_COOLDOWN_MS;
1504
- gate.failures = 0;
1505
- }
1506
- }
1507
1570
  const wire = toEnhanceError(error);
1571
+ outcome = breakerOutcome(callerAbort.signal.aborted, wire.code);
1508
1572
  if (stream && res.headersSent) {
1509
1573
  if (!res.writableEnded) {
1510
1574
  try {
@@ -1521,11 +1585,11 @@ data: ${JSON.stringify({ type: "error", error: wire })}
1521
1585
  }
1522
1586
  } finally {
1523
1587
  res.off("close", onConnectionClosed);
1524
- gate.active -= 1;
1588
+ gate.settle(outcome, Date.now());
1525
1589
  }
1526
1590
  }
1527
1591
  var mounts = /* @__PURE__ */ new WeakMap();
1528
- function registerEnhanceRoute(ctx, readConfig) {
1592
+ function registerEnhanceRoute(ctx, readConfig, gate) {
1529
1593
  ctx.inject(["webServer"], (routeCtx) => {
1530
1594
  const webserver = routeCtx.get("webServer");
1531
1595
  if (webserver === void 0) return;
@@ -1538,7 +1602,6 @@ function registerEnhanceRoute(ctx, readConfig) {
1538
1602
  }
1539
1603
  mounts.delete(ctx);
1540
1604
  }
1541
- const gate = { stamps: [], active: 0, failures: 0, cooldownUntil: 0 };
1542
1605
  routeCtx.effect(() => {
1543
1606
  const dispose = webserver.register({
1544
1607
  kind: "prefix",
@@ -1567,7 +1630,7 @@ function registerEnhanceRoute(ctx, readConfig) {
1567
1630
  }
1568
1631
 
1569
1632
  // src/enhance-command.ts
1570
- function registerEnhanceCommand(ctx, readConfig) {
1633
+ function registerEnhanceCommand(ctx, readConfig, gate) {
1571
1634
  const commands = ctx.get("commands");
1572
1635
  if (commands === void 0) return;
1573
1636
  const definition = {
@@ -1589,13 +1652,26 @@ function registerEnhanceCommand(ctx, readConfig) {
1589
1652
  if (!check.ok) {
1590
1653
  return { kind: "error", text: formatInputCheckZh(check) };
1591
1654
  }
1592
- const value = await runEnhance(ctx, config, {
1593
- text: raw,
1594
- sessionRoute: sessionRouteOf(ctx, invocation.agent.session.id),
1595
- signal: invocation.signal,
1596
- sessionId: invocation.agent.session.id
1597
- });
1598
- return { kind: "success", text: value.text };
1655
+ const decision = gate.admit(Date.now(), { rateLimitPerMinute: config.rateLimitPerMinute, maxConcurrent: config.maxConcurrent });
1656
+ if (!decision.ok) {
1657
+ return { kind: "error", text: formatEnhanceError(decision.error) };
1658
+ }
1659
+ let outcome = "aborted";
1660
+ try {
1661
+ const value = await runEnhance(ctx, config, {
1662
+ text: raw,
1663
+ sessionRoute: sessionRouteOf(ctx, invocation.agent.session.id),
1664
+ signal: invocation.signal,
1665
+ sessionId: invocation.agent.session.id
1666
+ });
1667
+ outcome = "success";
1668
+ return { kind: "success", text: value.text };
1669
+ } catch (error) {
1670
+ outcome = breakerOutcome(invocation.signal.aborted, toEnhanceError(error).code);
1671
+ throw error;
1672
+ } finally {
1673
+ gate.settle(outcome, Date.now());
1674
+ }
1599
1675
  } catch (error) {
1600
1676
  return { kind: "error", text: formatEnhanceError(toEnhanceError(error)) };
1601
1677
  }
@@ -1627,8 +1703,9 @@ function apply(ctx, config = { ...DEFAULT_CONFIG }) {
1627
1703
  }
1628
1704
  });
1629
1705
  const readConfig = () => resolveConfig(source.read());
1630
- registerEnhanceRoute(ctx, readConfig);
1631
- registerEnhanceCommand(ctx, readConfig);
1706
+ const gate = new AdmissionGate();
1707
+ registerEnhanceRoute(ctx, readConfig, gate);
1708
+ registerEnhanceCommand(ctx, readConfig, gate);
1632
1709
  }
1633
1710
  export {
1634
1711
  Config,