pi-advisor-flow 0.12.1-dev.1 → 0.12.1-dev.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-advisor-flow",
3
- "version": "0.12.1-dev.1",
3
+ "version": "0.12.1-dev.3",
4
4
  "description": "Advanced Executor/Advisor flow for Pi, fully configurable and extendable.",
5
5
  "keywords": [
6
6
  "advisor",
@@ -22,6 +22,7 @@
22
22
  "dist",
23
23
  "extensions",
24
24
  "src",
25
+ "scripts/check-bun-version.mjs",
25
26
  "CHANGELOG.md",
26
27
  "LICENSE",
27
28
  "README.md"
@@ -42,12 +43,13 @@
42
43
  "lint:fix": "oxlint --fix",
43
44
  "prepack": "bun run build >/dev/null",
44
45
  "package:check": "node scripts/check-package.mjs",
46
+ "preinstall": "node scripts/check-bun-version.mjs",
45
47
  "prepare": "husky",
46
48
  "socket": "bunx socket optimize",
47
49
  "test": "bun test && bun run test:node-loader",
48
50
  "test:bench": "bun --config=./bunfig.bench.toml test ./bench/test/",
49
51
  "test:node-loader": "node --test test/default-resource-loader.node.mjs",
50
- "typecheck": "tsc --noEmit",
52
+ "typecheck": "bun check",
51
53
  "format:check": "oxfmt --check"
52
54
  },
53
55
  "devDependencies": {
@@ -55,11 +57,11 @@
55
57
  "@earendil-works/pi-coding-agent": "1.1.0",
56
58
  "@earendil-works/pi-tui": "1.1.0",
57
59
  "@oxlint/plugins": "1.87.0",
58
- "@types/node": "^26.6.4",
60
+ "@types/node": "^26.6.5",
59
61
  "@typesafe-ai/sdk": "^0.6.0",
60
- "bun-types": "1.4.2",
62
+ "bun-types": "1.4.3",
61
63
  "husky": "^9.1.7",
62
- "knip": "6.40.0",
64
+ "knip": "6.41.0",
63
65
  "lint-staged": "^17.6.0",
64
66
  "oxfmt": "0.72.0",
65
67
  "oxlint": "1.87.0",
@@ -107,6 +109,7 @@
107
109
  "oxfmt"
108
110
  ]
109
111
  },
