@tea-agent/loop-agent 0.52.0-next.4 → 0.52.0-next.6

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +7 -1
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/pi-sdk-executor.js +3 -3
  4. package/dist/shared/pi-context-pressure/checkpoint.js +94 -24
  5. package/dist/shared/pi-context-pressure/compaction-policy.js +104 -11
  6. package/dist/shared/pi-context-pressure/extension.js +25 -8
  7. package/dist/shared/pi-context-pressure/telemetry.js +5 -0
  8. package/dist/worker/console/chat/chat-event-projection.js +4 -0
  9. package/dist/worker/console/chat/pi-runtime.js +109 -14
  10. package/dist/worker/console/pi-compaction-settings.js +182 -0
  11. package/dist/worker/console/server.js +59 -1
  12. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-CM5ocMUs.js → abnfDiagram-N423BO3Z-BiFM8_eW.js} +1 -1
  13. package/dist/worker/console/static/assets/{arc-CDapwdTN.js → arc-Ci4EnVJs.js} +1 -1
  14. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-Ogy4GOqS.js → architectureDiagram-T3A2C74G-C9Hnq824.js} +1 -1
  15. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DsiaOIgU.js → blockDiagram-VBNYF7ZC-Erza3vCj.js} +1 -1
  16. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B84hhgSe.js → c4Diagram-5PPSVZJV-DhiEJ_zn.js} +1 -1
  17. package/dist/worker/console/static/assets/channel-o866H8CG.js +1 -0
  18. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-SPqOhMla.js → chunk-2GRJ4B5K-Jwoe5Hha.js} +1 -1
  19. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BL0Q4ZV3.js → chunk-2Q5K7J3B-B2p-ASWD.js} +1 -1
  20. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CJpOcFAh.js → chunk-5RXB4S5H-CinVrkm9.js} +1 -1
  21. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DQC6vqVW.js → chunk-5VM5RSS4-DPEKo8K0.js} +1 -1
  22. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D4dq_L0l.js → chunk-6Q2QTUOP-BWkVY9W5.js} +1 -1
  23. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DVNZmiVo.js → chunk-GF5L2VYU-CMFm2SFJ.js} +1 -1
  24. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-B1yOfAhr.js → chunk-JWPE2WC7-Du_X-MSA.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BEPc1N6N.js → chunk-KBJHAD2P-cTlf6fnC.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-Da_-gMwh.js → chunk-RYQCIY6F-C5ve9fxF.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-C75eW9DT.js → chunk-XXDRQBXY-CRxS8vXT.js} +1 -1
  28. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-iDhRZSeN.js +1 -0
  29. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-iDhRZSeN.js +1 -0
  30. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-C4Gn7eYB.js → cose-bilkent-JH36ORCC-BEnyQAzp.js} +1 -1
  31. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55--CBwVt18.js → cynefinDiagram-MW4NZA55-DvPiK5od.js} +1 -1
  32. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B8dBxboB.js → dagre-VZM6K2ZE-DxigWx8E.js} +1 -1
  33. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-hKtlE0w-.js → diagram-7IWD3JNH-D50wvAbw.js} +1 -1
  34. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BKirx0F3.js → diagram-B4RE2ZJO-B6PmMJzk.js} +1 -1
  35. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-bkx-oUrD.js → diagram-LBJQPF4R-BbT1ZLia.js} +1 -1
  36. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D7sFtSjr.js → diagram-Q27KOJAE-CizMPXm7.js} +1 -1
  37. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BPjzGBV_.js → diagram-UB23O5K3-DjxNSFmF.js} +1 -1
  38. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-DODv-GbM.js → ebnfDiagram-BXEA7PRR-Bwg25Xpv.js} +1 -1
  39. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-DbfVp5uI.js → erDiagram-JOGREHBK-aHHIkVbd.js} +1 -1
  40. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-BHWWThbx.js → flowDiagram-UKHOOZJN-CBQFor5-.js} +1 -1
  41. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-SWY_8oU3.js → ganttDiagram-PKOTCBZU-Bhv0b_Ay.js} +1 -1
  42. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-CJdhHY-i.js → gitGraphDiagram-DS77QQ5N-CcTjAWTv.js} +1 -1
  43. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CLC4mTWX.js → infoDiagram-6WML65LV-Bwt6_MRI.js} +1 -1
  44. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-CiJDWOmX.js → ishikawaDiagram-WSZJBQD7-JcDN-oJ0.js} +1 -1
  45. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-eIQfMD0f.js → journeyDiagram-NVQOT4AX-C7YA3mW8.js} +1 -1
  46. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-3d6r1cG7.js → kanban-definition-27J2QSJJ-CfgSiedW.js} +1 -1
  47. package/dist/worker/console/static/assets/{linear-BjbmxxDk.js → linear-Dy5YZwCe.js} +1 -1
  48. package/dist/worker/console/static/assets/{main-B9ZnQejR.css → main-C537vZah.css} +1 -1
  49. package/dist/worker/console/static/assets/{main-D4knTr0R.js → main-D39kbkZI.js} +132 -131
  50. package/dist/worker/console/static/assets/{mermaid.core-CD2GFYrr.js → mermaid.core-CWATftfi.js} +4 -4
  51. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-D0ORXhx-.js → mindmap-definition-FAOFIHXS-DXcCCbEa.js} +1 -1
  52. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BqNbcp7_.js → pegDiagram-VL7TDLO6-CoS0ZgLy.js} +1 -1
  53. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-CGO0Y13N.js → pieDiagram-7S7Q4E2Y-DotRKEI5.js} +1 -1
  54. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-vH4fdvTV.js → quadrantDiagram-CIZ2JOQS-DMdkO7Rz.js} +1 -1
  55. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-B_sbmiFS.js → railroadDiagram-AXF67PYL-rj-Qc0fo.js} +1 -1
  56. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-DbHtPigL.js → requirementDiagram-LRYGKXZP-DDBta62g.js} +1 -1
  57. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BcqNS0Ko.js → sankeyDiagram-W5VNT64P-DWqZxqI8.js} +1 -1
  58. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-5Zf3xJfg.js → sequenceDiagram-SI44F4Z6-C0fVeYqG.js} +1 -1
  59. package/dist/worker/console/static/assets/{sheet-workbook-Bvq6WFll.js → sheet-workbook-CNv6AzfM.js} +1 -1
  60. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BoO7GXeG.js → sizeCapture-X5ZJPWSS-DOvvHUh-.js} +1 -1
  61. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-3suojNXT.js → stateDiagram-OKZ733FA-DgqVm117.js} +1 -1
  62. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-8zVknfpQ.js +1 -0
  63. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-B5CyFSLq.js → swimlanes-SLNWSIFB-C6H8hfVq.js} +2 -2
  64. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BTTCojly.js +8 -0
  65. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BuZ_HcXz.js → timeline-definition-Z64GVDOM-DyUP-YKn.js} +1 -1
  66. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-CJ_IDS7Q.js → vennDiagram-T6HMQDX7-CwY3bnAh.js} +1 -1
  67. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BpKLb-Su.js → wardleyDiagram-T6FBY63Y-DE1T6Hko.js} +1 -1
  68. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Mdo6gaIk.js → xychartDiagram-ELKLHX3M-C0h8BPyy.js} +1 -1
  69. package/dist/worker/console/static/index.html +2 -2
  70. package/dist/worker/console/static-src/operator-chat/changed-file-diff.js +15 -0
  71. package/dist/worker/console/static-src/operator-chat/compaction-message.js +4 -0
  72. package/package.json +7 -7
  73. package/scripts/patch-pi-sdk-windows-hide.mjs +3 -3
  74. package/dist/worker/console/static/assets/channel-BCVzSVXD.js +0 -1
  75. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BRlRsJR0.js +0 -1
  76. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BRlRsJR0.js +0 -1
  77. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Bq6cg1c9.js +0 -1
  78. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-VvJzDuB_.js +0 -8
