spur-board 0.130.0 → 0.131.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.
@@ -1,5 +1,5 @@
1
- import { bt as plainHttpAllowed, d as buildCatalogSnapshot, p as OPERATIONS, vt as configSchema } from "./chunk-CgQL6u77.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-2vFOidpZ.mjs";
1
+ import { bt as plainHttpAllowed, d as buildCatalogSnapshot, p as OPERATIONS, vt as configSchema } from "./chunk-CY_rWPWy.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-DfehZM2s.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
@@ -3054,6 +3054,7 @@ const defaultBranchViewSchema = z.strictObject({
3054
3054
  const sourceViewSchema = z.strictObject({
3055
3055
  pointsLastHour: z.int().nonnegative().optional().describe("Reported source points consumed during the preceding hour."),
3056
3056
  source: z.string().min(1).describe("Adapter source identifier."),
3057
+ project: z.string().min(1).nullable().describe("Board project whose tracker or repository this source polls; null for the shared spur source."),
3057
3058
  observedAt: z.iso.datetime().nullable().describe("Time of the latest observation, if any."),
3058
3059
  lastCompleteAt: z.iso.datetime().nullable().describe("Time of the latest complete observation."),
3059
3060
  blindReason: z.enum([
@@ -3068,6 +3069,7 @@ const sourceViewSchema = z.strictObject({
3068
3069
  resetAt: z.iso.datetime().describe("When the source said it restores the full budget.")
3069
3070
  }).nullable().describe("Request budget from the last poll of this source that reported one, or null when none did."),
3070
3071
  stale: z.boolean().describe("Whether facts from this source exceed their freshness threshold."),
3072
+ waitsForBudget: z.boolean().describe("Whether the daemon's adapter runner has put off this source's next regular poll for a rate limit: the last regular poll in this daemon run either reported a budget under github.reserveRemaining (GitHub sources, complete or not) or failed as throttled, with or without a retry time (any source), or failed in any other way while the last budget a poll of this run reported, an on-demand refresh included, is under github.reserveRemaining with a future reset (this case also ends at that reset), and the paused poll has not started yet. Held in memory, so false after a restart until a poll pauses again; a stored budget or an on-demand refresh never sets it."),
3071
3073
  healthySince: z.iso.datetime().nullable().describe("When this source became usable (not blind) in this daemon run: its first non-blind observation since daemon start or since it was last blind. Stale, warming-up or budget-wait spells that did not make it blind do not move it. Null while blind or before that observation. Resets when the daemon restarts; compare with daemon.startedAt."),
3072
3074
  warmingUp: z.boolean().describe("Whether this source needs a complete poll in this daemon run."),
3073
3075
  defaultBranch: defaultBranchViewSchema.nullable().optional().describe("GitHub pull request sources only: the default-branch colour, red when the latest check run of a push-triggered workflow finished without success (failed, cancelled, timed out) or a commit status failed (scheduled and other runs ignored, branch protection not read); null until a poll reads it.")
@@ -3267,16 +3269,16 @@ const serviceSchema = z.strictObject({
3267
3269
  reason: z.string().nullable().describe("Why the service is not healthy, from its first worst source for github, jira and spur; null when healthy.")
3268
3270
  }).describe("Health of one service.");
3269
3271
  const statusInputSchema = z.strictObject({
3270
- project: project$1,
3272
+ project: z.string().min(1).max(256).optional().describe("Project to limit the answer to, except sources and services, which always cover every project the caller may see; absent means every project the caller may see."),
3271
3273
  detail: z.boolean().optional().describe("Include full ticket, pull request and session facts; absent means compact rows.")
3272
3274
  });
3273
3275
  const statusOutputSchema = z.strictObject({
3274
3276
  items: z.array(statusItemSchema).describe("Actionable items in priority order."),
3275
- warmingUp: z.boolean().describe("Whether required sources still need a complete poll."),
3277
+ warmingUp: z.boolean().describe("Whether a source of the requested projects or spur still needs a complete poll."),
3276
3278
  spurUnavailable: z.string().nullable().describe("One combined Spur availability line, or null when available."),
3277
3279
  hostLoad: z.string().nullable().describe("Host-load episode line, or null when absent."),
3278
3280
  host: hostSchema,
3279
- services: z.array(serviceSchema).describe("One health row per service: daemon, each chat gateway, then github, spur and jira when sources lists one. Daemon and gateway rows are board-wide; source services roll up only the sources listed."),
3281
+ services: z.array(serviceSchema).describe("One health row per service: daemon, each chat gateway, then github, spur and jira when sources lists one. Daemon and gateway rows are board-wide; source services roll up the sources listed, which cover every project the caller may see whatever project says."),
3280
3282
  transport: z.array(z.strictObject({
3281
3283
  gateway: z.string().min(1).describe("Chat gateway kind."),
3282
3284
  state: z.enum(["up", "down"]).describe("down while delivery to any space of the gateway is suspended."),
@@ -3284,7 +3286,7 @@ const statusOutputSchema = z.strictObject({
3284
3286
  reason: z.string().nullable().describe("Reason of the earliest outage, or null when up."),
3285
3287
  spaces: z.array(z.enum(SPACE_IDS)).describe("Spaces whose delivery is suspended.")
3286
3288
  }).describe("Transport health of one gateway.")).describe("Transport health of each chat gateway."),
3287
- sources: z.array(sourceViewSchema).describe("Freshness and availability of each source."),
3289
+ sources: z.array(sourceViewSchema).describe("Freshness and availability of each source of every project the caller may see, whatever project says, with spur first."),
3288
3290
  tasks: z.array(statusTaskSchema).describe("Tasks with state, turn, PR summary arrays and navigation; full facts with detail."),
3289
3291
  columnGroups: z.array(z.strictObject({
3290
3292
  id: z.enum(COLUMN_GROUPS).describe("Column group."),
@@ -1,4 +1,4 @@
1
- import { _ as renderJsonError, at as errorContextSchema, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, o as tokenRequestResultSchema, ot as errorEnvelopeSchema, rt as ERRORS } from "./chunk-CgQL6u77.mjs";
1
+ import { _ as renderJsonError, at as errorContextSchema, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, o as tokenRequestResultSchema, ot as errorEnvelopeSchema, rt as ERRORS } from "./chunk-CY_rWPWy.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { D as sortSkillFiles, Ot as SLACK_BOT_SCOPES, Q as actorIdSchema, St as resolveWebOrigin, T as skillReloadFileSchema, a as requestHashOf, ct as successEnvelopeSchema, f as roleCanUseOperation, p as OPERATIONS, pt as DEFAULT_STAND_PORT_RANGE, r as remoteDoctorReportSchema, rt as ERRORS, u as SYSTEMD_SERVICE_SETTINGS, vt as configSchema, xt as requiredSecretKeys } from "./chunk-CgQL6u77.mjs";
1
+ import { D as sortSkillFiles, Ot as SLACK_BOT_SCOPES, Q as actorIdSchema, St as resolveWebOrigin, T as skillReloadFileSchema, a as requestHashOf, ct as successEnvelopeSchema, f as roleCanUseOperation, p as OPERATIONS, pt as DEFAULT_STAND_PORT_RANGE, r as remoteDoctorReportSchema, rt as ERRORS, u as SYSTEMD_SERVICE_SETTINGS, vt as configSchema, xt as requiredSecretKeys } from "./chunk-CY_rWPWy.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
- import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-2vFOidpZ.mjs";
4
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-B9WekLbU.mjs";
3
+ import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-DfehZM2s.mjs";
4
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-BUWlIiQd.mjs";
5
5
  import { createHash, randomBytes, randomUUID } from "node:crypto";
6
6
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
7
7
  import { homedir, hostname, tmpdir, userInfo } from "node:os";
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-2vFOidpZ.mjs";
1
+ export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-DfehZM2s.mjs";
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as encodeActorId, A as eventPayloadSchemas, At as TODO_GROUP_COLUMN_IDS, B as REVIEW_STATES, C as messageRefSchema, Ct as COLUMNS, D as sortSkillFiles, Dt as ITEM_KINDS, E as skillReloadFilesSchema, Et as DISPATCHER_MODES, F as prSourceId, G as prFactsSchema, H as SESSION_STATUSES, I as sessionTransitionSchema, J as sessionFactsSchema, K as prRefSchema, L as sourceCursorSchema, M as batchSchema, Mt as isTodoGroupColumn, N as defaultBranchFactSchema, O as EVENT_KINDS, Ot as SLACK_BOT_SCOPES, P as entityRefSchema, Q as actorIdSchema, R as trackerSourceId, S as interactionRefSchema, St as resolveWebOrigin, Tt as COLUMN_IDS, U as isExternalAuthor, V as SESSION_HEALTH_STATES, W as parseRingMarker, X as JIRA_PROJECT_KEY, Y as ticketFactsSchema, Z as REF_NUMBER, _t as configBindings, a as requestHashOf, b as conversationRefSchema, bt as plainHttpAllowed, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, d as buildCatalogSnapshot, et as errorCodeOf, f as roleCanUseOperation, ft as DEFAULT_SLACK_COMMAND, g as renderHttpProblem, gt as columnTurnTimings, h as turnHandedSchema, ht as boardWideSpurProject, i as TOKEN_REQUEST_LIMITS, it as err, j as AdapterError, jt as VIAS, k as GATE_REASONS, kt as TASK_HOLDS, l as BOARD_TICK_MS, m as defaultBranchViewSchema, mt as RESERVED_PROJECT, n as doctorReportSchema, nt as parseRef$1, o as tokenRequestResultSchema, p as OPERATIONS, q as ringMarker, rt as ERRORS, s as tokenRequestSchema, st as ok, t as assertNever, tt as parseActorId, ut as DEFAULT_LINK, vt as configSchema, w as userIdSchema, wt as COLUMN_GROUPS, x as inboundEventSchema, xt as requiredSecretKeys, y as SPACE_IDS, yt as defaultAddressee, z as PR_STATES } from "./chunk-CgQL6u77.mjs";
1
+ import { $ as encodeActorId, A as eventPayloadSchemas, At as TODO_GROUP_COLUMN_IDS, B as REVIEW_STATES, C as messageRefSchema, Ct as COLUMNS, D as sortSkillFiles, Dt as ITEM_KINDS, E as skillReloadFilesSchema, Et as DISPATCHER_MODES, F as prSourceId, G as prFactsSchema, H as SESSION_STATUSES, I as sessionTransitionSchema, J as sessionFactsSchema, K as prRefSchema, L as sourceCursorSchema, M as batchSchema, Mt as isTodoGroupColumn, N as defaultBranchFactSchema, O as EVENT_KINDS, Ot as SLACK_BOT_SCOPES, P as entityRefSchema, Q as actorIdSchema, R as trackerSourceId, S as interactionRefSchema, St as resolveWebOrigin, Tt as COLUMN_IDS, U as isExternalAuthor, V as SESSION_HEALTH_STATES, W as parseRingMarker, X as JIRA_PROJECT_KEY, Y as ticketFactsSchema, Z as REF_NUMBER, _t as configBindings, a as requestHashOf, b as conversationRefSchema, bt as plainHttpAllowed, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, d as buildCatalogSnapshot, et as errorCodeOf, f as roleCanUseOperation, ft as DEFAULT_SLACK_COMMAND, g as renderHttpProblem, gt as columnTurnTimings, h as turnHandedSchema, ht as boardWideSpurProject, i as TOKEN_REQUEST_LIMITS, it as err, j as AdapterError, jt as VIAS, k as GATE_REASONS, kt as TASK_HOLDS, l as BOARD_TICK_MS, m as defaultBranchViewSchema, mt as RESERVED_PROJECT, n as doctorReportSchema, nt as parseRef$1, o as tokenRequestResultSchema, p as OPERATIONS, q as ringMarker, rt as ERRORS, s as tokenRequestSchema, st as ok, t as assertNever, tt as parseActorId, ut as DEFAULT_LINK, vt as configSchema, w as userIdSchema, wt as COLUMN_GROUPS, x as inboundEventSchema, xt as requiredSecretKeys, y as SPACE_IDS, yt as defaultAddressee, z as PR_STATES } from "./chunk-CY_rWPWy.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -16512,7 +16512,7 @@ function pickTime(values, pick) {
16512
16512
  return chosen;
16513
16513
  }
16514
16514
  /** One source's health: failing when blind, degraded while not fully usable, else healthy. */
16515
- function sourceHealth(source, config, now) {
16515
+ function sourceHealth(source) {
16516
16516
  if (source.blindReason !== null) {
16517
16517
  const message = source.message === null ? "" : `: ${source.message}`;
16518
16518
  return {
@@ -16524,11 +16524,10 @@ function sourceHealth(source, config, now) {
16524
16524
  state: "degraded",
16525
16525
  reason
16526
16526
  });
16527
+ if (source.waitsForBudget) return degraded(`${source.source} waits for its rate budget`);
16527
16528
  if (source.lastCompleteAt === null) return degraded(`${source.source} ${source.warmingUp ? "warming up" : "never completed"}`);
16528
16529
  if (source.stale) return degraded(`${source.source} stale`);
16529
16530
  if (source.warmingUp) return degraded(`${source.source} warming up`);
16530
- const { budget } = source;
16531
- if (source.source.startsWith("github") && budget !== null && budget.remaining < config.github.reserveRemaining && Date.parse(budget.resetAt) > now) return degraded(`${source.source} waits for its rate budget until ${budget.resetAt}`);
16532
16531
  return {
16533
16532
  state: "healthy",
16534
16533
  reason: null
@@ -16539,7 +16538,7 @@ function sourceHealth(source, config, now) {
16539
16538
  * rolled up from the given sources only.
16540
16539
  */
16541
16540
  function services(input) {
16542
- const { config, now, daemon } = input;
16541
+ const { now, daemon } = input;
16543
16542
  const lastTick = daemon.lastDispatchAt ?? daemon.startedAt;
16544
16543
  const stalled = now - Date.parse(lastTick) > DAEMON_STALL_MS;
16545
16544
  const rows = [{
@@ -16572,7 +16571,7 @@ function services(input) {
16572
16571
  ]) {
16573
16572
  const members = input.sources.filter((source) => SOURCE_SERVICES[source.source.split(":")[0] ?? ""] === service);
16574
16573
  if (members.length === 0) continue;
16575
- const worst = members.map((source) => sourceHealth(source, config, now)).reduce((a, b) => STATE_RANK[b.state] > STATE_RANK[a.state] ? b : a);
16574
+ const worst = members.map(sourceHealth).reduce((a, b) => STATE_RANK[b.state] > STATE_RANK[a.state] ? b : a);
16576
16575
  rows.push({
16577
16576
  service,
16578
16577
  state: worst.state,
@@ -16811,7 +16810,8 @@ async function getStatus(deps, options = {}) {
16811
16810
  const { project: projectId, visibleProjects, detail = false } = options;
16812
16811
  const includeBoardItems = options.includeBoardItems ?? visibleProjects === void 0;
16813
16812
  const operatorProjects = options.operatorProjects ?? /* @__PURE__ */ new Set();
16814
- const projects = projectId === void 0 ? config.projects.filter((project) => visibleProjects === void 0 || visibleProjects.has(project.id)) : config.projects.filter((project) => project.id === projectId && (visibleProjects === void 0 || visibleProjects.has(project.id)));
16813
+ const visible = config.projects.filter((project) => visibleProjects === void 0 || visibleProjects.has(project.id));
16814
+ const projects = projectId === void 0 ? visible : visible.filter((project) => project.id === projectId);
16815
16815
  if (projects.length === 0) throw new CommandError("not_found", "Check the project ID.");
16816
16816
  const projectIds = new Set(projects.map((project) => project.id));
16817
16817
  const rows = await store.db.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
@@ -16969,16 +16969,19 @@ async function getStatus(deps, options = {}) {
16969
16969
  health
16970
16970
  };
16971
16971
  });
16972
- const required = /* @__PURE__ */ new Set(["spur", ...projects.flatMap((project) => [trackerSourceId(project), ...project.repos.map((repo) => prSourceId(project.id, repo))])]);
16972
+ const sourceIds = (scope) => /* @__PURE__ */ new Set(["spur", ...scope.flatMap((project) => [trackerSourceId(project), ...project.repos.map((repo) => prSourceId(project.id, repo))])]);
16973
+ const required = sourceIds(projects);
16974
+ const boardSources = sourceIds(visible);
16973
16975
  const costs = await store.db.selectFrom("source_cost").select(["source", "points"]).where("at", ">", (/* @__PURE__ */ new Date(clock.now() - 36e5)).toISOString()).where("at", "<=", new Date(clock.now()).toISOString()).execute();
16974
16976
  const points = /* @__PURE__ */ new Map();
16975
16977
  for (const cost of costs) points.set(cost.source, (points.get(cost.source) ?? 0) + cost.points);
16976
- const sources = [...required].map((source) => {
16978
+ const sources = [...boardSources].map((source) => {
16977
16979
  const row = sourceById.get(source);
16978
16980
  const last = row?.last_complete_at ?? null;
16979
16981
  const blindReason = row?.blind_reason === "auth" || row?.blind_reason === "config" || row?.blind_reason === "stale" ? row.blind_reason : null;
16980
16982
  return {
16981
16983
  source,
16984
+ project: projectForSource(config, source)?.id ?? null,
16982
16985
  ...source.startsWith("github:") && {
16983
16986
  pointsLastHour: points.get(source) ?? 0,
16984
16987
  defaultBranch: parseDefaultBranch(row?.default_branch)
@@ -16992,6 +16995,7 @@ async function getStatus(deps, options = {}) {
16992
16995
  limit: row.budget_limit,
16993
16996
  resetAt: row.budget_reset_at
16994
16997
  } : null,
16998
+ waitsForBudget: deps.budgetWaits?.has(source) ?? false,
16995
16999
  stale: last === null || clock.now() - Date.parse(last) > config.thresholds.staleMultiplier * sourceInterval(config, source),
16996
17000
  healthySince: deps.healthySince?.get(source) ?? null,
16997
17001
  warmingUp: !completeSince.has(source)
@@ -17047,12 +17051,11 @@ async function getStatus(deps, options = {}) {
17047
17051
  });
17048
17052
  return {
17049
17053
  items,
17050
- warmingUp: sources.some((source) => source.warmingUp),
17054
+ warmingUp: sources.some((source) => required.has(source.source) && source.warmingUp),
17051
17055
  spurUnavailable: spur?.blind_reason === null || spur === void 0 ? null : `Spur unavailable: ${spur.blind_message ?? spur.blind_reason}`,
17052
17056
  hostLoad: host?.value !== void 0 && host.value !== "null" ? "Host under load" : null,
17053
17057
  host: deps.host ?? null,
17054
17058
  services: services({
17055
- config,
17056
17059
  now: clock.now(),
17057
17060
  daemon,
17058
17061
  transport,
@@ -18919,6 +18922,7 @@ function createOperationRegistry(deps) {
18919
18922
  lastDispatchAt: lastDispatchAt()
18920
18923
  },
18921
18924
  healthySince: deps.healthySince,
18925
+ budgetWaits: deps.budgetWaits?.(),
18922
18926
  host: deps.hostMetrics?.()
18923
18927
  }, {
18924
18928
  project: input.project,
@@ -24102,27 +24106,34 @@ function throttledRetryAt(error) {
24102
24106
  /** The wait before the next poll and the new failure count. */
24103
24107
  function nextDelay(input) {
24104
24108
  const { outcome, intervalMs, failures, now } = input;
24105
- if (outcome.kind === "delivered") return {
24106
- delayMs: budgetPause(outcome.budget, input.reserveRemaining, intervalMs, now) ?? jitter(intervalMs),
24107
- failures: 0
24108
- };
24109
+ if (outcome.kind === "delivered") {
24110
+ const pause = budgetPause(outcome.budget, input.reserveRemaining, intervalMs, now);
24111
+ return {
24112
+ delayMs: pause ?? jitter(intervalMs),
24113
+ failures: 0,
24114
+ budgetWait: pause !== void 0
24115
+ };
24116
+ }
24109
24117
  const { error } = outcome;
24110
24118
  if (error instanceof AdapterError) {
24111
24119
  if (error.kind === "auth" || error.kind === "config") return {
24112
24120
  delayMs: jitter(input.authRetryMs),
24113
- failures
24121
+ failures,
24122
+ budgetWait: false
24114
24123
  };
24115
24124
  const retryAt = throttledRetryAt(error);
24116
24125
  if (retryAt !== void 0) return {
24117
24126
  delayMs: Math.max(retryAt - now, intervalMs),
24118
- failures
24127
+ failures,
24128
+ budgetWait: true
24119
24129
  };
24120
24130
  }
24121
24131
  const next = failures + 1;
24122
24132
  const cap = Math.max(MAX_BACKOFF_MS, intervalMs);
24123
24133
  return {
24124
24134
  delayMs: jitter(Math.min(intervalMs * 2 ** next, cap)),
24125
- failures: next
24135
+ failures: next,
24136
+ budgetWait: error instanceof AdapterError && error.kind === "throttled"
24126
24137
  };
24127
24138
  }
24128
24139
  /** The time after which a source without a new complete observation is blind stale. */
@@ -24216,9 +24227,11 @@ const MAX_TIMER_MS = 2147483647;
24216
24227
  const DEMAND_RETRY_WAITS_MS = [1e3, 2e3];
24217
24228
  function startRunner(options) {
24218
24229
  const startedAt = options.now();
24219
- const sources = options.entries.map((entry) => runSource(entry, options, startedAt));
24230
+ const budgetWaits = /* @__PURE__ */ new Set();
24231
+ const sources = options.entries.map((entry) => runSource(entry, options, startedAt, budgetWaits));
24220
24232
  const byId = new Map(sources.map((source) => [source.id, source]));
24221
24233
  return {
24234
+ budgetWaits,
24222
24235
  firstAttempts: Promise.all(sources.map(async (source) => ({
24223
24236
  source: source.id,
24224
24237
  outcome: await source.firstAttempt
@@ -24241,7 +24254,7 @@ const stoppedError = {
24241
24254
  kind: "stopped",
24242
24255
  message: "The adapter runner is stopping"
24243
24256
  };
24244
- function runSource(entry, options, runnerStartMs) {
24257
+ function runSource(entry, options, runnerStartMs, budgetWaits) {
24245
24258
  const { adapter, reserveRemaining } = entry;
24246
24259
  const { core, config } = options;
24247
24260
  const { now } = options;
@@ -24277,11 +24290,15 @@ function runSource(entry, options, runnerStartMs) {
24277
24290
  const pending = /* @__PURE__ */ new Set();
24278
24291
  /** Until when a regular throttled failure forbids calling the source. */
24279
24292
  let throttledUntilMs;
24293
+ /** The last budget a regular or on-demand poll of this run reported. */
24294
+ let lastBudget;
24280
24295
  /** Tail of the single-flight chain: regular polls and on-demand requests, one at a time. */
24281
24296
  let chain = Promise.resolve();
24282
24297
  let pollTimer;
24283
24298
  let deadlineTimer;
24284
24299
  let hardBoundTimer;
24300
+ /** Ends a remembered-budget wait at the budget's reset. */
24301
+ let waitTimer;
24285
24302
  let reports = Promise.resolve();
24286
24303
  let lastReported;
24287
24304
  function state() {
@@ -24353,10 +24370,24 @@ function runSource(entry, options, runnerStartMs) {
24353
24370
  chain = result.then(noop, noop);
24354
24371
  return result;
24355
24372
  }
24356
- function schedule(delayMs) {
24373
+ /**
24374
+ * Arms the next regular poll; `budgetWait` marks it as put off for the rate budget. With
24375
+ * `waitEndsAt`, the mark ends at that time even if the poll is due later.
24376
+ */
24377
+ function schedule(delayMs, budgetWait, waitEndsAt) {
24357
24378
  if (stopping) return;
24379
+ clearTimeout(waitTimer);
24380
+ waitTimer = void 0;
24381
+ if (budgetWait) budgetWaits.add(source);
24382
+ if (budgetWait && waitEndsAt !== void 0) waitTimer = setTimeout(() => {
24383
+ waitTimer = void 0;
24384
+ budgetWaits.delete(source);
24385
+ }, Math.min(Math.max(waitEndsAt - now(), 0), MAX_TIMER_MS));
24358
24386
  pollTimer = setTimeout(() => {
24359
24387
  pollTimer = void 0;
24388
+ clearTimeout(waitTimer);
24389
+ waitTimer = void 0;
24390
+ budgetWaits.delete(source);
24360
24391
  run(poll);
24361
24392
  }, Math.min(delayMs, MAX_TIMER_MS));
24362
24393
  }
@@ -24446,6 +24477,7 @@ function runSource(entry, options, runnerStartMs) {
24446
24477
  kind: "delivered",
24447
24478
  budget: parsed.data.budget
24448
24479
  };
24480
+ lastBudget = parsed.data.budget ?? lastBudget;
24449
24481
  }
24450
24482
  } catch (error) {
24451
24483
  if (aborted()) return;
@@ -24475,7 +24507,9 @@ function runSource(entry, options, runnerStartMs) {
24475
24507
  throttledUntilMs = outcome.kind === "failed" ? throttledRetryAt(outcome.error) : void 0;
24476
24508
  if (!options.oneShot) armDeadline();
24477
24509
  await report(usage);
24478
- if (!options.oneShot) schedule(delay.delayMs);
24510
+ const underReserve = reserveRemaining !== void 0 && lastBudget !== void 0 && lastBudget.remaining < reserveRemaining && Date.parse(lastBudget.resetAt) > now();
24511
+ const fallback = !delay.budgetWait && outcome.kind === "failed" && underReserve;
24512
+ if (!options.oneShot) schedule(delay.delayMs, delay.budgetWait || fallback, fallback && lastBudget !== void 0 ? Date.parse(lastBudget.resetAt) : void 0);
24479
24513
  return outcome;
24480
24514
  }
24481
24515
  /**
@@ -24568,6 +24602,7 @@ function runSource(entry, options, runnerStartMs) {
24568
24602
  counts = recoveredCounts;
24569
24603
  gone = recoveredGone;
24570
24604
  lastReported = JSON.stringify(committed);
24605
+ lastBudget = parsed.data.budget ?? lastBudget;
24571
24606
  return ok(value);
24572
24607
  });
24573
24608
  reports = accepted.then(noop, noop);
@@ -24661,7 +24696,9 @@ function runSource(entry, options, runnerStartMs) {
24661
24696
  clearTimeout(pollTimer);
24662
24697
  clearTimeout(deadlineTimer);
24663
24698
  clearTimeout(hardBoundTimer);
24664
- pollTimer = deadlineTimer = hardBoundTimer = void 0;
24699
+ clearTimeout(waitTimer);
24700
+ pollTimer = deadlineTimer = hardBoundTimer = waitTimer = void 0;
24701
+ budgetWaits.delete(source);
24665
24702
  controller?.abort();
24666
24703
  for (const cancel of [...pending]) cancel();
24667
24704
  await chain;
@@ -25113,6 +25150,7 @@ function startAdapters(config, core, options) {
25113
25150
  onFailure: options.onPollFailure
25114
25151
  });
25115
25152
  return {
25153
+ budgetWaits: runner.budgetWaits,
25116
25154
  firstAttempts: runner.firstAttempts,
25117
25155
  pollPr: runner.pollPr,
25118
25156
  async stop() {
@@ -26364,7 +26402,8 @@ function createJob(options) {
26364
26402
  * Compose the board's timer and adapter runner without adding lifecycle state to main. `tick`
26365
26403
  * runs the board-core job once more behind its active run and resolves when that run settles.
26366
26404
  * `pollPr` forwards to the running runner: `stopped` before its start and after its stop,
26367
- * `unsupported` for a runner without on-demand polls.
26405
+ * `unsupported` for a runner without on-demand polls. `budgetWaits` reads the running runner's
26406
+ * rate budget pauses, none before its start and after its stop.
26368
26407
  */
26369
26408
  function createBoardModules(ctxFor, options = {}) {
26370
26409
  const coreCtx = ctxFor("board-core");
@@ -26449,7 +26488,8 @@ function createBoardModules(ctxFor, options = {}) {
26449
26488
  return {
26450
26489
  entries,
26451
26490
  tick: () => boardCore.trigger(),
26452
- pollPr
26491
+ pollPr,
26492
+ budgetWaits: () => runner?.budgetWaits
26453
26493
  };
26454
26494
  }
26455
26495
  // ../daemon/src/host-metrics.ts
@@ -27613,6 +27653,7 @@ function createDaemonModules(ctxFor, ports = {}) {
27613
27653
  gateways: gateway === void 0 ? [] : [gateway.kind],
27614
27654
  reapplyInbound: () => inbound?.reapply,
27615
27655
  prPoller: () => boardModules.pollPr,
27656
+ budgetWaits: () => boardModules.budgetWaits(),
27616
27657
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
27617
27658
  lastDispatchAt: () => lastDispatchAt,
27618
27659
  webOrigin: () => webPort === void 0 ? void 0 : resolveWebOrigin(board.config.web, webPort)
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { p as OPERATIONS, rt as ERRORS, v as renderMcpError } from "./chunk-CgQL6u77.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-2vFOidpZ.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-B9WekLbU.mjs";
1
+ import { p as OPERATIONS, rt as ERRORS, v as renderMcpError } from "./chunk-CY_rWPWy.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-DfehZM2s.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-BUWlIiQd.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";