112
+ "packageManager": "bun@1.4.3",
110
113
  "pi": {
111
114
  "extensions": [
112
115
  "./dist/index.js"
@@ -0,0 +1,67 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const projectRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));
6
+ if (!existsSync(resolve(projectRoot, "bun.lock"))) {
7
+ process.exit(0);
8
+ }
9
+
10
+ const localPrefix = process.env.npm_config_local_prefix;
11
+ if (localPrefix && resolve(localPrefix) !== projectRoot) {
12
+ process.exit(0);
13
+ }
14
+
15
+ const packageJson = JSON.parse(
16
+ readFileSync(resolve(projectRoot, "package.json"), "utf-8")
17
+ );
18
+ const minimumVersion = /^bun@(?<version>\d+\.\d+\.\d+)$/u.exec(
19
+ packageJson.packageManager ?? ""
20
+ )?.groups?.version;
21
+ const currentVersion = /^bun\/(?<version>[^\s]+)/u.exec(
22
+ process.env.npm_config_user_agent ?? ""
23
+ )?.groups?.version;
24
+
25
+ const isAtLeast = (version, minimum) => {
26
+ const current =
27
+ /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[^\s]+))?$/u.exec(
28
+ version
29
+ )?.groups;
30
+ const required =
31
+ /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[^\s]+))?$/u.exec(
32
+ minimum
33
+ )?.groups;
34
+ if (!current || !required) {
35
+ return false;
36
+ }
37
+
38
+ const currentParts = [current.major, current.minor, current.patch].map(
39
+ Number
40
+ );
41
+ const requiredParts = [required.major, required.minor, required.patch].map(
42
+ Number
43
+ );
44
+ for (let index = 0; index < currentParts.length; index += 1) {
45
+ const difference = currentParts[index] - requiredParts[index];
46
+ if (difference !== 0) {
47
+ return difference > 0;
48
+ }
49
+ }
50
+
51
+ return !current.prerelease || Boolean(required.prerelease);
52
+ };
53
+
54
+ if (
55
+ !minimumVersion ||
56
+ !currentVersion ||
57
+ !isAtLeast(currentVersion, minimumVersion)
58
+ ) {
59
+ console.error(
60
+ `This repository requires Bun ${minimumVersion ?? "1.4.3"} or newer; found ${currentVersion ?? "a non-Bun package manager"}.`
61
+ );
62
+ process.exitCode = 1;
63
+ } else {
64
+ console.log(
65
+ `Bun ${currentVersion} meets the repository minimum ${minimumVersion}.`
66
+ );
67
+ }
@@ -1,3 +1,5 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
1
3
  import {
2
4
  alwaysOnRef,
3
5
  getAdvisorSettings,
@@ -8,8 +10,10 @@ import { saveConfig } from "../config/storage.ts";
8
10
  import {
9
11
  resolveJevTransport,
10
12
  resolveJevTransportFor,
13
+ resolveTypesafeCompatibleCredentials,
11
14
  } from "../jev/transport.ts";
12
15
  import { AdvisorSettingsSelector } from "../ui/settings-selector.ts";
16
+ import type { AdvisorSettings } from "../ui/types.ts";
13
17
  import { loadCommandConfig } from "./activation-preparation.ts";
14
18
  import {
15
19
  CONTEXT_PRESETS,
@@ -20,6 +24,31 @@ import { notify } from "./runtime.ts";
20
24
  import { saveAdvisorSettings } from "./settings-persistence.ts";
21
25
  import type { CommandRuntime } from "./types.ts";
22
26
 
27
+ const persistJevSettings = (
28
+ ctx: ExtensionContext,
29
+ settings: AdvisorSettings,
30
+ runtime: CommandRuntime
31
+ ): boolean => {
32
+ try {
33
+ saveAdvisorSettings(ctx, settings, { skipOutcomeLogging: true });
34
+ } catch (error) {
35
+ const message = error instanceof Error ? error.message : String(error);
36
+ ctx.ui.notify(`Could not save Advisor settings: ${message}`, "error");
37
+ return false;
38
+ }
39
+ try {
40
+ runtime.updateSameModelNotice(ctx);
41
+ runtime.updateAdvisorUsageStatus(ctx);
42
+ } catch (error) {
43
+ const message = error instanceof Error ? error.message : String(error);
44
+ ctx.ui.notify(
45
+ `Advisor settings were saved, but the status refresh failed: ${message}`,
46
+ "warning"
47
+ );
48
+ }
49
+ return true;
50
+ };
51
+
23
52
  export const registerSettingsCommands = (runtime: CommandRuntime) => {
24
53
  runtime.pi.registerCommand("advisor-settings", {
25
54
  description: "Configure Advisor settings",
@@ -35,6 +64,8 @@ export const registerSettingsCommands = (runtime: CommandRuntime) => {
35
64
  effortLevels: EFFORT_LEVELS,
36
65
  initial,
37
66
  jevSetupDeps: {
67
+ resolveEndpoint: (options) =>
68
+ resolveTypesafeCompatibleCredentials(options, ctx),
38
69
  resolveTransport: (transport) =>
39
70
  transport
40
71
  ? resolveJevTransportFor(transport, ctx)
@@ -57,39 +88,10 @@ export const registerSettingsCommands = (runtime: CommandRuntime) => {
57
88
  );
58
89
  }
59
90
  },
60
- onJevSetup: (selection, settings) => {
61
- try {
62
- saveAdvisorSettings(
63
- ctx,
64
- {
65
- ...settings,
66
- jevFilterEnabled: selection.enabled,
67
- jevTransport: selection.transport,
68
- },
69
- { skipOutcomeLogging: true }
70
- );
71
- } catch (error) {
72
- const message =
73
- error instanceof Error ? error.message : String(error);
74
- ctx.ui.notify(
75
- `Could not save Advisor settings: ${message}`,
76
- "error"
77
- );
78
- return false;
79
- }
80
- try {
81
- runtime.updateSameModelNotice(ctx);
82
- runtime.updateAdvisorUsageStatus(ctx);
83
- } catch (error) {
84
- const message =
85
- error instanceof Error ? error.message : String(error);
86
- ctx.ui.notify(
87
- `Advisor settings were saved, but the status refresh failed: ${message}`,
88
- "warning"
89
- );
90
- }
91
- return true;
92
- },
91
+ onJevFilter: (_selection, settings) =>
92
+ persistJevSettings(ctx, settings, runtime),
93
+ onJevProvider: (_selection, settings) =>
94
+ persistJevSettings(ctx, settings, runtime),
93
95
  presets: CONTEXT_PRESETS,
94
96
  theme,
95
97
  tui,
@@ -18,10 +18,12 @@ import {
18
18
  setAdvisorGitContextRef,
19
19
  setAdvisorHerdrIntegrationRef,
20
20
  setAdvisorJevDigestMaxCharsRef,
21
+ setAdvisorJevBaseUrlRef,
21
22
  setAdvisorJevFilterEnabledRef,
22
23
  setAdvisorJevFilterNoulMarginRef,
23
24
  setAdvisorJevFilterOverrideWindowRef,
24
25
  setAdvisorJevFilterSkipConfidenceRef,
26
+ setAdvisorJevKeyProviderRef,
25
27
  setAdvisorJevModelRef,
26
28
  setAdvisorJevPricePerMtokRef,
27
29
  setAdvisorJevTimeoutMsRef,
@@ -96,6 +98,8 @@ const applySessionSettings = (settings: AdvisorSettings) => {
96
98
 
97
99
  const applyJevSettings = (settings: AdvisorSettings) => {
98
100
  setAdvisorJevFilterEnabledRef(settings.jevFilterEnabled ?? false);
101
+ setAdvisorJevBaseUrlRef(settings.jevBaseUrl);
102
+ setAdvisorJevKeyProviderRef(settings.jevKeyProvider);
99
103
  setAdvisorJevFilterSkipConfidenceRef(
100
104
  settings.jevFilterSkipConfidence ?? DEFAULT_JEV_FILTER_SKIP_CONFIDENCE
101
105
  );
@@ -13,10 +13,12 @@ import {
13
13
  setAdvisorGitContextRef,
14
14
  setAdvisorHerdrIntegrationRef,
15
15
  setAdvisorJevDigestMaxCharsRef,
16
+ setAdvisorJevBaseUrlRef,
16
17
  setAdvisorJevFilterEnabledRef,
17
18
  setAdvisorJevFilterNoulMarginRef,
18
19
  setAdvisorJevFilterOverrideWindowRef,
19
20
  setAdvisorJevFilterSkipConfidenceRef,
21
+ setAdvisorJevKeyProviderRef,
20
22
  setAdvisorJevModelRef,
21
23
  setAdvisorJevPricePerMtokRef,
22
24
  setAdvisorJevTimeoutMsRef,
@@ -93,6 +95,8 @@ export const resetDefaults = () => {
93
95
  setAdvisorFailureModeRef("block-session");
94
96
  setAdvisorHerdrIntegrationRef(true);
95
97
  setAdvisorJevModelRef(DEFAULT_JEV_MODEL);
98
+ setAdvisorJevBaseUrlRef(undefined);
99
+ setAdvisorJevKeyProviderRef(undefined);
96
100
  setAdvisorJevFilterEnabledRef(false);
97
101
  setAdvisorJevFilterSkipConfidenceRef(DEFAULT_JEV_FILTER_SKIP_CONFIDENCE);
98
102
  setAdvisorJevFilterNoulMarginRef(DEFAULT_JEV_FILTER_NOUL_MARGIN);
@@ -238,6 +242,12 @@ export const applyConfig = (config: AdvisorConfig) => {
238
242
  setAdvisorJevFilterOverrideWindowRef
239
243
  );
240
244
  applyNonEmptyStringConfig(config.advisorJevModel, setAdvisorJevModelRef);
245
+ applyOptionalConfig(config, "advisorJevBaseUrl", setAdvisorJevBaseUrlRef);
246
+ applyOptionalConfig(
247
+ config,
248
+ "advisorJevKeyProvider",
249
+ setAdvisorJevKeyProviderRef
250
+ );
241
251
  applyOptionalConfig(config, "advisorJevTimeoutMs", setAdvisorJevTimeoutMsRef);
242
252
  applyOptionalConfig(
243
253
  config,
@@ -1,6 +1,7 @@
1
1
  import { isString } from "../content-utils.ts";
2
2
  import type { JsonValue } from "../content-utils.ts";
3
3
  import { GIT_CONTEXT_LEVELS, isValidGitContextLevel } from "../git.ts";
4
+ import { normalizeJevBaseUrl } from "../jev/base-url.ts";
4
5
  import {
5
6
  advisorAgentsMdContextRef,
6
7
  advisorAutoLoopGateRef,
@@ -16,11 +17,13 @@ import {
16
17
  advisorGitContextMaxCharsRef,
17
18
  advisorGitContextRef,
18
19
  advisorHerdrIntegrationRef,
20
+ advisorJevBaseUrlRef,
19
21
  advisorJevDigestMaxCharsRef,
20
22
  advisorJevFilterEnabledRef,
21
23
  advisorJevFilterNoulMarginRef,
22
24
  advisorJevFilterOverrideWindowRef,
23
25
  advisorJevFilterSkipConfidenceRef,
26
+ advisorJevKeyProviderRef,
24
27
  advisorJevModelRef,
25
28
  advisorJevPricePerMtokRef,
26
29
  advisorJevTimeoutMsRef,
@@ -150,6 +153,14 @@ const JEV_TRANSPORT_NAMES = new Set<string>(JEV_TRANSPORTS);
150
153
  export const isValidJevTransport = (value: unknown): value is JevTransport =>
151
154
  isString(value) && JEV_TRANSPORT_NAMES.has(value);
152
155
 
156
+ /** An empty value clears the endpoint; anything else must be a usable Base URL. */
157
+ export const isValidJevBaseUrl = (value: unknown): value is string =>
158
+ isString(value) &&
159
+ (value.trim() === "" || normalizeJevBaseUrl(value).baseUrl !== undefined);
160
+
161
+ export const isValidJevKeyProvider = (value: unknown): value is string =>
162
+ isString(value) && (value.trim() === "" || !/\s/u.test(value.trim()));
163
+
153
164
  /** One declarative entry per AdvisorConfig key: JSON type, persistence, and
154
165
  * the live runtime value behind it. Validation and storage derive from this
155
166
  * table; adding a setting means adding exactly one entry here. */
@@ -162,7 +173,7 @@ export interface ConfigKeySchema {
162
173
  persisted: boolean;
163
174
  /** JSON value type used for the base type check. */
164
175
  type: "string" | "boolean" | "number" | "enum" | "object" | "array";
165
- /** Type beyond the JSON type, for enum and object keys. */
176
+ /** Type beyond the JSON type; honoured for every schema type, not only enum and object. */
166
177
  validate?: (value: unknown) => value is JsonValue;
167
178
  }
168
179
 
@@ -253,6 +264,14 @@ export const CONFIG_SCHEMA = {
253
264
  persisted: true,
254
265
  type: "boolean",
255
266
  },
267
+ advisorJevBaseUrl: {
268
+ accepted:
269
+ "a System One–compatible Base URL over https, or over http on a loopback host",
270
+ current: () => advisorJevBaseUrlRef,
271
+ persisted: true,
272
+ type: "string",
273
+ validate: isValidJevBaseUrl,
274
+ },
256
275
  advisorJevDigestMaxChars: {
257
276
  accepted: "a non-negative safe integer",
258
277
  current: () => advisorJevDigestMaxCharsRef,
@@ -287,6 +306,13 @@ export const CONFIG_SCHEMA = {
287
306
  type: "number",
288
307
  validate: isValidJevSkipConfidence,
289
308
  },
309
+ advisorJevKeyProvider: {
310
+ accepted: "a Pi provider id whose stored login supplies the endpoint key",
311
+ current: () => advisorJevKeyProviderRef,
312
+ persisted: true,
313
+ type: "string",
314
+ validate: isValidJevKeyProvider,
315
+ },
290
316
  advisorJevModel: {
291
317
  accepted: "a non-empty string",
292
318
  current: () => advisorJevModelRef,
@@ -58,6 +58,8 @@ export let advisorJevModelRef = DEFAULT_JEV_MODEL;
58
58
  export let advisorJevTimeoutMsRef = DEFAULT_JEV_TIMEOUT_MS;
59
59
  export let advisorJevDigestMaxCharsRef = DEFAULT_JEV_DIGEST_MAX_CHARS;
60
60
  export let advisorJevPricePerMtokRef = DEFAULT_JEV_PRICE_PER_MTOK;
61
+ export let advisorJevBaseUrlRef: string | undefined;
62
+ export let advisorJevKeyProviderRef: string | undefined;
61
63
  export let advisorJevTransportRef: JevTransport = DEFAULT_JEV_TRANSPORT;
62
64
  export let advisorJevTurnGateEveryTurnsRef = DEFAULT_JEV_TURN_GATE_EVERY_TURNS;
63
65
  export let advisorJevTurnGateNoulThresholdRef =
@@ -188,6 +190,12 @@ export const setAdvisorJevDigestMaxCharsRef = (value: number) => {
188
190
  export const setAdvisorJevPricePerMtokRef = (value: number) => {
189
191
  advisorJevPricePerMtokRef = value;
190
192
  };
193
+ export const setAdvisorJevBaseUrlRef = (value: string | undefined) => {
194
+ advisorJevBaseUrlRef = value?.trim() || undefined;
195
+ };
196
+ export const setAdvisorJevKeyProviderRef = (value: string | undefined) => {
197
+ advisorJevKeyProviderRef = value?.trim() || undefined;
198
+ };
191
199
  export const setAdvisorJevTransportRef = (value: JevTransport) => {
192
200
  advisorJevTransportRef = value;
193
201
  };
@@ -258,11 +266,13 @@ export const getAdvisorSettings = () => ({
258
266
  gitContext: advisorGitContextRef,
259
267
  gitContextMaxChars: advisorGitContextMaxCharsRef,
260
268
  herdrIntegration: advisorHerdrIntegrationRef,
269
+ jevBaseUrl: advisorJevBaseUrlRef,
261
270
  jevDigestMaxChars: advisorJevDigestMaxCharsRef,
262
271
  jevFilterEnabled: advisorJevFilterEnabledRef,
263
272
  jevFilterNoulMargin: advisorJevFilterNoulMarginRef,
264
273
  jevFilterOverrideWindow: advisorJevFilterOverrideWindowRef,
265
274
  jevFilterSkipConfidence: advisorJevFilterSkipConfidenceRef,
275
+ jevKeyProvider: advisorJevKeyProviderRef,
266
276
  jevModel: advisorJevModelRef,
267
277
  jevPricePerMtok: advisorJevPricePerMtokRef,
268
278
  jevTimeoutMs: advisorJevTimeoutMsRef,
@@ -36,13 +36,15 @@ export type JevTransport =
36
36
  | "auto"
37
37
  | "typesafe"
38
38
  | "openrouter"
39
- | "openai-decisions";
39
+ | "openai-decisions"
40
+ | "typesafe-compatible";
40
41
  export const DEFAULT_JEV_TRANSPORT: JevTransport = "auto";
41
42
  export const JEV_TRANSPORTS: JevTransport[] = [
42
43
  "auto",
43
44
  "typesafe",
44
45
  "openrouter",
45
46
  "openai-decisions",
47
+ "typesafe-compatible",
46
48
  ];
47
49
 
48
50
  export type AdvisorToolPolicy = "full" | "summary" | "exclude";
@@ -78,11 +80,13 @@ export interface AdvisorConfig {
78
80
  advisorGitContext?: GitContextLevel;
79
81
  advisorGitContextMaxChars?: number;
80
82
  advisorHerdrIntegration?: boolean;
83
+ advisorJevBaseUrl?: string;
81
84
  advisorJevDigestMaxChars?: number;
82
85
  advisorJevFilterEnabled?: boolean;
83
86
  advisorJevFilterNoulMargin?: number;
84
87
  advisorJevFilterOverrideWindow?: number;
85
88
  advisorJevFilterSkipConfidence?: number;
89
+ advisorJevKeyProvider?: string;
86
90
  advisorJevModel?: string;
87
91
  advisorJevPricePerMtok?: number;
88
92
  advisorJevTimeoutMs?: number;
@@ -21,9 +21,6 @@ const CONFIG_KEYS = new Set<string>(configKeys);
21
21
  const keysOfType = (type: ConfigKeySchema["type"]): readonly ConfigKey[] =>
22
22
  configKeys.filter((key) => SCHEMA_BY_KEY[key].type === type);
23
23
 
24
- const BOOLEAN_CONFIG_KEYS = keysOfType("boolean");
25
- const STRING_CONFIG_KEYS = keysOfType("string");
26
-
27
24
  type ConfigRecord = Record<string, JsonValue>;
28
25
 
29
26
  const invalidConfigValue = (
@@ -39,70 +36,26 @@ const invalidConfigValue = (
39
36
  export const unknownConfigKeys = (config: AdvisorConfig) =>
40
37
  Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
41
38
 
42
- const validateStringValues = (config: ConfigRecord, path: string) => {
43
- for (const key of STRING_CONFIG_KEYS) {
44
- if (config[key] !== undefined && !isString(config[key])) {
45
- invalidConfigValue(path, key, SCHEMA_BY_KEY[key].accepted);
46
- }
47
- }
48
- };
49
-
50
- const validateBooleanValues = (config: ConfigRecord, path: string) => {
51
- for (const key of BOOLEAN_CONFIG_KEYS) {
52
- if (config[key] !== undefined && !isBoolean(config[key])) {
53
- invalidConfigValue(path, key, SCHEMA_BY_KEY[key].accepted);
54
- }
55
- }
56
- };
57
-
58
- const validateNumericValues = (config: ConfigRecord, path: string) => {
59
- for (const key of keysOfType("number")) {
60
- const isValid = SCHEMA_BY_KEY[key].validate;
61
- if (
62
- config[key] !== undefined &&
63
- isValid !== undefined &&
64
- !isValid(config[key])
65
- ) {
66
- invalidConfigValue(path, key, SCHEMA_BY_KEY[key].accepted);
67
- }
68
- }
69
- };
70
-
71
- const validateArrayValues = (config: ConfigRecord, path: string) => {
72
- for (const key of keysOfType("array")) {
73
- const isValid = SCHEMA_BY_KEY[key].validate;
74
- if (
75
- config[key] !== undefined &&
76
- isValid !== undefined &&
77
- !isValid(config[key])
78
- ) {
79
- invalidConfigValue(path, key, SCHEMA_BY_KEY[key].accepted);
39
+ const validateValues = (
40
+ config: ConfigRecord,
41
+ path: string,
42
+ type: ConfigKeySchema["type"]
43
+ ) => {
44
+ for (const key of keysOfType(type)) {
45
+ const value = config[key];
46
+ if (value === undefined) {
47
+ continue;
80
48
  }
81
- }
82
- };
83
-
84
- const validateEnumValues = (config: ConfigRecord, path: string) => {
85
- for (const key of keysOfType("enum")) {
86
- const isValid = SCHEMA_BY_KEY[key].validate;
87
- if (
88
- config[key] !== undefined &&
89
- isValid !== undefined &&
90
- !isValid(config[key])
91
- ) {
92
- invalidConfigValue(path, key, SCHEMA_BY_KEY[key].accepted);
49
+ const schema = SCHEMA_BY_KEY[key];
50
+ if (type === "string" || type === "boolean") {
51
+ const matchesType =
52
+ type === "string" ? isString(value) : isBoolean(value);
53
+ if (!matchesType) {
54
+ invalidConfigValue(path, key, schema.accepted);
55
+ }
93
56
  }
94
- }
95
- };
96
-
97
- const validateObjectValues = (config: ConfigRecord, path: string) => {
98
- for (const key of keysOfType("object")) {
99
- const isValid = SCHEMA_BY_KEY[key].validate;
100
- if (
101
- config[key] !== undefined &&
102
- isValid !== undefined &&
103
- !isValid(config[key])
104
- ) {
105
- invalidConfigValue(path, key, SCHEMA_BY_KEY[key].accepted);
57
+ if (schema.validate && !schema.validate(value)) {
58
+ invalidConfigValue(path, key, schema.accepted);
106
59
  }
107
60
  }
108
61
  };
@@ -116,11 +69,11 @@ export const validateConfig = (
116
69
  `Invalid advisor configuration at ${path}: expected a JSON object.`
117
70
  );
118
71
  }
119
- validateStringValues(value, path);
120
- validateBooleanValues(value, path);
121
- validateNumericValues(value, path);
122
- validateObjectValues(value, path);
123
- validateArrayValues(value, path);
124
- validateEnumValues(value, path);
72
+ validateValues(value, path, "string");
73
+ validateValues(value, path, "boolean");
74
+ validateValues(value, path, "number");
75
+ validateValues(value, path, "object");
76
+ validateValues(value, path, "array");
77
+ validateValues(value, path, "enum");
125
78
  return true;
126
79
  };
@@ -73,6 +73,142 @@ export const cleanNotification = (value: string, max: number) =>
73
73
  .trim()
74
74
  .slice(0, max);
75
75
 
76
+ interface HerdrAttempt {
77
+ responded: boolean;
78
+ wrote: boolean;
79
+ }
80
+
81
+ interface QueuedReport {
82
+ endpoint: string;
83
+ request: HerdrRequest;
84
+ }
85
+
86
+ interface ReportQueue {
87
+ active: boolean;
88
+ reports: QueuedReport[];
89
+ }
90
+
91
+ const FIRST_ATTEMPT_TIMEOUT_MS = 500;
92
+ const RETRY_ATTEMPT_TIMEOUT_MS = 1500;
93
+ const MAX_PENDING_NOTIFICATIONS = 16;
94
+ const reportQueues = new Map<string, ReportQueue>();
95
+
96
+ const isMetadataRequest = (request: HerdrRequest) =>
97
+ request.method === "pane.report_metadata";
98
+
99
+ const reportQueueKey = (request: HerdrRequest) =>
100
+ isMetadataRequest(request) ? request.params.source : NOTIFICATION_SOURCE;
101
+
102
+ const sendRequestAttempt = (
103
+ endpoint: string,
104
+ request: HerdrRequest,
105
+ timeoutMs: number
106
+ ): Promise<HerdrAttempt> => {
107
+ const deferred = Promise.withResolvers<HerdrAttempt>();
108
+ let settled = false;
109
+ let wrote = false;
110
+ let timeout: ReturnType<typeof setTimeout> | undefined;
111
+ let socket: net.Socket | undefined;
112
+
113
+ const finish = (responded: boolean) => {
114
+ if (settled) {
115
+ return;
116
+ }
117
+ settled = true;
118
+ if (timeout) {
119
+ clearTimeout(timeout);
120
+ }
121
+ socket?.destroy();
122
+ deferred.resolve({ responded, wrote });
123
+ };
124
+
125
+ try {
126
+ socket = net.createConnection(endpoint);
127
+ socket.once("connect", () => {
128
+ wrote = true;
129
+ try {
130
+ socket?.write(`${JSON.stringify(request)}\n`);
131
+ } catch {
132
+ finish(false);
133
+ }
134
+ });
135
+ socket.once("data", () => finish(true));
136
+ socket.once("end", () => finish(false));
137
+ socket.once("error", () => finish(false));
138
+ socket.once("close", () => finish(false));
139
+ timeout = setTimeout(() => finish(false), timeoutMs);
140
+ timeout.unref?.();
141
+ } catch {
142
+ finish(false);
143
+ }
144
+ return deferred.promise;
145
+ };
146
+
147
+ const sendQueuedReport = async ({ endpoint, request }: QueuedReport) => {
148
+ const first = await sendRequestAttempt(
149
+ endpoint,
150
+ request,
151
+ FIRST_ATTEMPT_TIMEOUT_MS
152
+ );
153
+ if (first.responded) {
154
+ return;
155
+ }
156
+ if (!isMetadataRequest(request) && first.wrote) {
157
+ return;
158
+ }
159
+ await sendRequestAttempt(endpoint, request, RETRY_ATTEMPT_TIMEOUT_MS);
160
+ };
161
+
162
+ const drainReportQueue = async (key: string, queue: ReportQueue) => {
163
+ if (queue.active) {
164
+ return;
165
+ }
166
+ queue.active = true;
167
+ try {
168
+ while (queue.reports.length > 0) {
169
+ const report = queue.reports.shift();
170
+ if (report) {
171
+ try {
172
+ await sendQueuedReport(report);
173
+ } catch {
174
+ continue;
175
+ }
176
+ }
177
+ }
178
+ } finally {
179
+ queue.active = false;
180
+ if (queue.reports.length === 0) {
181
+ reportQueues.delete(key);
182
+ } else {
183
+ void drainReportQueue(key, queue);
184
+ }
185
+ }
186
+ };
187
+
188
+ const enqueueReport = (report: QueuedReport) => {
189
+ const key = reportQueueKey(report.request);
190
+ let queue = reportQueues.get(key);
191
+ if (!queue) {
192
+ queue = { active: false, reports: [] };
193
+ reportQueues.set(key, queue);
194
+ }
195
+ if (isMetadataRequest(report.request)) {
196
+ if (queue.active) {
197
+ queue.reports = [report];
198
+ } else {
199
+ queue.reports.push(report);
200
+ }
201
+ } else {
202
+ if (queue.reports.length >= MAX_PENDING_NOTIFICATIONS) {
203
+ return;
204
+ }
205
+ queue.reports.push(report);
206
+ }
207
+ if (!queue.active) {
208
+ void drainReportQueue(key, queue);
209
+ }
210
+ };
211
+
76
212
  export const sendToHerdr: Report = (request) => {
77
213
  if (process.env.HERDR_ENV !== "1") {
78
214
  return;
@@ -84,13 +220,7 @@ export const sendToHerdr: Report = (request) => {
84
220
  }
85
221
  const endpoint =
86
222
  process.platform === "win32" ? `\\\\.\\pipe\\${socketPath}` : socketPath;
87
- const socket = net.createConnection(endpoint);
88
- const timeout = setTimeout(() => socket.destroy(), 500);
89
- timeout.unref?.();
90
- socket.once("connect", () => socket.write(`${JSON.stringify(request)}\n`));
91
- socket.once("data", () => socket.destroy());
92
- socket.once("error", () => socket.destroy());
93
- socket.once("close", () => clearTimeout(timeout));
223
+ enqueueReport({ endpoint, request });
94
224
  };
95
225
 
96
226
  export const createHerdrNotificationRequest = (