@@ -45,6 +45,7 @@ import { createWorkflowRecorder } from "./workflow/record.js";
45
45
  import { buildWorkflowJobTools } from "./workflow/job-tools.js";
46
46
  import { assertConsoleResourcePolicy, withConsoleResourcePolicy } from "./subagents/resource-policy.js";
47
47
  import { bindSessionExtensions, createConsoleToolPolicyExtension, disposeSessionExtensions, setSessionToolPolicy } from "./pi-runtime/extension-bindings.js";
48
+ import { createPiCompactionSettings, resolveCompactionSettings, } from "../pi-compaction-settings.js";
48
49
  import { createOperatorChatResourceLoader, } from "./resource-loader.js";
49
50
  import { applySkillAutoInvocationPreferences, loadResourcePreferences, } from "./resource-preferences-store.js";
50
51
  import { buildPiModeLoopIsolationOptions } from "./pi-mode-loop-isolation.js";
@@ -478,6 +479,27 @@ export class PiSessionInitFailedError extends Error {
478
479
  this.name = "PiSessionInitFailedError";
479
480
  }
480
481
  }
482
+ /**
483
+ * Merge saved user preferences into a parsed policy.
484
+ *
485
+ * Only the two deployment-shaped knobs are overridable here; everything else
486
+ * stays with the environment parser so there is a single source for each
487
+ * decision. The environment still wins inside `resolveCompactionSettings`.
488
+ */
489
+ function withUserCompactionSettings(policy, settings) {
490
+ if (!settings)
491
+ return policy;
492
+ const resolved = resolveCompactionSettings({ saved: settings });
493
+ return {
494
+ ...policy,
495
+ ...(resolved.gatewayInputLimitTokens === undefined
496
+ ? {}
497
+ : { gatewayInputLimitTokens: resolved.gatewayInputLimitTokens }),
498
+ ...(resolved.keepRecentTokens === undefined
499
+ ? {}
500
+ : { keepRecentTokens: resolved.keepRecentTokens }),
501
+ };
502
+ }
481
503
  async function readModelConfigFileVersion(filePath) {
482
504
  try {
483
505
  const value = await stat(filePath, { bigint: true });
@@ -867,20 +889,68 @@ export class ConsolePiRuntime {
867
889
  ...(pruneSettings.enabled && policy.mode !== "off" ? { prune: pruneSettings.config } : {}),
868
890
  });
869
891
  }
