ceulen 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +317 -12
- package/README.md +87 -91
- package/extensions/lib/advisor-marker.ts +33 -0
- package/extensions/lib/panel.ts +25 -2
- package/extensions/lib/rate.ts +24 -0
- package/extensions/lib/registry.ts +93 -7
- package/extensions/lib/tools.ts +47 -0
- package/extensions/lib/usage-store.ts +33 -0
- package/extensions/modules/advisor/commands/advisor.ts +244 -0
- package/extensions/modules/advisor/configPanel.ts +194 -0
- package/extensions/modules/advisor/index.ts +217 -0
- package/extensions/modules/advisor/lib/config.ts +248 -0
- package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
- package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
- package/extensions/modules/advisor/lib/model-picker.ts +47 -0
- package/extensions/modules/advisor/lib/watcher.ts +286 -0
- package/extensions/modules/advisor/test/compliance.test.ts +125 -0
- package/extensions/modules/advisor/test/config.test.ts +202 -0
- package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
- package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
- package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
- package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
- package/extensions/modules/advisor/test/module.test.ts +586 -0
- package/extensions/modules/advisor/test/watcher.test.ts +478 -0
- package/extensions/modules/classifier/configPanel.ts +104 -0
- package/extensions/modules/classifier/index.ts +297 -0
- package/extensions/modules/classifier/lib/settings.ts +95 -0
- package/extensions/modules/classifier/test/classifier.test.ts +475 -0
- package/extensions/modules/composer/index.ts +152 -3
- package/extensions/modules/composer/lib/footer.ts +119 -0
- package/extensions/modules/composer/lib/shapes.ts +265 -26
- package/extensions/modules/composer/test/editor.test.ts +1 -1
- package/extensions/modules/composer/test/footer.test.ts +96 -0
- package/extensions/modules/composer/test/module.test.ts +113 -11
- package/extensions/modules/composer/test/screen.test.ts +29 -1
- package/extensions/modules/composer/test/shapes.test.ts +224 -8
- package/extensions/modules/config/defaultTools.ts +96 -0
- package/extensions/modules/config/index.ts +147 -7
- package/extensions/modules/config/piSettings.ts +254 -69
- package/extensions/modules/config/test/defaultTools.test.ts +122 -0
- package/extensions/modules/config/test/menu.test.ts +64 -0
- package/extensions/modules/config/test/panel.test.ts +38 -23
- package/extensions/modules/config/test/piSettings.test.ts +130 -3
- package/extensions/modules/config/test/renderTools.test.ts +71 -0
- package/extensions/modules/config/test/tools.test.ts +146 -0
- package/extensions/modules/fff/index.ts +2094 -0
- package/extensions/modules/fff/lib/query.ts +129 -0
- package/extensions/modules/fff/test/index.test.ts +607 -0
- package/extensions/modules/fff/test/query.test.ts +71 -0
- package/extensions/modules/munin/configPanel.ts +105 -0
- package/extensions/modules/munin/index.ts +641 -0
- package/extensions/modules/munin/lib/helpers.ts +471 -0
- package/extensions/modules/munin/lib/retry.ts +20 -0
- package/extensions/modules/munin/lib/sdk.ts +218 -0
- package/extensions/modules/munin/test/config.test.ts +168 -0
- package/extensions/modules/munin/test/configPanel.test.ts +161 -0
- package/extensions/modules/munin/test/extension.test.ts +224 -0
- package/extensions/modules/munin/test/helpers.test.ts +523 -0
- package/extensions/modules/munin/test/retry.test.ts +145 -0
- package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
- package/extensions/modules/plan/configPanel.ts +152 -0
- package/extensions/modules/plan/index.ts +917 -0
- package/extensions/modules/plan/lib/plan-tools.ts +72 -0
- package/extensions/modules/plan/lib/prompt.ts +65 -0
- package/extensions/modules/plan/lib/settings.ts +166 -0
- package/extensions/modules/plan/lib/shell-gate.ts +200 -0
- package/extensions/modules/plan/test/configPanel.test.ts +96 -0
- package/extensions/modules/plan/test/harness.ts +133 -0
- package/extensions/modules/plan/test/module.test.ts +305 -0
- package/extensions/modules/plan/test/settings.test.ts +114 -0
- package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
- package/extensions/modules/ponytail/index.ts +23 -73
- package/extensions/modules/ponytail/lib/config.ts +1 -6
- package/extensions/modules/ponytail/test/extension.test.ts +1 -85
- package/extensions/modules/repair/configPanel.ts +96 -0
- package/extensions/modules/repair/index.ts +414 -0
- package/extensions/modules/repair/lib/auto-bg.ts +333 -0
- package/extensions/modules/repair/lib/edit-repair.ts +155 -0
- package/extensions/modules/repair/lib/editor.ts +251 -0
- package/extensions/modules/repair/lib/guards.ts +34 -0
- package/extensions/modules/repair/lib/input-repair.ts +324 -0
- package/extensions/modules/repair/lib/patch.ts +481 -0
- package/extensions/modules/repair/lib/settings.ts +114 -0
- package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
- package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
- package/extensions/modules/repair/test/editor.test.ts +141 -0
- package/extensions/modules/repair/test/guards.test.ts +64 -0
- package/extensions/modules/repair/test/input-repair.test.ts +231 -0
- package/extensions/modules/repair/test/patch.test.ts +563 -0
- package/extensions/modules/repair/test/settings.test.ts +167 -0
- package/extensions/modules/repair/test/wrapper.test.ts +210 -0
- package/extensions/modules/router/commands/commands.ts +4 -0
- package/extensions/modules/router/lib/client.ts +61 -0
- package/extensions/modules/router/lib/provider.ts +34 -13
- package/extensions/modules/router/lib/systemone.ts +152 -0
- package/extensions/modules/router/test/unit.test.ts +179 -0
- package/extensions/modules/rtk/findFallback.js +68 -0
- package/extensions/modules/rtk/index.ts +248 -0
- package/extensions/modules/rtk/safe-rewrite.js +74 -0
- package/extensions/modules/rtk/test/findFallback.test.js +66 -0
- package/extensions/modules/rtk/test/index.test.js +131 -0
- package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
- package/extensions/modules/rtk/version-gate.js +34 -0
- package/extensions/modules/serena/index.ts +629 -0
- package/extensions/modules/serena/lib/detect.ts +73 -0
- package/extensions/modules/serena/lib/env.ts +76 -0
- package/extensions/modules/serena/lib/guidance.ts +26 -0
- package/extensions/modules/serena/lib/normalize.ts +27 -0
- package/extensions/modules/serena/lib/symbol-key.ts +20 -0
- package/extensions/modules/serena/lib/truncate.ts +20 -0
- package/extensions/modules/serena/test/env.test.ts +122 -0
- package/extensions/modules/serena/test/index.test.ts +347 -0
- package/extensions/modules/serena/test/worker.test.ts +562 -0
- package/extensions/modules/serena/worker.ts +858 -0
- package/extensions/modules/steering/configPanel.ts +122 -0
- package/extensions/modules/steering/index.ts +616 -0
- package/extensions/modules/steering/lib/anchor.ts +175 -0
- package/extensions/modules/steering/lib/errors.ts +253 -0
- package/extensions/modules/steering/lib/family.ts +33 -0
- package/extensions/modules/steering/lib/guidance.ts +172 -0
- package/extensions/modules/steering/lib/history.ts +170 -0
- package/extensions/modules/steering/lib/settings.ts +127 -0
- package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
- package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
- package/extensions/modules/steering/test/anchor.test.ts +160 -0
- package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
- package/extensions/modules/steering/test/errors.test.ts +309 -0
- package/extensions/modules/steering/test/family.test.ts +43 -0
- package/extensions/modules/steering/test/guidance.test.ts +357 -0
- package/extensions/modules/steering/test/harness.ts +93 -0
- package/extensions/modules/steering/test/history.test.ts +118 -0
- package/extensions/modules/steering/test/settings.test.ts +182 -0
- package/extensions/modules/steering/test/status.test.ts +71 -0
- package/extensions/modules/steering/test/toolCall.test.ts +99 -0
- package/extensions/modules/subagent/agents/planner.md +14 -0
- package/extensions/modules/subagent/agents/reviewer.md +42 -0
- package/extensions/modules/subagent/agents/scout.md +47 -0
- package/extensions/modules/subagent/agents/tester.md +12 -0
- package/extensions/modules/subagent/agents/worker.md +18 -0
- package/extensions/modules/subagent/configPanel.ts +219 -0
- package/extensions/modules/subagent/index.ts +2451 -0
- package/extensions/modules/subagent/lib/agents.ts +408 -0
- package/extensions/modules/subagent/lib/background.ts +383 -0
- package/extensions/modules/subagent/lib/herdr.ts +1019 -0
- package/extensions/modules/subagent/lib/history.ts +126 -0
- package/extensions/modules/subagent/lib/model.ts +156 -0
- package/extensions/modules/subagent/lib/render.ts +335 -0
- package/extensions/modules/subagent/lib/result.ts +110 -0
- package/extensions/modules/subagent/lib/roles.ts +296 -0
- package/extensions/modules/subagent/lib/routing.ts +223 -0
- package/extensions/modules/subagent/lib/runner.ts +559 -0
- package/extensions/modules/subagent/lib/schema.ts +21 -0
- package/extensions/modules/subagent/lib/security.ts +752 -0
- package/extensions/modules/subagent/lib/settings.ts +159 -0
- package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
- package/extensions/modules/subagent/lib/threads.ts +135 -0
- package/extensions/modules/subagent/lib/types.ts +18 -0
- package/extensions/modules/subagent/lib/widget.ts +475 -0
- package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
- package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
- package/extensions/modules/subagent/test/routing.test.ts +350 -0
- package/extensions/modules/subagent/test/widget.test.ts +208 -0
- package/extensions/modules/usage/index.ts +59 -16
- package/extensions/modules/usage/test/genrate.test.ts +70 -0
- package/extensions/modules/usage/test/parsers.test.ts +13 -0
- package/extensions/modules/ux/UPSTREAM +24 -0
- package/extensions/modules/ux/index.ts +393 -0
- package/extensions/modules/ux/lib/audit.ts +562 -0
- package/extensions/modules/ux/lib/config.ts +136 -0
- package/extensions/modules/ux/lib/instructions.ts +77 -0
- package/extensions/modules/ux/test/audit.test.ts +756 -0
- package/extensions/modules/ux/test/extension.test.ts +394 -0
- package/extensions/modules/ux/test/instructions.test.ts +19 -0
- package/extensions/modules/web/configPanel.ts +193 -0
- package/extensions/modules/web/index.ts +978 -0
- package/extensions/modules/web/lib/agy.ts +209 -0
- package/extensions/modules/web/lib/brave.ts +42 -0
- package/extensions/modules/web/lib/cdp.ts +686 -0
- package/extensions/modules/web/lib/chatapi.ts +101 -0
- package/extensions/modules/web/lib/chatgpt.ts +796 -0
- package/extensions/modules/web/lib/chrome.ts +328 -0
- package/extensions/modules/web/lib/config.ts +136 -0
- package/extensions/modules/web/lib/content.ts +99 -0
- package/extensions/modules/web/lib/crawl4ai.ts +172 -0
- package/extensions/modules/web/lib/extract.ts +235 -0
- package/extensions/modules/web/lib/firecrawl.ts +56 -0
- package/extensions/modules/web/lib/format.ts +197 -0
- package/extensions/modules/web/lib/gemini-auth.ts +286 -0
- package/extensions/modules/web/lib/gemini-dr.ts +338 -0
- package/extensions/modules/web/lib/gemini.ts +551 -0
- package/extensions/modules/web/lib/imageapi.ts +559 -0
- package/extensions/modules/web/lib/retry.ts +71 -0
- package/extensions/modules/web/lib/search.ts +237 -0
- package/extensions/modules/web/lib/searxng.ts +69 -0
- package/extensions/modules/web/lib/settings.ts +148 -0
- package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
- package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
- package/extensions/modules/web/test/agy.test.ts +383 -0
- package/extensions/modules/web/test/cdp.test.ts +717 -0
- package/extensions/modules/web/test/chat.test.ts +171 -0
- package/extensions/modules/web/test/chatgpt.test.ts +633 -0
- package/extensions/modules/web/test/chrome.test.ts +282 -0
- package/extensions/modules/web/test/config.test.ts +218 -0
- package/extensions/modules/web/test/configPanel.test.ts +132 -0
- package/extensions/modules/web/test/crawl.test.ts +134 -0
- package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
- package/extensions/modules/web/test/extension.test.ts +118 -0
- package/extensions/modules/web/test/extract.test.ts +436 -0
- package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
- package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
- package/extensions/modules/web/test/fixtures/interaction.html +31 -0
- package/extensions/modules/web/test/format.test.ts +230 -0
- package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
- package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
- package/extensions/modules/web/test/gemini.test.ts +472 -0
- package/extensions/modules/web/test/hook.test.ts +101 -0
- package/extensions/modules/web/test/image.test.ts +1089 -0
- package/extensions/modules/web/test/retry.test.ts +119 -0
- package/extensions/modules/web/test/screenshot.test.ts +109 -0
- package/extensions/modules/web/test/search.test.ts +210 -0
- package/extensions/modules/web/test/settings.test.ts +165 -0
- package/extensions/modules/web/test/skill.test.ts +72 -0
- package/extensions/modules/web/types.d.ts +3 -0
- package/extensions/modules/web/vendor/package.json +1 -0
- package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
- package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
- package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
- package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
- package/extensions/modules/web/vendor/readability/index.js +9 -0
- package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
- package/extensions/modules/zai/configPanel.ts +151 -0
- package/extensions/modules/zai/index.ts +186 -0
- package/extensions/modules/zai/lib/anthropic.ts +159 -0
- package/extensions/modules/zai/lib/settings.ts +198 -0
- package/extensions/modules/zai/lib/signing.ts +718 -0
- package/extensions/modules/zai/lib/throttle.ts +198 -0
- package/extensions/modules/zai/test/anthropic.test.ts +132 -0
- package/extensions/modules/zai/test/configPanel.test.ts +207 -0
- package/extensions/modules/zai/test/extension.test.ts +249 -0
- package/extensions/modules/zai/test/settings.test.ts +183 -0
- package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
- package/extensions/modules/zai/test/signing.test.ts +345 -0
- package/extensions/modules/zai/test/throttle.test.ts +329 -0
- package/package.json +19 -4
- package/scripts/validate-themes.mjs +75 -0
- package/skills/munin/SKILL.md +117 -0
- package/skills/ux-capture/SKILL.md +202 -0
- package/skills/ux-design/SKILL.md +279 -0
- package/skills/ux-presets/SKILL.md +484 -0
- package/skills/ux-routing/SKILL.md +46 -0
- package/skills/web/SKILL.md +153 -0
- package/themes/alabaster.json +93 -0
- package/themes/amethyst.json +96 -0
- package/themes/anthracite.json +93 -0
- package/themes/basalt.json +91 -0
- package/themes/birch.json +95 -0
- package/themes/catppuccin-mocha.json +91 -0
- package/themes/dark-abyss.json +91 -0
- package/themes/dark-arctic.json +104 -0
- package/themes/dark-aurora.json +95 -0
- package/themes/dark-catppuccin.json +107 -0
- package/themes/dark-cavern.json +91 -0
- package/themes/dark-celestial.json +106 -0
- package/themes/dark-copper.json +95 -0
- package/themes/dark-cosmos.json +90 -0
- package/themes/dark-cyberpunk.json +102 -0
- package/themes/dark-dracula.json +98 -0
- package/themes/dark-eclipse.json +91 -0
- package/themes/dark-ember.json +95 -0
- package/themes/dark-equinox.json +90 -0
- package/themes/dark-forest.json +96 -0
- package/themes/dark-github.json +105 -0
- package/themes/dark-gruvbox.json +112 -0
- package/themes/dark-lavender.json +95 -0
- package/themes/dark-lunar.json +89 -0
- package/themes/dark-midnight.json +95 -0
- package/themes/dark-monochrome.json +94 -0
- package/themes/dark-monokai.json +98 -0
- package/themes/dark-nebula.json +90 -0
- package/themes/dark-neon-noir.json +100 -0
- package/themes/dark-nord.json +98 -0
- package/themes/dark-ocean.json +101 -0
- package/themes/dark-one.json +100 -0
- package/themes/dark-poimandres.json +115 -0
- package/themes/dark-rainforest.json +91 -0
- package/themes/dark-reef.json +91 -0
- package/themes/dark-retro.json +92 -0
- package/themes/dark-rose-pine.json +96 -0
- package/themes/dark-sakura.json +95 -0
- package/themes/dark-slate.json +95 -0
- package/themes/dark-solarized.json +97 -0
- package/themes/dark-solstice.json +90 -0
- package/themes/dark-starfall.json +91 -0
- package/themes/dark-sunset.json +99 -0
- package/themes/dark-swamp.json +90 -0
- package/themes/dark-synthwave.json +103 -0
- package/themes/dark-taiga.json +91 -0
- package/themes/dark-terminal.json +95 -0
- package/themes/dark-tokyo-night.json +101 -0
- package/themes/dark-tundra.json +91 -0
- package/themes/dark-twilight.json +91 -0
- package/themes/dark-volcanic.json +91 -0
- package/themes/dark.json +80 -0
- package/themes/graphite.json +92 -0
- package/themes/light-arctic.json +107 -0
- package/themes/light-aurora-day.json +91 -0
- package/themes/light-canyon.json +91 -0
- package/themes/light-catppuccin.json +106 -0
- package/themes/light-cirrus.json +90 -0
- package/themes/light-coral.json +95 -0
- package/themes/light-cyberpunk.json +96 -0
- package/themes/light-dawn.json +90 -0
- package/themes/light-dunes.json +91 -0
- package/themes/light-eucalyptus.json +95 -0
- package/themes/light-forest.json +100 -0
- package/themes/light-frost.json +95 -0
- package/themes/light-github.json +115 -0
- package/themes/light-glacier.json +91 -0
- package/themes/light-gruvbox.json +108 -0
- package/themes/light-haze.json +90 -0
- package/themes/light-honeycomb.json +95 -0
- package/themes/light-lagoon.json +91 -0
- package/themes/light-lavender.json +95 -0
- package/themes/light-meadow.json +91 -0
- package/themes/light-mint.json +95 -0
- package/themes/light-monochrome.json +101 -0
- package/themes/light-ocean.json +99 -0
- package/themes/light-one.json +99 -0
- package/themes/light-opal.json +91 -0
- package/themes/light-orchard.json +91 -0
- package/themes/light-paper.json +95 -0
- package/themes/light-poimandres.json +115 -0
- package/themes/light-prism.json +90 -0
- package/themes/light-retro.json +98 -0
- package/themes/light-sand.json +95 -0
- package/themes/light-savanna.json +91 -0
- package/themes/light-solarized.json +102 -0
- package/themes/light-soleil.json +90 -0
- package/themes/light-sunset.json +99 -0
- package/themes/light-synthwave.json +98 -0
- package/themes/light-tokyo-night.json +111 -0
- package/themes/light-wetland.json +91 -0
- package/themes/light-zenith.json +89 -0
- package/themes/light.json +80 -0
- package/themes/limestone.json +94 -0
- package/themes/mahogany.json +97 -0
- package/themes/marble.json +93 -0
- package/themes/mirage.json +79 -0
- package/themes/obsidian.json +91 -0
- package/themes/onyx.json +91 -0
- package/themes/pearl.json +93 -0
- package/themes/porcelain.json +91 -0
- package/themes/quartz.json +96 -0
- package/themes/sandstone.json +95 -0
- package/themes/titanium.json +90 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
// Ported verbatim from pi-model-tools extensions/test/unit/zcode-signing.test.ts
|
|
2
|
+
// (import path only: lib/signing.ts).
|
|
3
|
+
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { describe, it } from "node:test";
|
|
6
|
+
import {
|
|
7
|
+
ClientSigningManager,
|
|
8
|
+
buildZcodeIdentityHeaders,
|
|
9
|
+
createProofOfWork,
|
|
10
|
+
parseSigningCredential,
|
|
11
|
+
resolveZcodeIdentity,
|
|
12
|
+
zcodeSigningEnabled,
|
|
13
|
+
type MutableHeaders,
|
|
14
|
+
type SigningCredential,
|
|
15
|
+
} from "../lib/signing.js";
|
|
16
|
+
|
|
17
|
+
const IDENTITY = {
|
|
18
|
+
appVersion: "3.10.2",
|
|
19
|
+
sourceTitle: "electron",
|
|
20
|
+
refererOrigin: "https://zcode.z.ai",
|
|
21
|
+
deviceMid: "11111111-2222-3333-4444-555555555555",
|
|
22
|
+
};
|
|
23
|
+
const CRED: SigningCredential = { credential: "abc123.secret456", appVersion: "3.10.2" };
|
|
24
|
+
const URL_ULTRA = "https://zcode.z.ai/api/v1/ultra-zai/anthropic/v1/messages";
|
|
25
|
+
const URL_API = "https://api.z.ai/api/anthropic/v1/messages";
|
|
26
|
+
const URL_START_PLAN = "https://zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages";
|
|
27
|
+
|
|
28
|
+
const GATE_ENABLED = {
|
|
29
|
+
code: 0,
|
|
30
|
+
data: { codingPlanSignature: { enable: true } },
|
|
31
|
+
};
|
|
32
|
+
const GATE_DISABLED = { code: 0, data: {} };
|
|
33
|
+
|
|
34
|
+
/** JSON response helper for the injected fetch. */
|
|
35
|
+
function jsonResponse(body: unknown, status = 200): Response {
|
|
36
|
+
return new Response(JSON.stringify(body), {
|
|
37
|
+
status,
|
|
38
|
+
headers: { "content-type": "application/json" },
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function baseHeaders(): MutableHeaders {
|
|
43
|
+
return {
|
|
44
|
+
"x-api-key": CRED.credential,
|
|
45
|
+
"anthropic-version": "2023-06-01",
|
|
46
|
+
"content-type": "application/json",
|
|
47
|
+
"x-session-id": "sess_test_0001",
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The fixture needs the same HKDF the lib uses; re-implemented here so the test
|
|
52
|
+
// validates against the algorithm, not a shared secret helper.
|
|
53
|
+
async function hkdfTestHelpers() {
|
|
54
|
+
const { createHash, hkdfSync } = await import("node:crypto");
|
|
55
|
+
return {
|
|
56
|
+
createHash,
|
|
57
|
+
derive: (secret: string, info: string) =>
|
|
58
|
+
new Uint8Array(
|
|
59
|
+
hkdfSync("sha256", Buffer.from(secret, "utf8"), Buffer.from("WD_CLIENT_SIGN_KDF_SALT", "utf8"), Buffer.from(info, "utf8"), 32),
|
|
60
|
+
),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Server-side privateCipher for apiKeyId/secret wrapping pkcs8 (AES-256-GCM, AAD=apiKeyId). */
|
|
65
|
+
async function sealPrivateKey(apiKeyId: string, secret: string, pkcs8: Uint8Array<ArrayBuffer>): Promise<string> {
|
|
66
|
+
const { derive } = await hkdfTestHelpers();
|
|
67
|
+
const aesBits = new Uint8Array(derive(secret, "ed25519_priv"));
|
|
68
|
+
const aesKey = await crypto.subtle.importKey("raw", aesBits, "AES-GCM", false, ["encrypt"]);
|
|
69
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
70
|
+
const cipher = new Uint8Array(
|
|
71
|
+
await crypto.subtle.encrypt(
|
|
72
|
+
{ name: "AES-GCM", iv, additionalData: Buffer.from(apiKeyId, "utf8"), tagLength: 128 },
|
|
73
|
+
aesKey,
|
|
74
|
+
pkcs8,
|
|
75
|
+
),
|
|
76
|
+
);
|
|
77
|
+
const out = new Uint8Array(iv.length + cipher.length);
|
|
78
|
+
out.set(iv);
|
|
79
|
+
out.set(cipher, iv.length);
|
|
80
|
+
return Buffer.from(out).toString("base64");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface MockCalls {
|
|
84
|
+
urls: string[];
|
|
85
|
+
gateCount: number;
|
|
86
|
+
handshakeCount: number;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Fetch mock: gate (enabled/disabled per arg) + handshake returning a fixture
|
|
91
|
+
* cipher for a freshly generated key (kept in `state.privateKey`).
|
|
92
|
+
*/
|
|
93
|
+
function makeFetch(opts: { gateEnabled: boolean; gateThrows?: boolean; handshakeStatus?: number }) {
|
|
94
|
+
const calls: MockCalls = { urls: [], gateCount: 0, handshakeCount: 0 };
|
|
95
|
+
const privateKeys: CryptoKey[] = [];
|
|
96
|
+
const fetchImpl: typeof fetch = async (input, init) => {
|
|
97
|
+
const url = String(input);
|
|
98
|
+
calls.urls.push(url);
|
|
99
|
+
if (url.includes("/api/v1/agent/configs")) {
|
|
100
|
+
calls.gateCount += 1;
|
|
101
|
+
if (opts.gateThrows) throw new Error("network down");
|
|
102
|
+
return jsonResponse(opts.gateEnabled ? GATE_ENABLED : GATE_DISABLED);
|
|
103
|
+
}
|
|
104
|
+
if (url.includes("/api/paas/c1f3a7e2/v2/client")) {
|
|
105
|
+
calls.handshakeCount += 1;
|
|
106
|
+
if (opts.handshakeStatus) return jsonResponse({ code: opts.handshakeStatus, msg: "nope" }, opts.handshakeStatus);
|
|
107
|
+
// Verify the HMAC handshake signature the same way the server would.
|
|
108
|
+
const body = JSON.parse(String(init?.body)) as { apiKey: string; nonce: string; sig: string; ts: string };
|
|
109
|
+
const [apiKeyId, secret] = body.apiKey.split(".");
|
|
110
|
+
const { derive } = await hkdfTestHelpers();
|
|
111
|
+
const hmacBits = new Uint8Array(derive(secret, "getSignKey_hmac"));
|
|
112
|
+
const hmacKey = await crypto.subtle.importKey("raw", hmacBits, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
|
|
113
|
+
const message = `get_sign_key\n${apiKeyId}\n${body.ts}\n${body.nonce}`;
|
|
114
|
+
const ok = await crypto.subtle.verify(
|
|
115
|
+
"HMAC",
|
|
116
|
+
hmacKey,
|
|
117
|
+
Buffer.from(body.sig, "base64"),
|
|
118
|
+
Buffer.from(message, "utf8"),
|
|
119
|
+
);
|
|
120
|
+
assert.ok(ok, "handshake HMAC signature must verify server-side");
|
|
121
|
+
const pair = await crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"]) as CryptoKeyPair;
|
|
122
|
+
privateKeys.push(pair.privateKey);
|
|
123
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
124
|
+
// The server seals the PKCS8 key as BASE64 TEXT (upstream TextDecoder decode).
|
|
125
|
+
const pkcs8Text = Buffer.from(pkcs8).toString("base64");
|
|
126
|
+
const privateCipher = await sealPrivateKey(apiKeyId, secret, new TextEncoder().encode(pkcs8Text));
|
|
127
|
+
return jsonResponse({ code: 200, data: { privateCipher } });
|
|
128
|
+
}
|
|
129
|
+
return jsonResponse({ code: 404 }, 404);
|
|
130
|
+
};
|
|
131
|
+
return { fetchImpl, calls, getPrivateKey: (i = 0) => privateKeys[i] };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function signedHeaders(manager: ClientSigningManager, url = URL_ULTRA): Promise<MutableHeaders> {
|
|
135
|
+
const headers = baseHeaders();
|
|
136
|
+
const signed = await manager.sign(url, headers, CRED);
|
|
137
|
+
assert.equal(signed, true, "request should be signed");
|
|
138
|
+
return headers;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
describe("zcode-signing", () => {
|
|
142
|
+
it("credential parse: two-part ok, zero/two dots rejected, empty parts rejected", () => {
|
|
143
|
+
assert.deepEqual(parseSigningCredential("abc123.secret456"), { apiKeyId: "abc123", apiKeySecret: "secret456" });
|
|
144
|
+
assert.equal(parseSigningCredential("nodotshere"), undefined);
|
|
145
|
+
assert.equal(parseSigningCredential("a.b.c"), undefined);
|
|
146
|
+
assert.equal(parseSigningCredential(".secret"), undefined);
|
|
147
|
+
assert.equal(parseSigningCredential("id."), undefined);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("identity headers: exact set, env overrides, printable gate drops bad values", () => {
|
|
151
|
+
const h = buildZcodeIdentityHeaders(IDENTITY);
|
|
152
|
+
assert.equal(h["User-Agent"], "ZCode/3.10.2");
|
|
153
|
+
assert.equal(h["X-ZCode-App-Version"], "3.10.2");
|
|
154
|
+
assert.equal(h["X-Title"], "Z Code@electron");
|
|
155
|
+
assert.equal(h["X-ZCode-Agent"], "glm");
|
|
156
|
+
assert.equal(h["HTTP-Referer"], "https://zcode.z.ai");
|
|
157
|
+
assert.equal(h["X-Release-Channel"], "production");
|
|
158
|
+
assert.equal(h["X-Device-Mid"], IDENTITY.deviceMid);
|
|
159
|
+
assert.ok(h["X-Platform"] && h["X-Platform"].includes("-"));
|
|
160
|
+
assert.ok(h["X-Client-Language"], "locale header present");
|
|
161
|
+
assert.ok(h["X-Client-Timezone"], "timezone header present");
|
|
162
|
+
assert.ok(h["X-Os-Category"] && h["X-Os-Version"]);
|
|
163
|
+
// printable-ASCII gate: unprintable appVersion → header dropped, UA falls back
|
|
164
|
+
const bad = buildZcodeIdentityHeaders({ ...IDENTITY, appVersion: "bad\u0007bell" });
|
|
165
|
+
assert.equal(bad["User-Agent"], "ZCode/unknown");
|
|
166
|
+
assert.equal(bad["X-ZCode-App-Version"], undefined);
|
|
167
|
+
// env override wins (resolveZcodeIdentity applies it before header build)
|
|
168
|
+
const prev = process.env.ZCODE_IDENTITY_APP_VERSION;
|
|
169
|
+
process.env.ZCODE_IDENTITY_APP_VERSION = "9.9.9";
|
|
170
|
+
try {
|
|
171
|
+
assert.equal(resolveZcodeIdentity().appVersion, "9.9.9");
|
|
172
|
+
} finally {
|
|
173
|
+
if (prev === undefined) delete process.env.ZCODE_IDENTITY_APP_VERSION;
|
|
174
|
+
else process.env.ZCODE_IDENTITY_APP_VERSION = prev;
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("resolveZcodeIdentity: appVersion default and non-secret deviceMid present", () => {
|
|
179
|
+
const id = resolveZcodeIdentity();
|
|
180
|
+
assert.match(id.appVersion, /^[\x20-\x7e]+$/);
|
|
181
|
+
assert.ok(id.deviceMid && id.deviceMid.length >= 32, "deviceMid is a UUID");
|
|
182
|
+
assert.equal(id.refererOrigin, "https://zcode.z.ai");
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("PoW: candidate solves 8 leading zero bits and matches nonce+counter shape", async () => {
|
|
186
|
+
const pow = await createProofOfWork("abc123", "sess_x", "1700000000000");
|
|
187
|
+
assert.match(pow, /^[0-9a-f]{24}[0-9a-f]{8}$/, "12-byte nonce hex + 4-byte counter hex");
|
|
188
|
+
// Re-derive: seed + candidate digest must have 8 leading zero bits.
|
|
189
|
+
const { createHash } = await import("node:crypto");
|
|
190
|
+
const seed = createHash("sha256").update("abc123\nzcode\nsess_x\n1700000000000", "utf8").digest("hex").slice(0, 32);
|
|
191
|
+
const digest = createHash("sha256").update(`${seed}\n${pow}`, "utf8").digest();
|
|
192
|
+
assert.equal(digest[0], 0, "8 leading zero bits = first byte zero");
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it("signing happy path: gate probe + handshake once, all 7 headers, sig verifies with fixture pubkey, PoW valid", async () => {
|
|
196
|
+
const { fetchImpl, calls, getPrivateKey } = makeFetch({ gateEnabled: true });
|
|
197
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
198
|
+
const headers = await signedHeaders(manager); // signed with handshake #1's key
|
|
199
|
+
for (const name of ["X-Client-Ts", "X-Client-Version", "X-Client-Sig", "X-Session-Id", "X-Client-Nonce", "X-App-Id", "X-Client-Pow"]) {
|
|
200
|
+
assert.ok(headers[name], `${name} present`);
|
|
201
|
+
}
|
|
202
|
+
assert.equal(headers["X-App-Id"], "zcode");
|
|
203
|
+
assert.equal(headers["X-Session-Id"], "sess_test_0001");
|
|
204
|
+
assert.equal(headers["X-Client-Version"], "3.10.2");
|
|
205
|
+
assert.ok(!("x-session-id" in headers), "lowercase copy replaced by canonical X-Session-Id");
|
|
206
|
+
|
|
207
|
+
// gate + handshake: once per (origin, credential) state; cached afterwards
|
|
208
|
+
assert.equal(calls.gateCount, 1);
|
|
209
|
+
assert.equal(calls.handshakeCount, 1);
|
|
210
|
+
assert.ok(calls.urls[0].startsWith("https://zcode.z.ai/api/v1/agent/configs"));
|
|
211
|
+
// handshake plane is host-fixed to api.z.ai (live-verified: 404 on zcode.z.ai)
|
|
212
|
+
assert.ok(calls.urls[1].startsWith("https://api.z.ai/api/paas/c1f3a7e2/v2/client"));
|
|
213
|
+
await signedHeaders(manager, URL_ULTRA); // cached — no extra network
|
|
214
|
+
assert.equal(calls.gateCount + calls.handshakeCount, 2, "gate+handshake cached per credential");
|
|
215
|
+
|
|
216
|
+
// Verify the business signature with the fixture's public key.
|
|
217
|
+
const apiKeyId = CRED.credential.split(".")[0];
|
|
218
|
+
const message = `${apiKeyId}\n${headers["X-Client-Ts"]}\n3.10.2\nsess_test_0001\n${headers["X-Client-Nonce"]}`;
|
|
219
|
+
const verifyKey = await publicFromPrivate(getPrivateKey(0)!);
|
|
220
|
+
const ok = await crypto.subtle.verify(
|
|
221
|
+
"Ed25519",
|
|
222
|
+
verifyKey,
|
|
223
|
+
Buffer.from(headers["X-Client-Sig"]!, "base64"),
|
|
224
|
+
Buffer.from(message, "utf8"),
|
|
225
|
+
);
|
|
226
|
+
assert.ok(ok, "Ed25519 signature verifies with the handshake-issued key");
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("fail-open: gate disabled → untouched headers", async () => {
|
|
230
|
+
const { fetchImpl, calls } = makeFetch({ gateEnabled: false });
|
|
231
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
232
|
+
const headers = baseHeaders();
|
|
233
|
+
const signed = await manager.sign(URL_ULTRA, headers, CRED);
|
|
234
|
+
assert.equal(signed, false);
|
|
235
|
+
assert.deepEqual(Object.keys(headers).sort(), Object.keys(baseHeaders()).sort());
|
|
236
|
+
assert.equal(calls.gateCount, 1);
|
|
237
|
+
assert.equal(calls.handshakeCount, 0);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("fail-open: gate fetch throws → unsigned, negative-cached (immediate 2nd call no refetch)", async () => {
|
|
241
|
+
const { fetchImpl, calls } = makeFetch({ gateEnabled: true, gateThrows: true });
|
|
242
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
243
|
+
const headers = baseHeaders();
|
|
244
|
+
assert.equal(await manager.sign(URL_ULTRA, headers, CRED), false);
|
|
245
|
+
assert.equal(await manager.sign(URL_ULTRA, headers, CRED), false);
|
|
246
|
+
assert.equal(calls.gateCount, 1, "cooldown prevents refetch");
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("fail-open: handshake 500 → unsigned", async () => {
|
|
250
|
+
const { fetchImpl } = makeFetch({ gateEnabled: true, handshakeStatus: 500 });
|
|
251
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
252
|
+
const headers = baseHeaders();
|
|
253
|
+
assert.equal(await manager.sign(URL_ULTRA, headers, CRED), false);
|
|
254
|
+
assert.ok(!headers["X-Client-Sig"]);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it("unsigned paths and non-https are never signed", async () => {
|
|
258
|
+
const { fetchImpl, calls } = makeFetch({ gateEnabled: true });
|
|
259
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
260
|
+
assert.equal(await manager.sign(URL_START_PLAN, baseHeaders(), CRED), false);
|
|
261
|
+
assert.equal(await manager.sign("http://zcode.z.ai/api/v1/ultra-zai/anthropic/v1/messages", baseHeaders(), CRED), false);
|
|
262
|
+
assert.equal(calls.gateCount, 0, "no network before eligibility checks");
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it("missing x-session-id → skipped (client's own rule)", async () => {
|
|
266
|
+
const { fetchImpl, calls } = makeFetch({ gateEnabled: true });
|
|
267
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
268
|
+
const headers = baseHeaders();
|
|
269
|
+
delete headers["x-session-id"];
|
|
270
|
+
assert.equal(await manager.sign(URL_ULTRA, headers, CRED), false);
|
|
271
|
+
assert.equal(calls.gateCount, 0);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it("single-part credential → skipped", async () => {
|
|
275
|
+
const { fetchImpl, calls } = makeFetch({ gateEnabled: true });
|
|
276
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
277
|
+
assert.equal(await manager.sign(URL_ULTRA, baseHeaders(), { credential: "legacy-key", appVersion: "3.10.2" }), false);
|
|
278
|
+
assert.equal(calls.gateCount, 0, "cheap local checks run before the network");
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
it("401 ladder: two consecutive 401s after signed requests → bypass", async () => {
|
|
282
|
+
const { fetchImpl } = makeFetch({ gateEnabled: true });
|
|
283
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
284
|
+
await signedHeaders(manager); // sign #1
|
|
285
|
+
manager.noteResponse401(); // 401 after sign #1 → count 1 + invalidate
|
|
286
|
+
await signedHeaders(manager, URL_ULTRA); // re-handshake, sign #2
|
|
287
|
+
manager.noteResponse401(); // 401 after sign #2 → count 2 → bypass
|
|
288
|
+
const headers = baseHeaders();
|
|
289
|
+
assert.equal(await manager.sign(URL_ULTRA, headers, CRED), false, "bypassed after 2 consecutive 401s");
|
|
290
|
+
assert.ok(!headers["X-Client-Sig"]);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it("401 ladder: an intervening success resets the count (consecutive semantics)", async () => {
|
|
294
|
+
const { fetchImpl } = makeFetch({ gateEnabled: true });
|
|
295
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
296
|
+
await signedHeaders(manager);
|
|
297
|
+
manager.noteResponse401(); // 401 #1
|
|
298
|
+
await signedHeaders(manager, URL_ULTRA);
|
|
299
|
+
manager.noteResponseOk(); // success between 401s
|
|
300
|
+
await signedHeaders(manager, URL_ULTRA);
|
|
301
|
+
manager.noteResponse401(); // 401 again — count back to 1, NOT bypass
|
|
302
|
+
await signedHeaders(manager, URL_ULTRA); // must still sign
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it("origin allowlist: non-z.ai base URL → unsigned, zero network (no credential egress)", async () => {
|
|
306
|
+
const { fetchImpl, calls } = makeFetch({ gateEnabled: true });
|
|
307
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
|
|
308
|
+
const headers = baseHeaders();
|
|
309
|
+
assert.equal(
|
|
310
|
+
await manager.sign("https://open.bigmodel.cn/api/anthropic/v1/messages", headers, CRED),
|
|
311
|
+
false,
|
|
312
|
+
"bigmodel origin never signed",
|
|
313
|
+
);
|
|
314
|
+
assert.equal(calls.gateCount + calls.handshakeCount, 0, "no fetch may carry the credential to the gate/handshake");
|
|
315
|
+
assert.ok(!headers["X-Client-Sig"]);
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it("handshake failure backs off: immediate retry does not re-attempt the handshake", async () => {
|
|
319
|
+
let calls = 0;
|
|
320
|
+
let gateUp = true;
|
|
321
|
+
const now = { t: 1_000_000_000_000 };
|
|
322
|
+
const fetchImpl: typeof fetch = async (input) => {
|
|
323
|
+
const url = String(input);
|
|
324
|
+
if (url.includes("/agent/configs")) return jsonResponse(gateUp ? GATE_ENABLED : GATE_DISABLED);
|
|
325
|
+
calls += 1;
|
|
326
|
+
return jsonResponse({ code: 500, msg: "boom" }, 500);
|
|
327
|
+
};
|
|
328
|
+
const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl, now: () => now.t });
|
|
329
|
+
const h1 = baseHeaders();
|
|
330
|
+
assert.equal(await manager.sign(URL_ULTRA, h1, CRED), false);
|
|
331
|
+
assert.equal(calls, 1);
|
|
332
|
+
const h2 = baseHeaders();
|
|
333
|
+
assert.equal(await manager.sign(URL_ULTRA, h2, CRED), false, "unsigned during cooldown");
|
|
334
|
+
assert.equal(calls, 1, "handshake not retried within cooldown");
|
|
335
|
+
now.t += 61_000; // advance past cooldown → retries
|
|
336
|
+
assert.equal(await manager.sign(URL_ULTRA, baseHeaders(), CRED), false, "still fails (500)");
|
|
337
|
+
assert.equal(calls, 2, "handshake retried after cooldown");
|
|
338
|
+
});
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
async function publicFromPrivate(privateKey: CryptoKey): Promise<CryptoKey> {
|
|
342
|
+
const jwk = (await crypto.subtle.exportKey("jwk", privateKey)) as JsonWebKey;
|
|
343
|
+
const { crv, kty, x, y } = jwk;
|
|
344
|
+
return await crypto.subtle.importKey("jwk", { crv, kty, x, y }, "Ed25519", true, ["verify"]);
|
|
345
|
+
}
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// Ported from pi-model-tools extensions/test/unit/zai-throttle.test.ts.
|
|
2
|
+
// Added: defaultThrottlePaths() honors PI_CODING_AGENT_DIR (ceulen resolves the
|
|
3
|
+
// agent dir through lib/registry.ts agentDirs(), not a hardcoded ~/.pi/agent),
|
|
4
|
+
// and throttleZaiDispatch accepts the settings-resolved intervalMs override.
|
|
5
|
+
// Dropped: readFile/none — all assertions preserved.
|
|
6
|
+
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
9
|
+
import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { after, describe, it } from "node:test";
|
|
13
|
+
import {
|
|
14
|
+
DEFAULT_MIN_INTERVAL_MS,
|
|
15
|
+
MIN_INTERVAL_ENV,
|
|
16
|
+
acquireLock,
|
|
17
|
+
defaultThrottlePaths,
|
|
18
|
+
throttleDispatch,
|
|
19
|
+
throttleZaiDispatch,
|
|
20
|
+
zaiThrottleIntervalMs,
|
|
21
|
+
} from "../lib/throttle.js";
|
|
22
|
+
|
|
23
|
+
interface Ctx {
|
|
24
|
+
dir: string;
|
|
25
|
+
statePath: string;
|
|
26
|
+
lockPath: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const tmpDirs: string[] = [];
|
|
30
|
+
|
|
31
|
+
after(async () => {
|
|
32
|
+
for (const dir of tmpDirs) await rm(dir, { recursive: true, force: true });
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
async function freshCtx(): Promise<Ctx> {
|
|
36
|
+
const dir = await mkdtemp(join(tmpdir(), "zai-throttle-"));
|
|
37
|
+
tmpDirs.push(dir);
|
|
38
|
+
return {
|
|
39
|
+
dir,
|
|
40
|
+
statePath: join(dir, "zai-anthropic-dispatch.json"),
|
|
41
|
+
lockPath: join(dir, ".zai-anthropic-dispatch.lock"),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Fake clock: sleep() advances now() so waits resolve instantly but stay observable. */
|
|
46
|
+
function fakeClock(start = 10_000) {
|
|
47
|
+
let t = start;
|
|
48
|
+
const slept: number[] = [];
|
|
49
|
+
return {
|
|
50
|
+
now: () => t,
|
|
51
|
+
slept,
|
|
52
|
+
sleep: async (ms: number) => {
|
|
53
|
+
slept.push(ms);
|
|
54
|
+
t += ms;
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe("zai-throttle interval config", () => {
|
|
60
|
+
it("defaults to 1000ms; explicit 0 disables; garbage falls back to default", () => {
|
|
61
|
+
assert.equal(zaiThrottleIntervalMs({}), DEFAULT_MIN_INTERVAL_MS);
|
|
62
|
+
assert.equal(zaiThrottleIntervalMs({ [MIN_INTERVAL_ENV]: "0" }), 0);
|
|
63
|
+
assert.equal(zaiThrottleIntervalMs({ [MIN_INTERVAL_ENV]: "2500" }), 2500);
|
|
64
|
+
assert.equal(zaiThrottleIntervalMs({ [MIN_INTERVAL_ENV]: "bogus" }), DEFAULT_MIN_INTERVAL_MS);
|
|
65
|
+
assert.equal(zaiThrottleIntervalMs({ [MIN_INTERVAL_ENV]: "-5" }), DEFAULT_MIN_INTERVAL_MS);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("defaultThrottlePaths lands both files in the agent dir", () => {
|
|
69
|
+
const paths = defaultThrottlePaths("/agents");
|
|
70
|
+
assert.equal(paths.statePath, join("/agents", "zai-anthropic-dispatch.json"));
|
|
71
|
+
assert.equal(paths.lockPath, join("/agents", ".zai-anthropic-dispatch.lock"));
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("defaultThrottlePaths() resolves through agentDirs() — PI_CODING_AGENT_DIR wins", () => {
|
|
75
|
+
const prev = process.env.PI_CODING_AGENT_DIR;
|
|
76
|
+
process.env.PI_CODING_AGENT_DIR = "/tmp/ceulen-zai-agent-dir";
|
|
77
|
+
try {
|
|
78
|
+
const paths = defaultThrottlePaths();
|
|
79
|
+
assert.equal(paths.statePath, join("/tmp/ceulen-zai-agent-dir", "zai-anthropic-dispatch.json"));
|
|
80
|
+
assert.equal(paths.lockPath, join("/tmp/ceulen-zai-agent-dir", ".zai-anthropic-dispatch.lock"));
|
|
81
|
+
} finally {
|
|
82
|
+
if (prev === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
83
|
+
else process.env.PI_CODING_AGENT_DIR = prev;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe("throttleDispatch", () => {
|
|
89
|
+
it("interval 0 → no-op, touches no files", async () => {
|
|
90
|
+
const c = await freshCtx();
|
|
91
|
+
const waited = await throttleDispatch({ intervalMs: 0, statePath: c.statePath, lockPath: c.lockPath });
|
|
92
|
+
assert.equal(waited, 0);
|
|
93
|
+
assert.equal(existsSync(c.statePath), false, "no state written");
|
|
94
|
+
assert.equal(existsSync(c.lockPath), false, "no lock left");
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("first dispatch claims immediately, records ts, releases the lock before returning", async () => {
|
|
98
|
+
const c = await freshCtx();
|
|
99
|
+
const clock = fakeClock();
|
|
100
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath, ...clock });
|
|
101
|
+
assert.equal(waited, 0, "no state file yet → no wait");
|
|
102
|
+
assert.deepEqual(clock.slept, [], "slept nothing");
|
|
103
|
+
const state = JSON.parse(await readFile(c.statePath, "utf-8"));
|
|
104
|
+
assert.equal(state.ts, 10_000);
|
|
105
|
+
assert.equal(existsSync(c.lockPath), false, "lock released even though no request ever ran");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("second dispatch inside the interval waits for the slot (claim held during sleep)", async () => {
|
|
109
|
+
const c = await freshCtx();
|
|
110
|
+
await writeFile(c.statePath, JSON.stringify({ ts: 10_000 }));
|
|
111
|
+
const clock = fakeClock(10_500); // 500ms after last slot, interval 1000 → wait 500
|
|
112
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath, ...clock });
|
|
113
|
+
assert.equal(waited, 500);
|
|
114
|
+
assert.deepEqual(clock.slept, [500]);
|
|
115
|
+
assert.equal(JSON.parse(await readFile(c.statePath, "utf-8")).ts, 11_000, "slot recorded after the wait");
|
|
116
|
+
assert.equal(existsSync(c.lockPath), false);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("dispatch past the interval does not wait", async () => {
|
|
120
|
+
const c = await freshCtx();
|
|
121
|
+
await writeFile(c.statePath, JSON.stringify({ ts: 10_000 }));
|
|
122
|
+
const clock = fakeClock(12_000); // 2s later, interval 1000 → free
|
|
123
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath, ...clock });
|
|
124
|
+
assert.equal(waited, 0);
|
|
125
|
+
assert.deepEqual(clock.slept, []);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("stale lock (crash mid-claim) is broken after 30s", async () => {
|
|
129
|
+
const c = await freshCtx();
|
|
130
|
+
await writeFile(c.lockPath, "99999");
|
|
131
|
+
const old = new Date(Date.now() - 40_000);
|
|
132
|
+
await utimes(c.lockPath, old, old);
|
|
133
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath });
|
|
134
|
+
assert.equal(waited, 0);
|
|
135
|
+
assert.equal(existsSync(c.lockPath), false, "stale lock broken and our claim released");
|
|
136
|
+
assert.ok(existsSync(c.statePath));
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("fail-open: unwritable state → returns 0, does not throw, lock still released", async () => {
|
|
140
|
+
const c = await freshCtx();
|
|
141
|
+
await mkdir(c.statePath); // state path is a directory → readFile AND writeFile both fail
|
|
142
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath });
|
|
143
|
+
assert.equal(waited, 0);
|
|
144
|
+
assert.equal(existsSync(c.lockPath), false, "no lock leak on fail-open");
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it("concurrent dispatches space out by the interval (real timers)", async () => {
|
|
148
|
+
const c = await freshCtx();
|
|
149
|
+
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
|
|
150
|
+
const t0 = Date.now();
|
|
151
|
+
// Queued claimants sleep while holding the mutex, so each waits ~one
|
|
152
|
+
// interval from ITS acquisition; total wall clock spans (N-1)×interval.
|
|
153
|
+
const waits = await Promise.all([
|
|
154
|
+
throttleDispatch({ intervalMs: 120, statePath: c.statePath, lockPath: c.lockPath, sleep }),
|
|
155
|
+
throttleDispatch({ intervalMs: 120, statePath: c.statePath, lockPath: c.lockPath, sleep }),
|
|
156
|
+
throttleDispatch({ intervalMs: 120, statePath: c.statePath, lockPath: c.lockPath, sleep }),
|
|
157
|
+
]);
|
|
158
|
+
const elapsed = Date.now() - t0;
|
|
159
|
+
waits.sort((a, b) => a - b);
|
|
160
|
+
assert.ok(elapsed >= 230, `three claims at 120ms interval must queue, took ${elapsed}ms`);
|
|
161
|
+
assert.equal(waits[0], 0, "first claimant goes immediately");
|
|
162
|
+
// Slot spacing is the invariant (pinned deterministically by the fake-clock
|
|
163
|
+
// tests above); per-claimant sleeps vary by poll timing (up to one 40ms
|
|
164
|
+
// poll cycle late to the mutex) — just require real queueing happened.
|
|
165
|
+
assert.ok(Math.max(...waits) >= 60, `queued claimants slept real intervals (${waits.join(", ")})`);
|
|
166
|
+
assert.equal(existsSync(c.lockPath), false, "lock released after all claims");
|
|
167
|
+
const ts1 = JSON.parse(await readFile(c.statePath, "utf-8")).ts as number;
|
|
168
|
+
assert.ok(Math.abs(ts1 - Date.now()) < 5_000, "state holds a fresh ts");
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
describe("review hardening: lock protocol defects", () => {
|
|
173
|
+
it("unremovable stale lock → fails fast after deadline (no hot loop), fail-open with onError", async () => {
|
|
174
|
+
const c = await freshCtx();
|
|
175
|
+
// A directory at the lock path: open(…,"wx") → EEXIST, but unlink → EISDIR forever.
|
|
176
|
+
await mkdir(c.lockPath);
|
|
177
|
+
const old = new Date(Date.now() - 40_000);
|
|
178
|
+
await utimes(c.lockPath, old, old);
|
|
179
|
+
const errors: Error[] = [];
|
|
180
|
+
const t0 = Date.now();
|
|
181
|
+
const waited = await throttleDispatch({
|
|
182
|
+
intervalMs: 1000,
|
|
183
|
+
statePath: c.statePath,
|
|
184
|
+
lockPath: c.lockPath,
|
|
185
|
+
pollMs: 5,
|
|
186
|
+
lockDeadlineMs: 150,
|
|
187
|
+
onError: (e) => errors.push(e),
|
|
188
|
+
});
|
|
189
|
+
const elapsed = Date.now() - t0;
|
|
190
|
+
assert.equal(waited, 0, "fail-open");
|
|
191
|
+
assert.ok(elapsed < 5_000, `must hit the deadline fast, took ${elapsed}ms (hot loop would hang)`);
|
|
192
|
+
assert.equal(errors.length, 1, "fail-open reported via onError");
|
|
193
|
+
assert.match(errors[0]!.message, /lock busy/);
|
|
194
|
+
assert.equal(existsSync(c.statePath), false, "nothing claimed");
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("future/corrupt ts (clock step-back) is ignored → immediate dispatch, not an hour-long nap", async () => {
|
|
198
|
+
const c = await freshCtx();
|
|
199
|
+
await writeFile(c.statePath, JSON.stringify({ ts: Date.now() + 3_600_000 }));
|
|
200
|
+
const t0 = Date.now();
|
|
201
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath });
|
|
202
|
+
assert.ok(Date.now() - t0 < 5_000, "returns within seconds");
|
|
203
|
+
assert.equal(waited, 0);
|
|
204
|
+
const ts = JSON.parse(await readFile(c.statePath, "utf-8")).ts as number;
|
|
205
|
+
assert.ok(Math.abs(ts - Date.now()) < 5_000, "state rewritten with a sane fresh ts");
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it("long wait naps in bounded holds and re-queues — never holds ≥ stale threshold (fake clock)", async () => {
|
|
209
|
+
const c = await freshCtx();
|
|
210
|
+
await writeFile(c.statePath, JSON.stringify({ ts: 10_000 }));
|
|
211
|
+
const clock = fakeClock(10_500); // wait = 19_500 > MAX_HOLD_MS(15_000) → 2 holds
|
|
212
|
+
const waited = await throttleDispatch({ intervalMs: 20_000, statePath: c.statePath, lockPath: c.lockPath, ...clock });
|
|
213
|
+
assert.equal(waited, 19_500);
|
|
214
|
+
assert.deepEqual(clock.slept, [15_000, 4_500], "first nap capped at MAX_HOLD_MS, remainder re-queued");
|
|
215
|
+
assert.equal(JSON.parse(await readFile(c.statePath, "utf-8")).ts, 30_000);
|
|
216
|
+
assert.equal(existsSync(c.lockPath), false);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("wrong-typed ts (string/object) is corrupt → immediate dispatch, no NaN/hot loop", async () => {
|
|
220
|
+
const c = await freshCtx();
|
|
221
|
+
await writeFile(c.statePath, JSON.stringify({ ts: "12345" }));
|
|
222
|
+
const clock = fakeClock();
|
|
223
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath, ...clock });
|
|
224
|
+
assert.equal(waited, 0, "string ts → dispatch now");
|
|
225
|
+
assert.deepEqual(clock.slept, []);
|
|
226
|
+
assert.equal(JSON.parse(await readFile(c.statePath, "utf-8")).ts, 10_000, "state rewritten with numeric ts");
|
|
227
|
+
|
|
228
|
+
await writeFile(c.statePath, JSON.stringify({ ts: { nested: true } }));
|
|
229
|
+
const clock2 = fakeClock();
|
|
230
|
+
const waited2 = await throttleDispatch({ intervalMs: 1000, statePath: c.statePath, lockPath: c.lockPath, ...clock2 });
|
|
231
|
+
assert.equal(waited2, 0, "object ts → dispatch now");
|
|
232
|
+
assert.deepEqual(clock2.slept, []);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("fresh agent dir (missing parents) is created before the lock is claimed", async () => {
|
|
236
|
+
const root = await mkdtemp(join(tmpdir(), "zai-throttle-fresh-"));
|
|
237
|
+
const statePath = join(root, "does", "not", "exist", "zai-anthropic-dispatch.json");
|
|
238
|
+
const lockPath = join(root, "does", "not", "exist", ".zai-anthropic-dispatch.lock");
|
|
239
|
+
try {
|
|
240
|
+
const waited = await throttleDispatch({ intervalMs: 1000, statePath, lockPath });
|
|
241
|
+
assert.equal(waited, 0);
|
|
242
|
+
assert.ok(existsSync(statePath), "state written — throttle is not a permanent silent no-op");
|
|
243
|
+
assert.equal(existsSync(lockPath), false);
|
|
244
|
+
} finally {
|
|
245
|
+
await rm(root, { recursive: true, force: true });
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("release() deletes only OUR lock, never a stale-breaker's replacement", async () => {
|
|
250
|
+
const c = await freshCtx();
|
|
251
|
+
const lock = await acquireLock(c.lockPath, () => 0, (ms) => new Promise((r) => setTimeout(r, ms)));
|
|
252
|
+
// Simulate a stale-breaker replacing our lock while we "hold" it.
|
|
253
|
+
await writeFile(c.lockPath, "OTHER-PID");
|
|
254
|
+
await lock.release();
|
|
255
|
+
assert.equal(existsSync(c.lockPath), true, "foreign lock preserved");
|
|
256
|
+
await rm(c.lockPath, { force: true });
|
|
257
|
+
|
|
258
|
+
const mine = await acquireLock(c.lockPath, () => 0, (ms) => new Promise((r) => setTimeout(r, ms)));
|
|
259
|
+
assert.equal(existsSync(c.lockPath), true);
|
|
260
|
+
await mine.release();
|
|
261
|
+
assert.equal(existsSync(c.lockPath), false, "our own lock is removed");
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it("second claim after a big-interval slot waits another full interval — no stale-break cascade (fake clock)", async () => {
|
|
265
|
+
const c = await freshCtx();
|
|
266
|
+
await writeFile(c.statePath, JSON.stringify({ ts: 10_000 }));
|
|
267
|
+
const clock = fakeClock(10_000);
|
|
268
|
+
// Claim 1: wait 20_000 in two capped holds (proves re-looping under MAX_HOLD_MS).
|
|
269
|
+
const first = await throttleDispatch({ intervalMs: 20_000, statePath: c.statePath, lockPath: c.lockPath, ...clock });
|
|
270
|
+
assert.equal(first, 20_000);
|
|
271
|
+
// Claim 2 joins AFTER the big slot: must wait its own full interval
|
|
272
|
+
// (two more capped holds), never inherit/break anything.
|
|
273
|
+
const second = await throttleDispatch({ intervalMs: 20_000, statePath: c.statePath, lockPath: c.lockPath, ...clock });
|
|
274
|
+
assert.equal(second, 20_000);
|
|
275
|
+
assert.deepEqual(clock.slept, [15_000, 5_000, 15_000, 5_000]);
|
|
276
|
+
assert.equal(JSON.parse(await readFile(c.statePath, "utf-8")).ts, 50_000, "slot = previous slot + interval");
|
|
277
|
+
assert.equal(existsSync(c.lockPath), false);
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
describe("throttleZaiDispatch wiring", () => {
|
|
282
|
+
it("non-zai-anthropic provider → no-op even with default interval", async () => {
|
|
283
|
+
const c = await freshCtx();
|
|
284
|
+
const waited = await throttleZaiDispatch("openrouter", {}, { statePath: c.statePath, lockPath: c.lockPath });
|
|
285
|
+
assert.equal(waited, 0);
|
|
286
|
+
assert.equal(existsSync(c.statePath), false);
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
it("undefined provider → no-op", async () => {
|
|
290
|
+
const c = await freshCtx();
|
|
291
|
+
const waited = await throttleZaiDispatch(undefined, {}, { statePath: c.statePath, lockPath: c.lockPath });
|
|
292
|
+
assert.equal(waited, 0);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it("zai-anthropic provider claims a slot using env interval", async () => {
|
|
296
|
+
const c = await freshCtx();
|
|
297
|
+
await writeFile(c.statePath, JSON.stringify({ ts: 10_000 }));
|
|
298
|
+
const waited = await throttleZaiDispatch(
|
|
299
|
+
"ZAI-Anthropic", // case-insensitive, matches provider gating elsewhere
|
|
300
|
+
{ [MIN_INTERVAL_ENV]: "700" },
|
|
301
|
+
{ statePath: c.statePath, lockPath: c.lockPath },
|
|
302
|
+
);
|
|
303
|
+
void waited; // real timers; ts in the past → likely no wait — the assertion is that the gate RAN
|
|
304
|
+
assert.ok(existsSync(c.statePath), "state written for zai-anthropic provider");
|
|
305
|
+
await stat(c.statePath); // readable
|
|
306
|
+
assert.equal(existsSync(c.lockPath), false);
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
it("settings-resolved intervalMs override wins over the env default (0 = gate off)", async () => {
|
|
310
|
+
const c = await freshCtx();
|
|
311
|
+
const waited = await throttleZaiDispatch(
|
|
312
|
+
"zai-anthropic",
|
|
313
|
+
{ [MIN_INTERVAL_ENV]: "700" },
|
|
314
|
+
{ statePath: c.statePath, lockPath: c.lockPath },
|
|
315
|
+
{ intervalMs: 0 },
|
|
316
|
+
);
|
|
317
|
+
assert.equal(waited, 0);
|
|
318
|
+
assert.equal(existsSync(c.statePath), false, "interval 0 → the gate never touches the state file");
|
|
319
|
+
|
|
320
|
+
const waited2 = await throttleZaiDispatch(
|
|
321
|
+
"zai-anthropic",
|
|
322
|
+
{ [MIN_INTERVAL_ENV]: "0" },
|
|
323
|
+
{ statePath: c.statePath, lockPath: c.lockPath },
|
|
324
|
+
{ intervalMs: 1000 },
|
|
325
|
+
);
|
|
326
|
+
assert.equal(waited2, 0);
|
|
327
|
+
assert.ok(existsSync(c.statePath), "explicit 1000 overrides the env's 0");
|
|
328
|
+
});
|
|
329
|
+
});
|