870
- applySessionRecoveryOverrides(sessionId, services, session) {
892
+ /**
893
+ * The conversation window Pi itself reports, and the window Pi will compute
894
+ * its threshold against.
895
+ *
896
+ * Pi derives its own compaction threshold from the model definition, so the
897
+ * reserve handed to it must be expressed against that same number. A gateway
898
+ * limit only narrows the Console's trigger basis; feeding it to Pi as the
899
+ * window would make Pi subtract the limit twice and never fire.
900
+ */
901
+ piDeclaredWindow(session, reportedWindow) {
902
+ const configured = session?.model?.contextWindow;
903
+ if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
904
+ return configured;
905
+ }
906
+ if (typeof reportedWindow === "number" && reportedWindow > 0) {
907
+ return reportedWindow;
908
+ }
909
+ return undefined;
910
+ }
911
+ applySessionRecoveryOverrides(sessionId, services, session, userSettings) {
871
912
  applyProcessRetryOverride(services?.settingsManager);
872
913
  const manager = services?.settingsManager;
873
- const window = session?.getSessionStats?.()?.contextUsage?.contextWindow;
914
+ const reportedWindow = session?.getSessionStats?.()?.contextUsage?.contextWindow;
915
+ const declaredWindow = this.piDeclaredWindow(session, reportedWindow);
874
916
  applyProcessCompactionOverride(manager, {
875
- policy: parseCompactionPolicy(),
876
- ...(typeof window === "number" ? { contextWindow: window } : {}),
877
- // Console should allow an explicit compact as soon as there is a
878
- // previous turn. Pi's 20k default is a useful retention policy for
879
- // the TUI, but becomes a hard "session too small" gate here.
880
- keepRecentTokens: 0,
917
+ // User-scoped gateway limit / retained tail, when the operator saved
918
+ // one in 模型与认证. Environment variables still win inside
919
+ // resolveCompactionSettings.
920
+ policy: withUserCompactionSettings(parseCompactionPolicy(), userSettings),
921
+ ...(typeof declaredWindow === "number"
922
+ ? {
923
+ contextWindow: declaredWindow,
924
+ declaredContextWindow: declaredWindow,
925
+ }
926
+ : {}),
927
+ // NOTE: no explicit keepRecentTokens here on purpose. Forcing 0 made
928
+ // `messagesToSummarize` span the whole branch, so the summary request
929
+ // re-sent the history the gateway had just rejected and failed too.
930
+ // The policy derives a bounded tail from the trigger line (see
931
+ // resolveKeepRecentTokens); saved settings or
932
+ // HARNESS_COMPACTION_KEEP_RECENT_TOKENS override that split.
881
933
  });
882
934
  void sessionId;
883
935
  }
936
+ /**
937
+ * Read the saved compaction preferences once per session start.
938
+ *
939
+ * A missing or unreadable file must not break session creation; the policy
940
+ * falls back to environment variables and then to the declared window.
941
+ */
942
+ async loadUserCompactionSettings() {
943
+ const appDataRoot = this.options.appDataRoot;
944
+ if (!appDataRoot)
945
+ return undefined;
946
+ try {
947
+ const store = await createPiCompactionSettings(appDataRoot);
948
+ return await store.current();
949
+ }
950
+ catch {
951
+ return undefined;
952
+ }
953
+ }
884
954
  /**
885
955
  * Pick the context window to gate proactive compaction on.
886
956
  *
@@ -907,18 +977,25 @@ export class ConsolePiRuntime {
907
977
  return DEFAULT_CONTEXT_WINDOW;
908
978
  }
909
979
  async runPrePromptCompaction(sessionId, session, promptText, imageCount, onEvent, signal) {
910
- const policy = parseCompactionPolicy();
911
980
  if (signal?.aborted)
912
981
  return;
913
- if (policy.mode === "off")
982
+ const parsed = parseCompactionPolicy();
983
+ if (parsed.mode === "off")
914
984
  return;
985
+ // The saved preferences must reach this check too: the operator sets the
986
+ // gateway limit here, and evaluating it only when writing Pi's settings
987
+ // left the pre-prompt gate on the declared window.
988
+ const policy = withUserCompactionSettings(parsed, await this.loadUserCompactionSettings());
915
989
  const controller = this.getCompactionController(sessionId);
916
990
  const stats = session.getSessionStats?.();
917
991
  const reportedWindow = stats?.contextUsage?.contextWindow;
918
992
  const tokens = stats?.contextUsage?.tokens;
919
993
  const window = this.resolveContextWindow(session, reportedWindow);
994
+ // Keep Pi's own threshold on the same line as this gate. The settings
995
+ // write is idempotent, so repeating it here costs nothing and guarantees
996
+ // the two thresholds agree even when the window changed mid-session.
920
997
  if (typeof window === "number" && window > 0) {
921
- this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session);
998
+ this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session, await this.loadUserCompactionSettings());
922
999
  }
923
1000
  const projection = projectPromptPressure({
924
1001
  currentContextTokens: tokens,
@@ -1347,7 +1424,7 @@ export class ConsolePiRuntime {
1347
1424
  return undefined;
1348
1425
  }
1349
1426
  this.pinSessionTools(init.sessionId, session);
1350
- this.applySessionRecoveryOverrides(init.sessionId, services, session);
1427
+ this.applySessionRecoveryOverrides(init.sessionId, services, session, await this.loadUserCompactionSettings());
1351
1428
  }
1352
1429
  catch (error) {
1353
1430
  abandon();
@@ -2348,8 +2425,9 @@ export class ConsolePiRuntime {
2348
2425
  if (this.disposedSessions.has(sessionId))
2349
2426
  return disposedResult();
2350
2427
  const services = this.serviceScopes.get(sessionId);
2351
- if (services)
2352
- this.applySessionRecoveryOverrides(sessionId, services, session);
2428
+ if (services) {
2429
+ this.applySessionRecoveryOverrides(sessionId, services, session, await this.loadUserCompactionSettings());
2430
+ }
2353
2431
  await this.refreshModelConfiguration(sessionId, "force");
2354
2432
  if (this.disposedSessions.has(sessionId))
2355
2433
  return disposedResult();
@@ -3235,6 +3313,23 @@ export class ConsolePiRuntime {
3235
3313
  ? activeCompaction?.compactionId ?? newCompactionId(sessionId)
3236
3314
  : undefined;
3237
3315
  const mapped = mapSdkEvent(sessionId, event.type === "tool_execution_start" ? { ...event, args: projectSkillReadArgs(event.toolName, event.args, currentSkills(), this.serviceScopes.get(sessionId)?.cwd ?? this.options.cwd) } : event, compactionId, Math.max(1, step));
3316
+ /*
3317
+ * Say WHY a compaction produced a local summary.
3318
+ *
3319
+ * The extension only takes over after the provider summary request
3320
+ * failed, so a completed compaction with the fallback armed means the
3321
+ * gateway refused twice: once for the original request and again for
3322
+ * the summary. Without this the message stream shows a compaction that
3323
+ * looks identical to a normal one, while the content is visibly worse.
3324
+ */
3325
+ if (mapped?.type === "compaction_end") {
3326
+ const controller = this.compactionControllers.get(sessionId);
3327
+ if (controller?.summaryRetryPending) {
3328
+ mapped.localFallback = true;
3329
+ mapped.localFallbackReason = "网关拒绝了摘要请求,已改用本地摘要";
3330
+ controller.summaryRetryPending = undefined;
3331
+ }
3332
+ }
3238
3333
  if (event.type === "compaction_end")
3239
3334
  activeCompaction = undefined;
3240
3335
  if (mapped?.type === "error") {
@@ -0,0 +1,182 @@
1
+ /**
2
+ * User-scoped compaction limits for the Console's Pi runtime.
3
+ *
4
+ * Stored outside any repo, beside the other cross-project preferences:
5
+ * `<appDataRoot>/settings/pi-compaction.json`.
6
+ *
7
+ * Why this exists: a self-hosted gateway can accept far less input than the
8
+ * model's declared `contextWindow`. When compaction is triggered from the
9
+ * declared window it never fires before the gateway rejects the request, so
10
+ * every session lands on the deterministic local checkpoint instead of a
11
+ * provider summary. The gateway limit is a property of the deployment, not of
12
+ * the project or the model, so it is a user preference rather than a manifest
13
+ * value or a hard-coded constant.
14
+ *
15
+ * Environment variables remain supported and take precedence, so an operator
16
+ * can override without touching saved settings (see `resolveCompactionSettings`).
17
+ */
18
+ import { readFile, rename, writeFile } from "node:fs/promises";
19
+ import path from "node:path";
20
+ import { ensureSecureDir } from "../../infrastructure/console/app-data.js";
21
+ export const PI_COMPACTION_SETTINGS_SCHEMA_VERSION = 1;
22
+ export class PiCompactionSettingsError extends Error {
23
+ code;
24
+ status;
25
+ constructor(code, message, status = 400) {
26
+ super(message);
27
+ this.code = code;
28
+ this.status = status;
29
+ this.name = "PiCompactionSettingsError";
30
+ }
31
+ }
32
+ /** Bounds mirror the environment parser so the two sources cannot disagree. */
33
+ export const GATEWAY_LIMIT_MIN = 1_024;
34
+ export const GATEWAY_LIMIT_MAX = 10_000_000;
35
+ export const KEEP_RECENT_MIN = 0;
36
+ export const KEEP_RECENT_MAX = 1_000_000;
37
+ function isRecord(value) {
38
+ return typeof value === "object" && value !== null && !Array.isArray(value);
39
+ }
40
+ function boundedInteger(value, field, label, min, max) {
41
+ if (value === undefined || value === null)
42
+ return undefined;
43
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
44
+ throw new PiCompactionSettingsError("INVALID_INPUT", `${label}必须是整数`);
45
+ }
46
+ if (value < min || value > max) {
47
+ throw new PiCompactionSettingsError("INVALID_INPUT", `${label}必须在 ${min} 到 ${max} 之间(收到 ${value})`);
48
+ }
49
+ void field;
50
+ return value;
51
+ }
52
+ export function parsePiCompactionSettings(value) {
53
+ if (value === undefined || value === null)
54
+ return {};
55
+ if (!isRecord(value)) {
56
+ throw new PiCompactionSettingsError("INVALID_INPUT", "压缩设置格式无效");
57
+ }
58
+ const unknownKeys = Object.keys(value).filter((key) => key !== "gatewayInputLimitTokens" && key !== "keepRecentTokens");
59
+ if (unknownKeys.length > 0) {
60
+ throw new PiCompactionSettingsError("INVALID_INPUT", `压缩设置包含无效字段:${unknownKeys.join(", ")}`);
61
+ }
62
+ const gateway = boundedInteger(value.gatewayInputLimitTokens, "gatewayInputLimitTokens", "网关输入上限", GATEWAY_LIMIT_MIN, GATEWAY_LIMIT_MAX);
63
+ const keepRecent = boundedInteger(value.keepRecentTokens, "keepRecentTokens", "压缩保留的近期 token", KEEP_RECENT_MIN, KEEP_RECENT_MAX);
64
+ return {
65
+ ...(gateway === undefined ? {} : { gatewayInputLimitTokens: gateway }),
66
+ ...(keepRecent === undefined ? {} : { keepRecentTokens: keepRecent }),
67
+ };
68
+ }
69
+ /**
70
+ * Saved settings win over the environment only when the environment is absent:
71
+ * an operator's exported variable is an explicit override for this process,
72
+ * while the saved file is the durable preference.
73
+ */
74
+ export function resolveCompactionSettings(input) {
75
+ const env = input.env ?? process.env;
76
+ const saved = input.saved ?? {};
77
+ const gatewayFromEnv = Number(env.HARNESS_GATEWAY_INPUT_LIMIT_TOKENS?.trim());
78
+ const keepRecentFromEnv = Number(env.HARNESS_COMPACTION_KEEP_RECENT_TOKENS?.trim());
79
+ const hasGatewayEnv = Number.isSafeInteger(gatewayFromEnv) && gatewayFromEnv > 0;
80
+ const hasKeepRecentEnv = Number.isSafeInteger(keepRecentFromEnv) && keepRecentFromEnv >= 0;
81
+ return {
82
+ gatewayInputLimitTokens: hasGatewayEnv
83
+ ? gatewayFromEnv
84
+ : saved.gatewayInputLimitTokens,
85
+ keepRecentTokens: hasKeepRecentEnv
86
+ ? keepRecentFromEnv
87
+ : saved.keepRecentTokens,
88
+ };
89
+ }
90
+ function settingsFile(appDataRoot) {
91
+ return path.join(appDataRoot, "settings", "pi-compaction.json");
92
+ }
93
+ async function readStored(file) {
94
+ let raw;
95
+ try {
96
+ raw = await readFile(file, "utf8");
97
+ }
98
+ catch {
99
+ return {
100
+ schemaVersion: PI_COMPACTION_SETTINGS_SCHEMA_VERSION,
101
+ revision: 0,
102
+ updatedAt: new Date(0).toISOString(),
103
+ settings: {},
104
+ };
105
+ }
106
+ try {
107
+ const parsed = JSON.parse(raw);
108
+ if (!isRecord(parsed) ||
109
+ parsed.schemaVersion !== PI_COMPACTION_SETTINGS_SCHEMA_VERSION ||
110
+ !Number.isSafeInteger(parsed.revision) ||
111
+ parsed.revision < 0) {
112
+ throw new Error("invalid schema");
113
+ }
114
+ return {
115
+ schemaVersion: PI_COMPACTION_SETTINGS_SCHEMA_VERSION,
116
+ revision: parsed.revision,
117
+ updatedAt: typeof parsed.updatedAt === "string"
118
+ ? parsed.updatedAt
119
+ : new Date(0).toISOString(),
120
+ settings: parsePiCompactionSettings(parsed.settings),
121
+ };
122
+ }
123
+ catch {
124
+ throw new PiCompactionSettingsError("SETTINGS_UNREADABLE", "无法读取压缩设置,请检查程序数据目录中的 settings/pi-compaction.json", 503);
125
+ }
126
+ }
127
+ async function writeAtomic(file, content) {
128
+ await ensureSecureDir(path.dirname(file));
129
+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
130
+ await writeFile(temporary, content, { encoding: "utf8", mode: 0o600 });
131
+ await rename(temporary, file);
132
+ }
133
+ /**
134
+ * One persisted preference per Console data root.
135
+ *
136
+ * Reads are uncached on purpose: the runtime asks once per session start, and a
137
+ * stale cache would silently keep a corrected gateway limit from applying.
138
+ */
139
+ export async function createPiCompactionSettings(appDataRoot) {
140
+ const file = settingsFile(appDataRoot);
141
+ const view = (stored) => {
142
+ const effective = resolveCompactionSettings({ saved: stored.settings });
143
+ return {
144
+ ok: true,
145
+ revision: stored.revision,
146
+ settings: stored.settings,
147
+ effective,
148
+ envOverrides: {
149
+ gatewayInputLimitTokens: effective.gatewayInputLimitTokens !== stored.settings.gatewayInputLimitTokens,
150
+ keepRecentTokens: effective.keepRecentTokens !== stored.settings.keepRecentTokens,
151
+ },
152
+ };
153
+ };
154
+ return {
155
+ async read() {
156
+ return view(await readStored(file));
157
+ },
158
+ async current() {
159
+ return (await readStored(file)).settings;
160
+ },
161
+ async save(input) {
162
+ if (!isRecord(input) ||
163
+ !Number.isSafeInteger(input.expectedRevision) ||
164
+ input.expectedRevision < 0) {
165
+ throw new PiCompactionSettingsError("INVALID_INPUT", "保存需要有效的设置和版本号");
166
+ }
167
+ const settings = parsePiCompactionSettings(input.settings);
168
+ const current = await readStored(file);
169
+ if (current.revision !== input.expectedRevision) {
170
+ throw new PiCompactionSettingsError("REVISION_CONFLICT", "压缩设置已在其他页面更新,请重新加载后再保存", 409);
171
+ }
172
+ const next = {
173
+ schemaVersion: PI_COMPACTION_SETTINGS_SCHEMA_VERSION,
174
+ revision: current.revision + 1,
175
+ updatedAt: new Date().toISOString(),
176
+ settings,
177
+ };
178
+ await writeAtomic(file, `${JSON.stringify(next, null, 2)}\n`);
179
+ return { ok: true, revision: next.revision, settings };
180
+ },
181
+ };
182
+ }
@@ -1,6 +1,7 @@
1
1
  import { createVersionCheck } from "./version-check.js";
2
2
  import { createVersionNotes } from "./version-notes.js";
3
3
  import { createNetworkProxySettings, NetworkProxyError } from "./network-proxy-settings.js";
4
+ import { createPiCompactionSettings, PiCompactionSettingsError, } from "./pi-compaction-settings.js";
4
5
  import { createNpmUpdateClient } from "../../shared/update/npm-client.js";
5
6
  import { AutomationStore } from "../scheduler/automation-store.js";
6
7
  import { AutomationRuntime } from "./automation-runtime.js";
@@ -710,7 +711,11 @@ export async function createConsoleServer(options) {
710
711
  // (显式 ?workspaceId=),不属于 chat 的 pi/* 前缀面;
711
712
  // 交给 handleOperatorDispatch。
712
713
  pathname !== "/api/operator/v1/pi/credentials" &&
713
- pathname !== "/api/operator/v1/pi/providers") {
714
+ pathname !== "/api/operator/v1/pi/providers" &&
715
+ // 压缩设置是用户级全局偏好(网关上限属于部署而非工作区),
716
+ // 没有 workspaceId 可传;留在 chat 分发里会被
717
+ // WORKSPACE_REQUIRED 拒绝,永远到不了下面的 handler。
718
+ pathname !== "/api/operator/v1/pi/compaction-settings") {
714
719
  await handleChatDispatch(req, res, pathname, url, method);
715
720
  return;
716
721
  }
@@ -1023,6 +1028,59 @@ export async function createConsoleServer(options) {
1023
1028
  await dispatchChat(req, res, resolution.context.chatRouteDeps, pathname, resolution.context.workspaceId);
1024
1029
  }
1025
1030
  async function handleOperatorDispatch(req, res, pathname, url, method) {
1031
+ if (pathname === "/api/operator/v1/pi/compaction-settings") {
1032
+ // Gateway limit and retained tail live with the other
1033
+ // cross-project preferences; no-store keeps a corrected limit
1034
+ // from being served stale after a save.
1035
+ res.setHeader("Cache-Control", "no-store");
1036
+ try {
1037
+ const store = await createPiCompactionSettings(bootstrapAppData.root);
1038
+ if (method === "GET") {
1039
+ sendJson(res, 200, await store.read());
1040
+ return;
1041
+ }
1042
+ if (method !== "PUT") {
1043
+ sendJson(res, 405, {
1044
+ ok: false,
1045
+ error: { code: "METHOD_NOT_ALLOWED", message: "method not allowed" },
1046
+ });
1047
+ return;
1048
+ }
1049
+ const failure = evaluateMutationGate(req, {
1050
+ cookieName: bootToken.cookieName,
1051
+ bootToken: bootToken.value,
1052
+ confirmationToken: bootToken.confirmationToken,
1053
+ consoleOrigin: getConsoleOrigin(),
1054
+ allowNonLoopbackAccess: !loopbackBind,
1055
+ });
1056
+ if (failure) {
1057
+ sendJson(res, failure.status, { ok: false, error: failure });
1058
+ return;
1059
+ }
1060
+ const body = await readBodyOnce(req, 16_384);
1061
+ if (!body.ok) {
1062
+ sendJson(res, body.status, {
1063
+ ok: false,
1064
+ error: { code: body.code, message: body.message },
1065
+ });
1066
+ return;
1067
+ }
1068
+ sendJson(res, 200, await store.save(body.value));
1069
+ }
1070
+ catch (error) {
1071
+ const known = error instanceof PiCompactionSettingsError;
1072
+ sendJson(res, known ? error.status : 503, {
1073
+ ok: false,
1074
+ error: {
1075
+ code: known ? error.code : "COMPACTION_SETTINGS_FAILED",
1076
+ message: known
1077
+ ? error.message
1078
+ : "压缩设置未能保存,请检查程序数据目录后重试",
1079
+ },
1080
+ });
1081
+ }
1082
+ return;
1083
+ }
1026
1084
  if (pathname === "/api/operator/v1/network-proxy") {
1027
1085
  res.setHeader("Cache-Control", "no-store");
1028
1086
  try {
@@ -1 +1 @@
1
- import{g as p,r as u,d as a}from"./chunk-6Q2QTUOP-D4dq_L0l.js";import{p as f}from"./chunk-JWPE2WC7-B1yOfAhr.js";import{_ as n,l as o}from"./mermaid.core-CD2GFYrr.js";import{M as c,b as d}from"./cynefin-VYW2F7L2-BIFL8KrA.js";import"./FilePreviewDocx-ybM3ZqSl.js";var v=d().RailroadAbnf.parser.LangiumParser,i=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),l=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:l,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},B={parser:R,db:a,renderer:u,styles:p};export{B as diagram};
1
+ import{g as p,r as u,d as a}from"./chunk-6Q2QTUOP-BWkVY9W5.js";import{p as f}from"./chunk-JWPE2WC7-Du_X-MSA.js";import{_ as n,l as o}from"./mermaid.core-CWATftfi.js";import{M as c,b as d}from"./cynefin-VYW2F7L2-BIFL8KrA.js";import"./FilePreviewDocx-ybM3ZqSl.js";var v=d().RailroadAbnf.parser.LangiumParser,i=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),l=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:l,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},B={parser:R,db:a,renderer:u,styles:p};export{B as diagram};
@@ -1 +1 @@
1
- import{Y as ln,$ as an,a0 as F,a1 as q,a2 as j,a3 as un,a4 as y,a5 as tn,a6 as J,a7 as _,a8 as rn,a9 as o,aa as on,ab as sn,ac as fn}from"./mermaid.core-CD2GFYrr.js";function cn(l){return l.innerRadius}function yn(l){return l.outerRadius}function gn(l){return l.startAngle}function dn(l){return l.endAngle}function mn(l){return l&&l.padAngle}function pn(l,h,I,D,v,A,z,a){var O=I-l,i=D-h,n=z-v,d=a-A,u=d*O-n*i;if(!(u*u<y))return u=(n*(h-A)-d*(l-v))/u,[l+u*O,h+u*i]}function U(l,h,I,D,v,A,z){var a=l-I,O=h-D,i=(z?A:-A)/J(a*a+O*O),n=i*O,d=-i*a,u=l+n,s=h+d,f=I+n,c=D+d,B=(u+f)/2,t=(s+c)/2,m=f-u,g=c-s,R=m*m+g*g,T=v-A,P=u*c-f*s,S=(g<0?-1:1)*J(on(0,T*T*R-P*P)),Y=(P*g-m*S)/R,$=(-P*m-g*S)/R,w=(P*g+m*S)/R,p=(-P*m+g*S)/R,x=Y-B,e=$-t,r=w-B,C=p-t;return x*x+e*e>r*r+C*C&&(Y=w,$=p),{cx:Y,cy:$,x01:-n,y01:-d,x11:Y*(v/T-1),y11:$*(v/T-1)}}function hn(){var l=cn,h=yn,I=j(0),D=null,v=gn,A=dn,z=mn,a=null,O=ln(i);function i(){var n,d,u=+l.apply(this,arguments),s=+h.apply(this,arguments),f=v.apply(this,arguments)-un,c=A.apply(this,arguments)-un,B=rn(c-f),t=c>f;if(a||(a=n=O()),s<u&&(d=s,s=u,u=d),!(s>y))a.moveTo(0,0);else if(B>tn-y)a.moveTo(s*F(f),s*q(f)),a.arc(0,0,s,f,c,!t),u>y&&(a.moveTo(u*F(c),u*q(c)),a.arc(0,0,u,c,f,t));else{var m=f,g=c,R=f,T=c,P=B,S=B,Y=z.apply(this,arguments)/2,$=Y>y&&(D?+D.apply(this,arguments):J(u*u+s*s)),w=_(rn(s-u)/2,+I.apply(this,arguments)),p=w,x=w,e,r;if($>y){var C=sn($/u*q(Y)),K=sn($/s*q(Y));(P-=C*2)>y?(C*=t?1:-1,R+=C,T-=C):(P=0,R=T=(f+c)/2),(S-=K*2)>y?(K*=t?1:-1,m+=K,g-=K):(S=0,m=g=(f+c)/2)}var G=s*F(m),H=s*q(m),L=u*F(T),M=u*q(T);if(w>y){var N=s*F(g),Q=s*q(g),V=u*F(R),W=u*q(R),E;if(B<an)if(E=pn(G,H,V,W,N,Q,L,M)){var X=G-E[0],Z=H-E[1],b=N-E[0],k=Q-E[1],nn=1/q(fn((X*b+Z*k)/(J(X*X+Z*Z)*J(b*b+k*k)))/2),en=J(E[0]*E[0]+E[1]*E[1]);p=_(w,(u-en)/(nn-1)),x=_(w,(s-en)/(nn+1))}else p=x=0}S>y?x>y?(e=U(V,W,G,H,s,x,t),r=U(N,Q,L,M,s,x,t),a.moveTo(e.cx+e.x01,e.cy+e.y01),x<w?a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,s,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),!t),a.arc(r.cx,r.cy,x,o(r.y11,r.x11),o(r.y01,r.x01),!t))):(a.moveTo(G,H),a.arc(0,0,s,m,g,!t)):a.moveTo(G,H),!(u>y)||!(P>y)?a.lineTo(L,M):p>y?(e=U(L,M,N,Q,u,-p,t),r=U(G,H,V,W,u,-p,t),a.lineTo(e.cx+e.x01,e.cy+e.y01),p<w?a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,u,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),t),a.arc(r.cx,r.cy,p,o(r.y11,r.x11),o(r.y01,r.x01),!t))):a.arc(0,0,u,T,R,t)}if(a.closePath(),n)return a=null,n+""||null}return i.centroid=function(){var n=(+l.apply(this,arguments)+ +h.apply(this,arguments))/2,d=(+v.apply(this,arguments)+ +A.apply(this,arguments))/2-an/2;return[F(d)*n,q(d)*n]},i.innerRadius=function(n){return arguments.length?(l=typeof n=="function"?n:j(+n),i):l},i.outerRadius=function(n){return arguments.length?(h=typeof n=="function"?n:j(+n),i):h},i.cornerRadius=function(n){return arguments.length?(I=typeof n=="function"?n:j(+n),i):I},i.padRadius=function(n){return arguments.length?(D=n==null?null:typeof n=="function"?n:j(+n),i):D},i.startAngle=function(n){return arguments.length?(v=typeof n=="function"?n:j(+n),i):v},i.endAngle=function(n){return arguments.length?(A=typeof n=="function"?n:j(+n),i):A},i.padAngle=function(n){return arguments.length?(z=typeof n=="function"?n:j(+n),i):z},i.context=function(n){return arguments.length?(a=n??null,i):a},i}export{hn as d};
1
+ import{Y as ln,$ as an,a0 as F,a1 as q,a2 as j,a3 as un,a4 as y,a5 as tn,a6 as J,a7 as _,a8 as rn,a9 as o,aa as on,ab as sn,ac as fn}from"./mermaid.core-CWATftfi.js";function cn(l){return l.innerRadius}function yn(l){return l.outerRadius}function gn(l){return l.startAngle}function dn(l){return l.endAngle}function mn(l){return l&&l.padAngle}function pn(l,h,I,D,v,A,z,a){var O=I-l,i=D-h,n=z-v,d=a-A,u=d*O-n*i;if(!(u*u<y))return u=(n*(h-A)-d*(l-v))/u,[l+u*O,h+u*i]}function U(l,h,I,D,v,A,z){var a=l-I,O=h-D,i=(z?A:-A)/J(a*a+O*O),n=i*O,d=-i*a,u=l+n,s=h+d,f=I+n,c=D+d,B=(u+f)/2,t=(s+c)/2,m=f-u,g=c-s,R=m*m+g*g,T=v-A,P=u*c-f*s,S=(g<0?-1:1)*J(on(0,T*T*R-P*P)),Y=(P*g-m*S)/R,$=(-P*m-g*S)/R,w=(P*g+m*S)/R,p=(-P*m+g*S)/R,x=Y-B,e=$-t,r=w-B,C=p-t;return x*x+e*e>r*r+C*C&&(Y=w,$=p),{cx:Y,cy:$,x01:-n,y01:-d,x11:Y*(v/T-1),y11:$*(v/T-1)}}function hn(){var l=cn,h=yn,I=j(0),D=null,v=gn,A=dn,z=mn,a=null,O=ln(i);function i(){var n,d,u=+l.apply(this,arguments),s=+h.apply(this,arguments),f=v.apply(this,arguments)-un,c=A.apply(this,arguments)-un,B=rn(c-f),t=c>f;if(a||(a=n=O()),s<u&&(d=s,s=u,u=d),!(s>y))a.moveTo(0,0);else if(B>tn-y)a.moveTo(s*F(f),s*q(f)),a.arc(0,0,s,f,c,!t),u>y&&(a.moveTo(u*F(c),u*q(c)),a.arc(0,0,u,c,f,t));else{var m=f,g=c,R=f,T=c,P=B,S=B,Y=z.apply(this,arguments)/2,$=Y>y&&(D?+D.apply(this,arguments):J(u*u+s*s)),w=_(rn(s-u)/2,+I.apply(this,arguments)),p=w,x=w,e,r;if($>y){var C=sn($/u*q(Y)),K=sn($/s*q(Y));(P-=C*2)>y?(C*=t?1:-1,R+=C,T-=C):(P=0,R=T=(f+c)/2),(S-=K*2)>y?(K*=t?1:-1,m+=K,g-=K):(S=0,m=g=(f+c)/2)}var G=s*F(m),H=s*q(m),L=u*F(T),M=u*q(T);if(w>y){var N=s*F(g),Q=s*q(g),V=u*F(R),W=u*q(R),E;if(B<an)if(E=pn(G,H,V,W,N,Q,L,M)){var X=G-E[0],Z=H-E[1],b=N-E[0],k=Q-E[1],nn=1/q(fn((X*b+Z*k)/(J(X*X+Z*Z)*J(b*b+k*k)))/2),en=J(E[0]*E[0]+E[1]*E[1]);p=_(w,(u-en)/(nn-1)),x=_(w,(s-en)/(nn+1))}else p=x=0}S>y?x>y?(e=U(V,W,G,H,s,x,t),r=U(N,Q,L,M,s,x,t),a.moveTo(e.cx+e.x01,e.cy+e.y01),x<w?a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,s,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),!t),a.arc(r.cx,r.cy,x,o(r.y11,r.x11),o(r.y01,r.x01),!t))):(a.moveTo(G,H),a.arc(0,0,s,m,g,!t)):a.moveTo(G,H),!(u>y)||!(P>y)?a.lineTo(L,M):p>y?(e=U(L,M,N,Q,u,-p,t),r=U(G,H,V,W,u,-p,t),a.lineTo(e.cx+e.x01,e.cy+e.y01),p<w?a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,u,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),t),a.arc(r.cx,r.cy,p,o(r.y11,r.x11),o(r.y01,r.x01),!t))):a.arc(0,0,u,T,R,t)}if(a.closePath(),n)return a=null,n+""||null}return i.centroid=function(){var n=(+l.apply(this,arguments)+ +h.apply(this,arguments))/2,d=(+v.apply(this,arguments)+ +A.apply(this,arguments))/2-an/2;return[F(d)*n,q(d)*n]},i.innerRadius=function(n){return arguments.length?(l=typeof n=="function"?n:j(+n),i):l},i.outerRadius=function(n){return arguments.length?(h=typeof n=="function"?n:j(+n),i):h},i.cornerRadius=function(n){return arguments.length?(I=typeof n=="function"?n:j(+n),i):I},i.padRadius=function(n){return arguments.length?(D=n==null?null:typeof n=="function"?n:j(+n),i):D},i.startAngle=function(n){return arguments.length?(v=typeof n=="function"?n:j(+n),i):v},i.endAngle=function(n){return arguments.length?(A=typeof n=="function"?n:j(+n),i):A},i.padAngle=function(n){return arguments.length?(z=typeof n=="function"?n:j(+n),i):z},i.context=function(n){return arguments.length?(a=n??null,i):a},i}export{hn as d};