@staix/agent-hub 0.51.0 → 0.52.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 +35 -0
- package/README.md +1 -1
- package/docs/adding-an-ai-tool.md +24 -2
- package/docs/agent-notes/adapters.md +1 -0
- package/docs/agent-notes/budget.md +8 -2
- package/docs/agent-notes/daemon.md +13 -8
- package/docs/agent-notes/security-review.md +6 -5
- package/docs/agent-notes/tasks.md +5 -2
- package/docs/agent-notes/tests.md +4 -3
- package/docs/cooperbench.md +1 -1
- package/docs/design/adapters.md +4 -0
- package/docs/design/cli-output-inventory.md +162 -152
- package/docs/design/cli-output.md +4 -3
- package/docs/design/guidance-probes.md +1 -0
- package/docs/design/roadmap.md +2 -0
- package/docs/design/task-board.md +1 -0
- package/docs/dogfood.md +14 -0
- package/docs/events.md +4 -2
- package/docs/memory.md +5 -3
- package/docs/operations.md +210 -16
- package/docs/quickstart.md +12 -2
- package/docs/roles.md +1 -1
- package/docs/sdlc.md +26 -3
- package/docs/security.md +11 -5
- package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
- package/docs/specs/2026-09-19-multi-project-design.md +4 -0
- package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
- package/docs/specs/mcp-endpoint.md +63 -0
- package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
- package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
- package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
- package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
- package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
- package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
- package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
- package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
- package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
- package/docs/verification/2026-12-03-0.52.0.md +150 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
- package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
- package/docs/verification/agy/README.md +17 -0
- package/docs/verification/agy/cli-surface.ts +68 -0
- package/docs/verification/agy/interactive-bridge.ts +92 -0
- package/docs/verification/agy/interactive-session.ts +131 -0
- package/docs/verification/agy/launcher-nonce.ts +215 -0
- package/docs/verification/agy/native-hooks.ts +210 -0
- package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
- package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
- package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
- package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
- package/docs/verification/agy/originals.json +25 -0
- package/docs/verification/agy/permission-new-functions.ts +128 -0
- package/docs/verification/agy/run-probe.py +108 -0
- package/docs/verification/agy/runtime.ts +171 -0
- package/docs/verification/agy/tmux-helper-control.ts +6 -0
- package/docs/verification/agy/tmux-session.ts +235 -0
- package/docs/verified.json +82 -41
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/compat.json +157 -0
- package/plugins/agent-hub/kimi-hook.js +621 -865
- package/plugins/agent-hub/server.js +17423 -32962
- package/src/adapters/agy/definition.ts +7 -24
- package/src/adapters/channel-peer.ts +3 -1
- package/src/adapters/claude-channel.ts +38 -257
- package/src/adapters/claude-implementer.ts +3 -1
- package/src/adapters/codex-appserver.ts +77 -15
- package/src/adapters/compat.ts +74 -11
- package/src/adapters/configured-acp.ts +23 -163
- package/src/adapters/configured-adapter-policy.ts +160 -0
- package/src/adapters/configured-pull-entry.ts +53 -0
- package/src/adapters/configured-pull.ts +38 -0
- package/src/adapters/conformance/fakes/app-server.ts +9 -2
- package/src/adapters/declaration-catalog.ts +25 -0
- package/src/adapters/declaration-data.ts +342 -0
- package/src/adapters/declaration-resolution.ts +53 -0
- package/src/adapters/definitions/builtin-metadata.ts +61 -83
- package/src/adapters/definitions/jcode-launch.ts +13 -0
- package/src/adapters/definitions/native-adapter-policy.ts +390 -0
- package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
- package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
- package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
- package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
- package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
- package/src/adapters/definitions/native-cli-retained.ts +1 -1
- package/src/adapters/definitions/native-configuration.ts +18 -0
- package/src/adapters/definitions/native-help.ts +24 -0
- package/src/adapters/definitions/native-launch-declarations.ts +34 -0
- package/src/adapters/definitions/native-launch-policy.ts +4 -0
- package/src/adapters/definitions/native-launch-settings.ts +72 -0
- package/src/adapters/definitions/native-light-cli.ts +18 -0
- package/src/adapters/definitions/native-light-preview.ts +10 -0
- package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
- package/src/adapters/definitions/qwen.ts +6 -29
- package/src/adapters/definitions/reviewer-variants.ts +7 -8
- package/src/adapters/external-declarations.ts +31 -0
- package/src/adapters/external-modules.ts +4 -29
- package/src/adapters/jcode.ts +3 -12
- package/src/adapters/native-capabilities.ts +18 -8
- package/src/adapters/native-proof-ports.ts +1 -1
- package/src/adapters/presets.ts +136 -0
- package/src/adapters/qwen-dual.ts +2 -2
- package/src/adapters/registry-types.ts +3 -0
- package/src/adapters/registry.ts +20 -81
- package/src/adapters/reviewer-print.ts +26 -9
- package/src/adapters/role-eligibility.ts +2 -1
- package/src/cli/accounts-import.ts +72 -0
- package/src/cli/agents-latest-table.ts +88 -0
- package/src/cli/agents-latest.ts +22 -0
- package/src/cli/agents-output.ts +10 -0
- package/src/cli/agents-presets.ts +100 -0
- package/src/cli/agents.ts +1 -1
- package/src/cli/attention.ts +3 -2
- package/src/cli/autonomy-homes.ts +7 -2
- package/src/cli/budget-renew-guidance.ts +129 -0
- package/src/cli/claude-homes.ts +9 -5
- package/src/cli/command-context.ts +3 -0
- package/src/cli/command-table.ts +123 -0
- package/src/cli/commands/accounts.ts +8 -0
- package/src/cli/commands/agents.ts +18 -0
- package/src/cli/commands/answer.ts +28 -0
- package/src/cli/commands/ask.ts +17 -0
- package/src/cli/commands/autonomy.ts +83 -0
- package/src/cli/commands/backlog.ts +46 -0
- package/src/cli/commands/bench.ts +60 -0
- package/src/cli/commands/board.ts +48 -0
- package/src/cli/commands/broker.ts +9 -0
- package/src/cli/commands/budget.ts +96 -0
- package/src/cli/commands/capabilities.ts +12 -0
- package/src/cli/commands/check-path.ts +55 -0
- package/src/cli/commands/completion.ts +8 -0
- package/src/cli/commands/console.ts +12 -0
- package/src/cli/commands/daemon.ts +8 -0
- package/src/cli/commands/deliverables.ts +25 -0
- package/src/cli/commands/doctor.ts +249 -0
- package/src/cli/commands/down.ts +3 -0
- package/src/cli/commands/export.ts +15 -0
- package/src/cli/commands/facts.ts +15 -0
- package/src/cli/commands/goal.ts +22 -0
- package/src/cli/commands/guidance.ts +102 -0
- package/src/cli/commands/help.ts +17 -0
- package/src/cli/commands/host.ts +45 -0
- package/src/cli/commands/init.ts +121 -0
- package/src/cli/commands/instructed.ts +19 -0
- package/src/cli/commands/instruction-hook.ts +15 -0
- package/src/cli/commands/intake.ts +24 -0
- package/src/cli/commands/kill.ts +15 -0
- package/src/cli/commands/learn.ts +23 -0
- package/src/cli/commands/lineage.ts +30 -0
- package/src/cli/commands/logs.ts +21 -0
- package/src/cli/commands/manager.ts +15 -0
- package/src/cli/commands/memory.ts +21 -0
- package/src/cli/commands/model.ts +25 -0
- package/src/cli/commands/models.ts +40 -0
- package/src/cli/commands/native.ts +39 -0
- package/src/cli/commands/pause.ts +5 -0
- package/src/cli/commands/peer.ts +32 -0
- package/src/cli/commands/permission.ts +26 -0
- package/src/cli/commands/permit.ts +12 -0
- package/src/cli/commands/pet.ts +24 -0
- package/src/cli/commands/projects.ts +49 -0
- package/src/cli/commands/queue.ts +70 -0
- package/src/cli/commands/recovery-run.ts +13 -0
- package/src/cli/commands/recovery.ts +130 -0
- package/src/cli/commands/release.ts +23 -0
- package/src/cli/commands/releases.ts +9 -0
- package/src/cli/commands/remember.ts +6 -0
- package/src/cli/commands/report.ts +27 -0
- package/src/cli/commands/research.ts +53 -0
- package/src/cli/commands/reset.ts +89 -0
- package/src/cli/commands/restart.ts +5 -0
- package/src/cli/commands/results.ts +31 -0
- package/src/cli/commands/resume.ts +5 -0
- package/src/cli/commands/review.ts +24 -0
- package/src/cli/commands/roadmap.ts +21 -0
- package/src/cli/commands/role.ts +34 -0
- package/src/cli/commands/roles.ts +30 -0
- package/src/cli/commands/room.ts +14 -0
- package/src/cli/commands/roster.ts +48 -0
- package/src/cli/commands/route.ts +9 -0
- package/src/cli/commands/say.ts +21 -0
- package/src/cli/commands/schedule.ts +17 -0
- package/src/cli/commands/sdlc.ts +321 -0
- package/src/cli/commands/settings.ts +148 -0
- package/src/cli/commands/setup.ts +89 -0
- package/src/cli/commands/shared-refusals.ts +25 -0
- package/src/cli/commands/smoke.ts +44 -0
- package/src/cli/commands/source.ts +64 -0
- package/src/cli/commands/specs.ts +13 -0
- package/src/cli/commands/status.ts +28 -0
- package/src/cli/commands/stop.ts +17 -0
- package/src/cli/commands/structure.ts +60 -0
- package/src/cli/commands/study.ts +39 -0
- package/src/cli/commands/tail.ts +19 -0
- package/src/cli/commands/task.ts +114 -0
- package/src/cli/commands/title.ts +17 -0
- package/src/cli/commands/turns.ts +10 -0
- package/src/cli/commands/ui.ts +47 -0
- package/src/cli/commands/undo.ts +77 -0
- package/src/cli/commands/up.ts +39 -0
- package/src/cli/commands/upgrade.ts +5 -0
- package/src/cli/commands/usage.ts +33 -0
- package/src/cli/commands/version.ts +5 -0
- package/src/cli/commands/watch.ts +30 -0
- package/src/cli/commands/worktrees.ts +31 -0
- package/src/cli/console-state.ts +5 -138
- package/src/cli/console-versions.ts +1 -1
- package/src/cli/help.ts +37 -15
- package/src/cli/identity.ts +23 -4
- package/src/cli/launch-check.ts +1 -2
- package/src/cli/launch.ts +13 -82
- package/src/cli/light-dispatch.ts +29 -0
- package/src/cli/main.js +8 -1
- package/src/cli/main.ts +233 -2816
- package/src/cli/orca-probe.ts +119 -0
- package/src/cli/output.ts +31 -2
- package/src/cli/preview.ts +10 -5
- package/src/cli/recovery-version-preflight.ts +28 -9
- package/src/cli/replace-process.ts +22 -0
- package/src/cli/report-layout.ts +142 -0
- package/src/cli/roadmap-usage.ts +16 -0
- package/src/cli/roadmap.ts +3 -16
- package/src/cli/sdlc-doctor.ts +27 -0
- package/src/cli/sdlc-output.ts +55 -1
- package/src/cli/setup-homes.ts +1 -1
- package/src/cli/start-agents-run.ts +1 -1
- package/src/cli/statusline-tee.ts +25 -4
- package/src/cli/terminal-recovery.ts +53 -10
- package/src/cli/upgrade-interactive.ts +1 -0
- package/src/cli/upgrade-runtime.ts +11 -0
- package/src/cli/upgrade.ts +4 -15
- package/src/hub/accounts.ts +148 -0
- package/src/hub/addons.ts +20 -0
- package/src/hub/agent-drift.ts +2 -1
- package/src/hub/budget-projection.ts +39 -7
- package/src/hub/budget.ts +231 -16
- package/src/hub/channel-project.ts +3 -3
- package/src/hub/conductor-peer.ts +24 -0
- package/src/hub/conductor.ts +2 -21
- package/src/hub/config-apply.ts +24 -13
- package/src/hub/config-edit.ts +1 -1
- package/src/hub/config-tier.ts +2 -0
- package/src/hub/config.ts +31 -14
- package/src/hub/control-client.ts +48 -0
- package/src/hub/daemon.ts +421 -61
- package/src/hub/events.ts +3 -0
- package/src/hub/home-tag.ts +12 -0
- package/src/hub/host.ts +217 -0
- package/src/hub/hub-tools.ts +2 -1
- package/src/hub/instance-budget.ts +2 -2
- package/src/hub/instance-config.ts +15 -126
- package/src/hub/instances.ts +22 -6
- package/src/hub/instruction-receipt.ts +2 -2
- package/src/hub/kimi-usage.ts +38 -11
- package/src/hub/lifecycle.ts +86 -4
- package/src/hub/mcp-bridge-core.ts +98 -0
- package/src/hub/mcp-channel-push.ts +20 -0
- package/src/hub/mcp-endpoint-serve.ts +178 -0
- package/src/hub/mcp-endpoint.ts +226 -0
- package/src/hub/mcp-tool-call.ts +181 -0
- package/src/hub/operational-settings.ts +2 -0
- package/src/hub/orca-env.ts +6 -0
- package/src/hub/orca-state.ts +84 -0
- package/src/hub/peers.ts +5 -1
- package/src/hub/permission-mode.ts +2 -1
- package/src/hub/project.ts +20 -0
- package/src/hub/protocol-window.ts +58 -0
- package/src/hub/quota-origin.ts +20 -0
- package/src/hub/registry.ts +36 -2
- package/src/hub/report.ts +1 -1
- package/src/hub/research.ts +1 -1
- package/src/hub/review-brief.ts +47 -2
- package/src/hub/roster.ts +6 -3
- package/src/hub/routing.ts +9 -2
- package/src/hub/sdlc-check.ts +205 -0
- package/src/hub/sdlc-sync.ts +146 -0
- package/src/hub/sdlc.ts +33 -4
- package/src/hub/settings.ts +7 -4
- package/src/hub/start-agents.ts +1 -1
- package/src/hub/start-mode.ts +11 -4
- package/src/hub/structure-budget.ts +131 -0
- package/src/hub/structure-scan.ts +149 -0
- package/src/hub/tasks-experiment.ts +455 -0
- package/src/hub/tasks-guidance.ts +606 -0
- package/src/hub/tasks-roadmap-plan.ts +419 -0
- package/src/hub/tasks-roadmap.ts +491 -0
- package/src/hub/tasks-study.ts +661 -0
- package/src/hub/tasks-survey.ts +192 -0
- package/src/hub/tasks.ts +319 -2548
- package/src/hub/terminal-open.ts +5 -3
- package/src/hub/tooling.ts +3 -19
- package/src/hub/usage-rollup.ts +9 -3
- package/src/local/tools.ts +5 -0
- package/src/ui/index.html +1 -1
- package/src/ui/needs.ts +17 -5
- package/src/ui/peer-palette.ts +2 -4
- package/templates/presets/agents.json +60 -0
- package/templates/presets/confirmation-matrix.json +8 -8
|
@@ -13,11 +13,11 @@ export interface ProjectionPoint {
|
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
* `projected`: the window reaches its limit at `at`. `basis` says which span the rate was measured over — the whole
|
|
16
|
-
* lookback,
|
|
16
|
+
* lookback, the window itself, or the span since the first provider reading after renewal.
|
|
17
17
|
* `unknown`: no time is claimed, and `cause` says why. It is never rendered as a date.
|
|
18
18
|
*/
|
|
19
19
|
export type ExhaustionProjection =
|
|
20
|
-
| { state: "projected"; at: number; basis: "lookback" | "window" }
|
|
20
|
+
| { state: "projected"; at: number; basis: "lookback" | "window" | "renewal" }
|
|
21
21
|
| { state: "unknown"; cause: "few_points" | "no_burn" | "reset_first" | "unknown_usage" };
|
|
22
22
|
|
|
23
23
|
export interface ProjectionInput {
|
|
@@ -32,9 +32,20 @@ export interface ProjectionInput {
|
|
|
32
32
|
lookbackMs: number;
|
|
33
33
|
/** The reading behind this window is older than the hub's freshness bound, so none of these numbers describe it now. */
|
|
34
34
|
stale?: boolean;
|
|
35
|
+
/** Last explicit account renewal. Older windows require provider evidence after it. */
|
|
36
|
+
renewedAt?: number;
|
|
37
|
+
baseline?: { at: number; used: number };
|
|
35
38
|
points: readonly ProjectionPoint[];
|
|
36
39
|
}
|
|
37
40
|
|
|
41
|
+
// Provider percentages are rounded. Smaller changes do not establish a reliable rate or a new baseline.
|
|
42
|
+
const MIN_RENEWED_USAGE_GAIN = 0.05;
|
|
43
|
+
// Give delayed provider updates time to settle before interpreting a jump as fast burn.
|
|
44
|
+
const MIN_RENEWED_SPAN_MS = 15 * 60_000;
|
|
45
|
+
|
|
46
|
+
export function quotaUsageGainAtLeast(gain: number): boolean {
|
|
47
|
+
return gain >= MIN_RENEWED_USAGE_GAIN - Number.EPSILON;
|
|
48
|
+
}
|
|
38
49
|
const finite = (v: number | null | undefined): v is number => typeof v === "number" && Number.isFinite(v);
|
|
39
50
|
|
|
40
51
|
/**
|
|
@@ -42,17 +53,30 @@ const finite = (v: number | null | undefined): v is number => typeof v === "numb
|
|
|
42
53
|
* projection that lands after the window's own reset each answer `unknown` with the cause named, never a time.
|
|
43
54
|
*/
|
|
44
55
|
export function projectExhaustion(input: ProjectionInput): ExhaustionProjection {
|
|
45
|
-
const { used, windowStart, resetsAt, now, lookbackMs, points, stale } = input;
|
|
56
|
+
const { used, windowStart, resetsAt, now, lookbackMs, points, stale, renewedAt, baseline } = input;
|
|
46
57
|
// A stale reading is no usable reading, exactly like a window whose reset has passed: the numbers it still carries
|
|
47
58
|
// describe an earlier window, so no time is claimed from them.
|
|
48
59
|
if (stale === true || !finite(used) || used < 0 || used > 1) return { state: "unknown", cause: "unknown_usage" };
|
|
49
60
|
if (!finite(windowStart) || !finite(resetsAt) || windowStart >= now || resetsAt <= now) return { state: "unknown", cause: "unknown_usage" };
|
|
61
|
+
if (renewedAt !== undefined && windowStart < renewedAt) {
|
|
62
|
+
if (!baseline || !finite(baseline.at) || !finite(baseline.used) || baseline.used < 0 || baseline.used > 1
|
|
63
|
+
|| baseline.at < renewedAt || !quotaUsageGainAtLeast(used - baseline.used)) {
|
|
64
|
+
return { state: "unknown", cause: "unknown_usage" };
|
|
65
|
+
}
|
|
66
|
+
const span = now - baseline.at;
|
|
67
|
+
if (!finite(span) || span < MIN_RENEWED_SPAN_MS) return { state: "unknown", cause: "few_points" };
|
|
68
|
+
// ponytail: this average since baseline can show a recent speed-up in a weekly window late.
|
|
69
|
+
// A bounded history of provider readings can give the recent pace without changing either gate.
|
|
70
|
+
const rate = (used - baseline.used) / span;
|
|
71
|
+
const at = now + (1 - used) / rate;
|
|
72
|
+
if (!Number.isFinite(at)) return { state: "unknown", cause: "few_points" };
|
|
73
|
+
return at > resetsAt ? { state: "unknown", cause: "reset_first" } : { state: "projected", at: Math.round(at), basis: "renewal" };
|
|
74
|
+
}
|
|
50
75
|
if (!finite(lookbackMs) || lookbackMs <= 0) return { state: "unknown", cause: "few_points" };
|
|
51
|
-
// A reset inside the lookback
|
|
52
|
-
// start and never across the reset. The projection says which span it used.
|
|
76
|
+
// A reset inside the lookback limits the rate to the window's own span.
|
|
53
77
|
const lookbackFrom = now - lookbackMs;
|
|
54
78
|
const from = Math.max(windowStart, lookbackFrom);
|
|
55
|
-
const basis
|
|
79
|
+
const basis = from > lookbackFrom ? "window" : "lookback";
|
|
56
80
|
const inside = points.filter(p => finite(p.at) && finite(p.tokens) && p.tokens >= 0 && p.at >= from && p.at <= now).sort((a, b) => a.at - b.at);
|
|
57
81
|
const total = points.filter(p => finite(p.at) && finite(p.tokens) && p.tokens > 0 && p.at >= windowStart && p.at <= now).reduce((sum, p) => sum + p.tokens, 0);
|
|
58
82
|
if (used >= 1) return { state: "projected", at: now, basis };
|
|
@@ -86,7 +110,7 @@ const CAUSE_TEXT: Record<Extract<ExhaustionProjection, { state: "unknown" }>["ca
|
|
|
86
110
|
*/
|
|
87
111
|
export function projectionText(projection: ExhaustionProjection, when: (at: number) => string): string {
|
|
88
112
|
return projection.state === "projected"
|
|
89
|
-
? `reaches its limit ${when(projection.at)}${projection.basis === "window" ? " (rate since the window opened)" : ""}`
|
|
113
|
+
? `reaches its limit ${when(projection.at)}${projection.basis === "renewal" ? " (rate since the renewal)" : projection.basis === "window" ? " (rate since the window opened)" : ""}`
|
|
90
114
|
: `no forecast: ${CAUSE_TEXT[projection.cause]}`;
|
|
91
115
|
}
|
|
92
116
|
|
|
@@ -97,3 +121,11 @@ export const WINDOW_MINS: Record<string, number> = { "5h": 300, week: 10_080, to
|
|
|
97
121
|
export function windowLeft(used: number | null | undefined): number | null {
|
|
98
122
|
return finite(used) && used >= 0 && used <= 1 ? 1 - used : null;
|
|
99
123
|
}
|
|
124
|
+
|
|
125
|
+
const EARLY_WARNING_MS = 60 * 60_000;
|
|
126
|
+
|
|
127
|
+
/** Mention only a projected exhaustion within the warning horizon and strictly before its reset. */
|
|
128
|
+
export function earlyBudgetWarning(projection: ExhaustionProjection, resetsAt: number | undefined, now: number): number | undefined {
|
|
129
|
+
return projection.state === "projected" && resetsAt !== undefined && projection.at >= now
|
|
130
|
+
&& projection.at < resetsAt && projection.at - now <= EARLY_WARNING_MS ? projection.at : undefined;
|
|
131
|
+
}
|
package/src/hub/budget.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { quotaAccountUsage, type QuotaAccountUsage, type QuotaAccountReading } from "./quota-account.ts";
|
|
2
|
-
import {
|
|
2
|
+
import type { AdapterDefinition } from "../adapters/registry-types.ts";
|
|
3
3
|
import type { Database } from "./db-schema.ts";
|
|
4
4
|
import { openHubDatabase } from "./db-schema.ts";
|
|
5
|
+
import { quotaStampAfter, stampQuotaBoundary, type QuotaStamp } from "./quota-origin.ts";
|
|
5
6
|
import type { PeerId } from "./envelope.ts";
|
|
7
|
+
import { isClaudeSessionUuid } from "./claude-state.ts";
|
|
8
|
+
import { quotaUsageGainAtLeast } from "./budget-projection.ts";
|
|
6
9
|
import { windowKind, type WindowKind } from "./window-kind.ts";
|
|
7
10
|
export { windowKind, type WindowKind };
|
|
8
11
|
|
|
@@ -29,10 +32,13 @@ interface Reading extends UsageWindow {
|
|
|
29
32
|
/** Readings are kept per window id and kind, so a person's number and the provider's for one window never overwrite each other. */
|
|
30
33
|
const readingKey = (id: string, kind: WindowKind): string => `${id}|${kind}`;
|
|
31
34
|
|
|
35
|
+
const quotaFraction = (used: number): number => Math.max(0, Math.min(1, used));
|
|
36
|
+
|
|
32
37
|
export interface Moved {
|
|
33
38
|
id: number;
|
|
34
39
|
title: string;
|
|
35
40
|
to: PeerId | null;
|
|
41
|
+
from?: PeerId;
|
|
36
42
|
role: "owner" | "reviewer";
|
|
37
43
|
}
|
|
38
44
|
export interface PauseRecord {
|
|
@@ -53,11 +59,29 @@ export interface BudgetConfig {
|
|
|
53
59
|
kimi_tokens_5h: number;
|
|
54
60
|
/** A paused peer whose window resets within this many minutes keeps its work, urgent tasks aside; 0 always hands over (issue #36). */
|
|
55
61
|
wait_max_min: number;
|
|
62
|
+
/** #1810: a paused account's work may go to a peer of the same kind on another declared account. Off restores handoff across kinds only. */
|
|
63
|
+
cross_account_handoff: boolean;
|
|
56
64
|
}
|
|
57
65
|
// wait_max_min is off here, as approvals.notify is: a project config turns it on (30 unless it says otherwise).
|
|
58
|
-
export const DEFAULT_BUDGET: BudgetConfig = { gate: 0.99, stale_min: 30, poll_min: 10, checkpoint_timeout_s: 90, kimi_tokens_5h: 0, wait_max_min: 0 };
|
|
66
|
+
export const DEFAULT_BUDGET: BudgetConfig = { gate: 0.99, stale_min: 30, poll_min: 10, checkpoint_timeout_s: 90, kimi_tokens_5h: 0, wait_max_min: 0, cross_account_handoff: true };
|
|
67
|
+
|
|
68
|
+
type RenewalMode = "reset" | "switched";
|
|
69
|
+
type DiscardedWindow = Pick<Reading, "used" | "resetsAt">;
|
|
70
|
+
type Renewal = { at: number; mode: RenewalMode; discarded: Record<string, DiscardedWindow>; stamp: QuotaStamp };
|
|
71
|
+
export interface QuotaOrigin {
|
|
72
|
+
processStartedAt?: number;
|
|
73
|
+
processStamp?: QuotaStamp;
|
|
74
|
+
forecastSession?: { sessionId: unknown; launchId?: unknown };
|
|
75
|
+
turnStartedAt?: number;
|
|
76
|
+
turnStartedAtLatest?: number;
|
|
77
|
+
}
|
|
78
|
+
interface BudgetRenewalResult {
|
|
79
|
+
account: PeerId;
|
|
80
|
+
moved: Pick<Moved, "id" | "to" | "from" | "role">[];
|
|
81
|
+
}
|
|
59
82
|
|
|
60
83
|
export type BudgetLedgerEntry =
|
|
84
|
+
| { type: "budget_renew"; peer: PeerId; mode: RenewalMode; by: "person" }
|
|
61
85
|
| { type: "budget_pause"; peer: PeerId; reason: string; window: string; resetsAt: number; by: "hub" | "person" }
|
|
62
86
|
| { type: "budget_resume"; peer: PeerId; reason: string; window: string; resetsAt: number; by: "hub" | "person" }
|
|
63
87
|
| { type: "quota_reset"; peer: PeerId; window: string; cause: "resets_at_moved" | "used_dropped"; resetsAt?: number; previousResetsAt?: number; used: number; previousUsed: number; measuredAt?: string };
|
|
@@ -69,6 +93,8 @@ export interface BudgetHooks {
|
|
|
69
93
|
definitionOf?(peer: PeerId): AdapterDefinition | undefined;
|
|
70
94
|
/** Stable/idempotent for this Budget lifetime. All lifecycle hooks receive this canonical account id. */
|
|
71
95
|
account?(peer: PeerId): PeerId;
|
|
96
|
+
/** Accept switched readings only when this source is proven to use the new quota context. */
|
|
97
|
+
allowSwitchedReading?(reporter: PeerId, renewedAt: number, origin: QuotaOrigin | undefined): boolean;
|
|
72
98
|
pause(peer: PeerId): void;
|
|
73
99
|
/** Must leave a manual `ahub pause` in place. */
|
|
74
100
|
resume(peer: PeerId): void;
|
|
@@ -82,7 +108,7 @@ export interface BudgetHooks {
|
|
|
82
108
|
canHandOff(peer: PeerId): boolean;
|
|
83
109
|
/** Move the peer's open work; with `urgentOnly`, only tasks marked urgent (the peer waits for its reset). */
|
|
84
110
|
handoff(peer: PeerId, context: string | undefined, urgentOnly: boolean): Promise<Moved[]>;
|
|
85
|
-
resumed(record: PauseRecord): void;
|
|
111
|
+
resumed(record: PauseRecord, renewal?: RenewalMode): void;
|
|
86
112
|
/** Every reading as it arrives, with the time it was measured (telemetry, issue #40). */
|
|
87
113
|
reading?(peer: PeerId, windows: UsageWindow[], hard: boolean, at: number): void;
|
|
88
114
|
/**
|
|
@@ -90,9 +116,12 @@ export interface BudgetHooks {
|
|
|
90
116
|
* numbers only. Telemetry never costs a pause or a reading, so a throwing hook is ignored.
|
|
91
117
|
*/
|
|
92
118
|
ledger?(entry: BudgetLedgerEntry): void;
|
|
119
|
+
/** Optional tighter time limit for a caller waiting to rebaseline after an in-flight handoff. */
|
|
120
|
+
renewHandoffWaitMs?: number;
|
|
93
121
|
notify(line: string): void;
|
|
94
122
|
}
|
|
95
123
|
|
|
124
|
+
const RENEW_HANDOFF_WAIT_MS = 10_000;
|
|
96
125
|
const HYSTERESIS = 0.1;
|
|
97
126
|
/** A window whose `used` falls by this much inside one window id has been reset (#683 U1). */
|
|
98
127
|
const RESET_DROP = 0.5;
|
|
@@ -102,11 +131,41 @@ const RESET_DROP = 0.5;
|
|
|
102
131
|
* A forward move of this much or less is the same window, not a reset (#683 U1).
|
|
103
132
|
*/
|
|
104
133
|
const RESET_JITTER_MS = 15 * 60_000;
|
|
134
|
+
|
|
135
|
+
function sameQuotaWindow(left?: number, right?: number): boolean {
|
|
136
|
+
return left === undefined || right === undefined || Math.abs(left - right) <= RESET_JITTER_MS;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const MAX_FORECAST_SOURCES = 8;
|
|
140
|
+
|
|
141
|
+
function forecastSource(reporter: PeerId, origin?: QuotaOrigin): string | undefined {
|
|
142
|
+
const session = origin?.forecastSession;
|
|
143
|
+
if (session) {
|
|
144
|
+
if (!isClaudeSessionUuid(session.sessionId) || (session.launchId !== undefined && !isClaudeSessionUuid(session.launchId))) return;
|
|
145
|
+
return JSON.stringify(["session", session.sessionId.toLowerCase(), typeof session.launchId === "string" ? session.launchId.toLowerCase() : null]);
|
|
146
|
+
}
|
|
147
|
+
const stamp = origin?.processStamp;
|
|
148
|
+
if (stamp && isClaudeSessionUuid(stamp.runtime) && Number.isSafeInteger(stamp.order) && stamp.order > 0) {
|
|
149
|
+
return JSON.stringify(["process", reporter, stamp.runtime, stamp.order]);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface ForecastReading { source: string; version: number }
|
|
154
|
+
|
|
155
|
+
interface ForecastBaseline {
|
|
156
|
+
at: number;
|
|
157
|
+
used: number;
|
|
158
|
+
latestAt: number;
|
|
159
|
+
latestUsed: number;
|
|
160
|
+
latestReset?: number;
|
|
161
|
+
}
|
|
105
162
|
/** Mark a pause whose handoff was a wait, and one whose wait was undone, in its reason (issue #36). */
|
|
106
163
|
const WAIT_NOTE = "; keeps its work:";
|
|
107
164
|
const WAITED_NOTE = "; waited, then the reset moved to";
|
|
108
165
|
const waitedNote = (min: number, max: number) => `${WAITED_NOTE} ${min} min, beyond wait_max_min ${max}`;
|
|
109
166
|
const FALLBACK_WINDOW_MINS = 300;
|
|
167
|
+
// #1234: fail closed on a corrupt marker, with the recovery step board.ts gives for the same kind of failure; never the row contents.
|
|
168
|
+
const CORRUPT_RENEWAL_MARKER = "invalid stored budget renewal marker; stop the hub and restore a trusted hub.db backup before retrying";
|
|
110
169
|
|
|
111
170
|
/**
|
|
112
171
|
* Budget relay. Readings come from the adapters (Codex rate limits, Claude's status line, Kimi tokens) or from
|
|
@@ -119,7 +178,12 @@ export class Budget {
|
|
|
119
178
|
private readonly pausing = new Map<PeerId, object>();
|
|
120
179
|
private readonly accountUsage = new Map<PeerId, QuotaAccountUsage & { at: number }>();
|
|
121
180
|
private readonly pauseObservers = new Map<PeerId, Set<() => void>>();
|
|
122
|
-
private readonly handingOff = new
|
|
181
|
+
private readonly handingOff = new Map<PeerId, Promise<void>>();
|
|
182
|
+
private readonly renewals = new Map<PeerId, Renewal>();
|
|
183
|
+
private readonly forecastBaselines = new Map<PeerId, Map<string, Map<string, ForecastBaseline>>>();
|
|
184
|
+
// Attach private source identity to each exact reading, including its transient status view.
|
|
185
|
+
private readonly forecastReadings = new WeakMap<UsageWindow, ForecastReading>();
|
|
186
|
+
private forecastVersion = 0;
|
|
123
187
|
/** The last reading of each window of an account, for the derived `quota_reset` (see `deriveResets`). */
|
|
124
188
|
private readonly lastSeen = new Map<PeerId, Map<string, { used: number; resetsAt?: number; at: number }>>();
|
|
125
189
|
/** `peer|window|resetsAt` of every reset already written this run, so a duplicate reading adds no reset. */
|
|
@@ -142,7 +206,26 @@ export class Budget {
|
|
|
142
206
|
this.db = openHubDatabase(dbPath, { create: true });
|
|
143
207
|
this.db.run(`CREATE TABLE IF NOT EXISTS budget_pauses (peer TEXT PRIMARY KEY, since INTEGER NOT NULL, resets_at INTEGER NOT NULL,
|
|
144
208
|
reason TEXT NOT NULL, summary TEXT, handed_off INTEGER NOT NULL DEFAULT 0, moved TEXT NOT NULL DEFAULT '[]')`);
|
|
145
|
-
try {
|
|
209
|
+
try {
|
|
210
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS budget_renewals (
|
|
211
|
+
peer TEXT PRIMARY KEY, at INTEGER NOT NULL, mode TEXT NOT NULL, discarded TEXT NOT NULL,
|
|
212
|
+
runtime TEXT NOT NULL, ordering INTEGER NOT NULL
|
|
213
|
+
)`);
|
|
214
|
+
this.normalizeStoredPauses();
|
|
215
|
+
for (const row of this.db.query("SELECT peer, at, mode, discarded, runtime, ordering FROM budget_renewals").all() as
|
|
216
|
+
{ peer: string; at: number; mode: RenewalMode; discarded: string; runtime: string; ordering: number }[]) {
|
|
217
|
+
let discarded: unknown;
|
|
218
|
+
try { discarded = JSON.parse(row.discarded); } catch { throw new Error(CORRUPT_RENEWAL_MARKER); }
|
|
219
|
+
if (!Number.isSafeInteger(row.at) || (row.mode !== "reset" && row.mode !== "switched")
|
|
220
|
+
|| !discarded || typeof discarded !== "object" || Array.isArray(discarded)
|
|
221
|
+
|| typeof row.runtime !== "string" || !row.runtime || !Number.isSafeInteger(row.ordering)) throw new Error(CORRUPT_RENEWAL_MARKER);
|
|
222
|
+
const account = this.account(row.peer);
|
|
223
|
+
const previous = this.renewals.get(account);
|
|
224
|
+
if (!previous || previous.at <= row.at) {
|
|
225
|
+
this.renewals.set(account, { at: row.at, mode: row.mode, discarded: discarded as Renewal["discarded"], stamp: { runtime: row.runtime, order: row.ordering } });
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
} catch (error) { this.db.close(); throw error; }
|
|
146
229
|
}
|
|
147
230
|
|
|
148
231
|
private account(peer: PeerId): PeerId {
|
|
@@ -256,14 +339,47 @@ export class Budget {
|
|
|
256
339
|
|
|
257
340
|
/** `hard`: the peer cannot run another turn (its provider refused one), so there is nobody to ask for a checkpoint. */
|
|
258
341
|
/** `at`: when the numbers were measured, for sources that arrive through a file (a leftover file is not a fresh reading). */
|
|
259
|
-
report(peer: PeerId, windows: UsageWindow[], hard = false, at = this.now(), accountUsage?: QuotaAccountUsage): void {
|
|
342
|
+
report(peer: PeerId, windows: UsageWindow[], hard = false, at = this.now(), accountUsage?: QuotaAccountUsage, origin?: QuotaOrigin): void {
|
|
343
|
+
this.reportWindows(peer, windows, hard, at, accountUsage, origin);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Call only with the shared hub counter, after filtering its measured rows against the saved renewal. */
|
|
347
|
+
reportKimiCount(peer: PeerId, window: { used: number; resetsAt: number; ceiling: number }): void {
|
|
348
|
+
this.reportWindows(peer, [{ id: "tokens", kind: "count", used: window.used, resetsAt: window.resetsAt,
|
|
349
|
+
source: `hub count, kimi wire log, of kimi_tokens_5h ${window.ceiling}` }], false, this.now(), undefined, undefined, true);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
private reportWindows(peer: PeerId, windows: UsageWindow[], hard: boolean, at: number, accountUsage?: QuotaAccountUsage,
|
|
353
|
+
origin?: QuotaOrigin, trustedKimiCount = false): void {
|
|
260
354
|
// Execution-budget instrumentation is independent of native quota accounting.
|
|
261
355
|
// Explicit quota exemption or absent budget metadata exempts registered kinds; external ids keep accounting.
|
|
262
356
|
const reporter = peer;
|
|
263
357
|
peer = this.account(peer);
|
|
264
|
-
const resolve = this.hooks.definitionOf ?? definitionOf;
|
|
358
|
+
const resolve = this.hooks.definitionOf ?? (require("../adapters/registry.ts") as typeof import("../adapters/registry.ts")).definitionOf;
|
|
265
359
|
const adapter = resolve(reporter) ?? resolve(peer);
|
|
266
360
|
if (reporter === "user" || reporter === "hub" || peer === "user" || peer === "hub" || adapter && (!adapter.budget || adapter.budget.quotaExempt === true) || this.closed) return;
|
|
361
|
+
const renewal = this.renewals.get(peer);
|
|
362
|
+
if (renewal) {
|
|
363
|
+
if (!Number.isFinite(at) || !hard && at < renewal.at) return;
|
|
364
|
+
const latestTurnStart = origin?.turnStartedAtLatest ?? origin?.turnStartedAt;
|
|
365
|
+
if (hard && latestTurnStart !== undefined && latestTurnStart < renewal.at) return;
|
|
366
|
+
if (!hard) {
|
|
367
|
+
const processProved = origin?.processStamp === undefined && origin?.processStartedAt === undefined
|
|
368
|
+
|| !!origin.processStamp && origin.processStartedAt !== undefined && origin.processStartedAt > renewal.at
|
|
369
|
+
&& quotaStampAfter(renewal.stamp, origin.processStamp);
|
|
370
|
+
const providerAllowed = renewal.mode === "reset" || processProved && this.hooks.allowSwitchedReading?.(reporter, renewal.at, origin) === true;
|
|
371
|
+
windows = windows.filter(w => {
|
|
372
|
+
const kind = windowKind(w);
|
|
373
|
+
if (kind === "manual") return true; // Only the authenticated console path supplies this kind.
|
|
374
|
+
if (trustedKimiCount && kind === "count") return w.used > 0;
|
|
375
|
+
if (!providerAllowed) return false;
|
|
376
|
+
const discarded = renewal.discarded[readingKey(w.id, kind)];
|
|
377
|
+
return !discarded || discarded.used !== quotaFraction(w.used) || !sameQuotaWindow(discarded.resetsAt, w.resetsAt);
|
|
378
|
+
});
|
|
379
|
+
if (!windows.length) return;
|
|
380
|
+
if (!windows.some(window => windowKind(window) === "native")) accountUsage = undefined;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
267
383
|
if (accountUsage !== undefined && Number.isFinite(at)) {
|
|
268
384
|
const prior = this.accountUsage.get(peer);
|
|
269
385
|
if (!prior || at >= prior.at) this.accountUsage.set(peer, { ...quotaAccountUsage(accountUsage), at });
|
|
@@ -276,11 +392,14 @@ export class Budget {
|
|
|
276
392
|
this.deriveResets(peer, windows, at);
|
|
277
393
|
const mine = this.readings.get(peer) ?? new Map<string, Reading>();
|
|
278
394
|
this.readings.set(peer, mine);
|
|
395
|
+
const source = renewal && !hard ? forecastSource(reporter, origin) : undefined;
|
|
279
396
|
for (const w of windows) {
|
|
280
397
|
const kind = windowKind(w);
|
|
281
398
|
// A provider that has refused another turn outranks a person's number for the same window.
|
|
282
399
|
if (hard && kind !== "manual") mine.delete(readingKey(w.id, "manual"));
|
|
283
|
-
|
|
400
|
+
const reading = { ...w, kind, used: quotaFraction(w.used), at };
|
|
401
|
+
if (source && kind === "native" && Number.isFinite(w.used)) this.trackForecastBaseline(peer, reading, source);
|
|
402
|
+
mine.set(readingKey(w.id, kind), reading);
|
|
284
403
|
}
|
|
285
404
|
if (this.recoveryHeld) { this.deferred = true; if (hard) this.deferredHard.add(peer); return; }
|
|
286
405
|
this.evaluate(peer, hard).catch((e: Error) => this.closed || this.hooks.notify(`budget: evaluating ${peer} failed: ${e.message}`));
|
|
@@ -291,6 +410,7 @@ export class Budget {
|
|
|
291
410
|
const mine = this.readings.get(this.account(peer));
|
|
292
411
|
if (!mine) return;
|
|
293
412
|
for (const [key, reading] of mine) if (reading.id === id && (!kind || reading.kind === kind)) mine.delete(key);
|
|
413
|
+
if (!kind || kind === "native") this.forecastBaselines.get(this.account(peer))?.delete(id);
|
|
294
414
|
}
|
|
295
415
|
|
|
296
416
|
/** Readings that still say something: not stale, and not about a window that has reset since they were taken. */
|
|
@@ -323,10 +443,10 @@ export class Budget {
|
|
|
323
443
|
const last = this.lastSeen.get(peer) ?? new Map<string, { used: number; resetsAt?: number; at: number }>();
|
|
324
444
|
this.lastSeen.set(peer, last);
|
|
325
445
|
for (const w of windows) {
|
|
326
|
-
const used =
|
|
446
|
+
const used = quotaFraction(w.used), slot = readingKey(w.id, windowKind(w)), before = last.get(slot);
|
|
327
447
|
if (before && at >= before.at) {
|
|
448
|
+
const sameWindow = sameQuotaWindow(before.resetsAt, w.resetsAt);
|
|
328
449
|
const moved = w.resetsAt !== undefined && before.resetsAt !== undefined && w.resetsAt - before.resetsAt > RESET_JITTER_MS;
|
|
329
|
-
const sameWindow = w.resetsAt === undefined || before.resetsAt === undefined || Math.abs(w.resetsAt - before.resetsAt) <= RESET_JITTER_MS;
|
|
330
450
|
const dropped = !moved && before.used - used >= RESET_DROP && sameWindow;
|
|
331
451
|
if (moved || dropped) {
|
|
332
452
|
const key = `${peer}|${w.id}|${w.resetsAt ?? "none"}`;
|
|
@@ -364,6 +484,75 @@ export class Budget {
|
|
|
364
484
|
return true;
|
|
365
485
|
}
|
|
366
486
|
|
|
487
|
+
private trackForecastBaseline(peer: PeerId, reading: Reading, source: string): void {
|
|
488
|
+
const windows = this.forecastBaselines.get(peer) ?? new Map<string, Map<string, ForecastBaseline>>();
|
|
489
|
+
const sources = windows.get(reading.id) ?? new Map<string, ForecastBaseline>();
|
|
490
|
+
const { used, at, resetsAt } = reading;
|
|
491
|
+
const baseline = sources.get(source);
|
|
492
|
+
if (baseline && at < baseline.latestAt) return;
|
|
493
|
+
const latestReset = resetsAt ?? baseline?.latestReset;
|
|
494
|
+
const expired = baseline?.latestReset !== undefined && at - baseline.latestReset > RESET_JITTER_MS;
|
|
495
|
+
const retake = !baseline || !sameQuotaWindow(baseline.latestReset, resetsAt) || expired
|
|
496
|
+
|| baseline.latestUsed - used >= RESET_DROP || quotaUsageGainAtLeast(baseline.used - used);
|
|
497
|
+
// Refresh insertion order only for accepted observations.
|
|
498
|
+
sources.delete(source);
|
|
499
|
+
sources.set(source, {
|
|
500
|
+
at: retake ? at : baseline.at, used: retake ? used : baseline.used, latestAt: at, latestUsed: used, latestReset,
|
|
501
|
+
});
|
|
502
|
+
if (sources.size > MAX_FORECAST_SOURCES) {
|
|
503
|
+
const oldest = sources.keys().next();
|
|
504
|
+
if (!oldest.done) sources.delete(oldest.value);
|
|
505
|
+
}
|
|
506
|
+
windows.set(reading.id, sources);
|
|
507
|
+
this.forecastBaselines.set(peer, windows);
|
|
508
|
+
this.forecastReadings.set(reading, { source, version: ++this.forecastVersion });
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
forecastBaseline(peer: PeerId, window: UsageWindow & { at: number }): { at: number; used: number } | undefined {
|
|
512
|
+
const observed = this.forecastReadings.get(window);
|
|
513
|
+
if (!observed) return;
|
|
514
|
+
const baseline = this.forecastBaselines.get(this.account(peer))?.get(window.id)?.get(observed.source);
|
|
515
|
+
if (baseline && window.at === baseline.latestAt) return { at: baseline.at, used: baseline.used };
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
forecastReadingVersion(window: UsageWindow): number | undefined {
|
|
519
|
+
return this.forecastReadings.get(window)?.version;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
renewalAt(peer: PeerId): number | undefined {
|
|
523
|
+
return this.renewals.get(this.account(peer))?.at;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** Rebaseline an account without installing an override or taking back moved work. */
|
|
527
|
+
async renew(peer: PeerId, mode: RenewalMode, beforeSave?: () => void): Promise<BudgetRenewalResult> {
|
|
528
|
+
peer = this.account(peer);
|
|
529
|
+
if (this.handingOff.has(peer)) await this.waitForRenewalHandoff(peer);
|
|
530
|
+
if (this.closed || this.recoveryHeld) throw new Error("budget renewal unavailable during shutdown or recovery; retry after the hub is ready");
|
|
531
|
+
beforeSave?.();
|
|
532
|
+
const discarded = Object.fromEntries(
|
|
533
|
+
[...(this.lastSeen.get(peer) ?? [])].filter(([, value]) => Number.isFinite(value.used)).map(([key, value]) => [key,
|
|
534
|
+
{ used: value.used, ...(value.resetsAt === undefined ? {} : { resetsAt: value.resetsAt }) }]),
|
|
535
|
+
);
|
|
536
|
+
const record = this.resume(peer, "quota readings renewed by the console user", "person", { at: this.now(), mode, discarded, stamp: stampQuotaBoundary() });
|
|
537
|
+
return { account: peer, moved: (record?.moved ?? []).map(({ id, role, to, from }) => ({ id, role, to, ...(from === undefined ? {} : { from }) })) };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
private async waitForRenewalHandoff(peer: PeerId): Promise<void> {
|
|
541
|
+
// Wait only for work already moving. A timeout leaves both the pause and the handoff owned by their existing paths.
|
|
542
|
+
const deadline = performance.now() + (this.hooks.renewHandoffWaitMs ?? RENEW_HANDOFF_WAIT_MS);
|
|
543
|
+
for (let pending = this.handingOff.get(peer); pending; pending = this.handingOff.get(peer)) {
|
|
544
|
+
let cancel: (() => void) | undefined;
|
|
545
|
+
try {
|
|
546
|
+
const timeout = new Promise<false>(resolve => {
|
|
547
|
+
const timer = setTimeout(() => resolve(false), Math.max(0, deadline - performance.now()));
|
|
548
|
+
cancel = () => clearTimeout(timer);
|
|
549
|
+
});
|
|
550
|
+
const finished = await Promise.race([pending.then(() => true, () => true), timeout]);
|
|
551
|
+
if (!finished) throw new Error("budget renewal was not saved; a task handoff may still be running. Check ahub status and retry ahub budget renew after the handoff settles");
|
|
552
|
+
} finally { cancel?.(); }
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
367
556
|
private async evaluate(peer: PeerId, hard: boolean): Promise<void> {
|
|
368
557
|
peer = this.account(peer);
|
|
369
558
|
if (this.recoveryHeld) { this.deferred = true; if (hard) this.deferredHard.add(peer); return; }
|
|
@@ -436,9 +625,10 @@ export class Budget {
|
|
|
436
625
|
peer = this.account(peer);
|
|
437
626
|
if (this.closed || this.recoveryHeld) { this.deferred = true; return; }
|
|
438
627
|
if (this.handingOff.has(peer) || !this.hooks.canHandOff(peer)) return; // retried by the next tick
|
|
439
|
-
this.
|
|
628
|
+
const handoff = this.handOff(peer, summary);
|
|
629
|
+
this.handingOff.set(peer, handoff);
|
|
440
630
|
try {
|
|
441
|
-
await
|
|
631
|
+
await handoff;
|
|
442
632
|
if (this.recoveryHeld) { this.deferred = true; return; }
|
|
443
633
|
} finally {
|
|
444
634
|
this.handingOff.delete(peer);
|
|
@@ -497,20 +687,39 @@ export class Budget {
|
|
|
497
687
|
}
|
|
498
688
|
}
|
|
499
689
|
|
|
500
|
-
private resume(peer: PeerId, why: string, by: "hub" | "person" = "hub"):
|
|
690
|
+
private resume(peer: PeerId, why: string, by: "hub" | "person" = "hub", renewal?: Renewal): PauseRecord | undefined {
|
|
501
691
|
peer = this.account(peer);
|
|
502
692
|
const record = this.record(peer);
|
|
693
|
+
if (renewal) {
|
|
694
|
+
this.db.transaction(() => {
|
|
695
|
+
this.db.query("INSERT OR REPLACE INTO budget_renewals (peer, at, mode, discarded, runtime, ordering) VALUES (?, ?, ?, ?, ?, ?)")
|
|
696
|
+
.run(peer, renewal.at, renewal.mode, JSON.stringify(renewal.discarded), renewal.stamp.runtime, renewal.stamp.order);
|
|
697
|
+
if (record) this.db.query("DELETE FROM budget_pauses WHERE peer = ?").run(peer);
|
|
698
|
+
}).immediate();
|
|
699
|
+
this.renewals.set(peer, renewal);
|
|
700
|
+
this.forecastBaselines.delete(peer);
|
|
701
|
+
this.pausing.delete(peer);
|
|
702
|
+
this.readings.delete(peer);
|
|
703
|
+
this.lastSeen.delete(peer);
|
|
704
|
+
this.ignoreUntil.delete(peer);
|
|
705
|
+
this.accountUsage.delete(peer);
|
|
706
|
+
this.resetBounds.delete(peer);
|
|
707
|
+
this.reviewerResetProof.delete(peer);
|
|
708
|
+
this.deferredHard.delete(peer);
|
|
709
|
+
this.writeLedger({ type: "budget_renew", peer, mode: renewal.mode, by: "person" });
|
|
710
|
+
} else if (record) this.db.query("DELETE FROM budget_pauses WHERE peer = ?").run(peer);
|
|
503
711
|
if (!record) return;
|
|
504
|
-
this.db.query("DELETE FROM budget_pauses WHERE peer = ?").run(peer);
|
|
505
712
|
this.writeLedger({ type: "budget_resume", peer, reason: why, window: reasonWindow(record.reason), resetsAt: record.resetsAt, by });
|
|
506
713
|
this.readings.get(peer)?.clear(); // the old numbers describe the window that just ended
|
|
714
|
+
this.forecastBaselines.delete(peer);
|
|
507
715
|
this.resetBounds.delete(peer);
|
|
508
716
|
// The notice is queued while the peer is still paused, so it leads the first delivery: the peer learns what moved
|
|
509
717
|
// before it touches anything that was waiting for it.
|
|
510
|
-
this.hooks.resumed(record);
|
|
718
|
+
this.hooks.resumed(record, renewal?.mode);
|
|
511
719
|
this.hooks.resume(peer);
|
|
512
720
|
this.pauseChanged(peer);
|
|
513
721
|
this.hooks.notify(`budget: ${peer} resumed (${why})`);
|
|
722
|
+
return record;
|
|
514
723
|
}
|
|
515
724
|
|
|
516
725
|
/**
|
|
@@ -558,7 +767,12 @@ export class Budget {
|
|
|
558
767
|
// client did before kinds existed, lands on the effective number and not on the one it replaced.
|
|
559
768
|
const rank = (r: Reading) => (used.has(r) ? 0 : fresh.has(r) ? 1 : 2);
|
|
560
769
|
const ordered = [...(this.readings.get(peer)?.values() ?? [])].sort((a, b) => rank(a) - rank(b));
|
|
561
|
-
return [peer, { windows: ordered.map((r) =>
|
|
770
|
+
return [peer, { windows: ordered.map((r) => {
|
|
771
|
+
const view = { ...r, stale: this.now() - r.at > staleMs, superseded: fresh.has(r) && !used.has(r) };
|
|
772
|
+
const source = this.forecastReadings.get(r);
|
|
773
|
+
if (source) this.forecastReadings.set(view, source);
|
|
774
|
+
return view;
|
|
775
|
+
}), ...(open ? { paused: { reason: open.reason, resetsAt: open.resetsAt, since: open.since } } : {}),
|
|
562
776
|
...(open && accountUsage ? { accountUsage: { ...quotaAccountUsage(accountUsage), at: accountUsage.at, stale: this.now() - accountUsage.at > staleMs } } : {}) }];
|
|
563
777
|
}),
|
|
564
778
|
);
|
|
@@ -568,6 +782,7 @@ export class Budget {
|
|
|
568
782
|
this.closed = true;
|
|
569
783
|
this.pauseObservers.clear();
|
|
570
784
|
this.accountUsage.clear();
|
|
785
|
+
this.forecastBaselines.clear();
|
|
571
786
|
this.db.close();
|
|
572
787
|
}
|
|
573
788
|
}
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
// main repository's hub.
|
|
5
5
|
//
|
|
6
6
|
// Limit, stated plainly: this stops accidental and inherited-environment joins. It is not a defence against a same-user process that sets the variables and the launch evidence itself.
|
|
7
|
-
import { definitionOf } from "../adapters/
|
|
8
|
-
import {
|
|
7
|
+
import { builtinPolicyOf as definitionOf } from "../adapters/declaration-data.ts";
|
|
8
|
+
import { readChannelInstanceConfig } from "../adapters/declaration-data.ts";
|
|
9
9
|
import { effectiveInstanceRoles } from "./instances.ts";
|
|
10
10
|
import { resolveInstanceExecutionCwd } from "./instance-execution.ts";
|
|
11
11
|
import { existsSync } from "node:fs";
|
|
@@ -43,7 +43,7 @@ export function channelProject(cwd: string, env: NodeJS.ProcessEnv, policyRoles:
|
|
|
43
43
|
if (peer && declared && !definitionOf(peer)) {
|
|
44
44
|
// A declared extra instance: its workspace is the exact managed worktree the project declares for it, and its hub is the project that declares it.
|
|
45
45
|
try {
|
|
46
|
-
const root = realPath(declared), config =
|
|
46
|
+
const root = realPath(declared), config = readChannelInstanceConfig(root);
|
|
47
47
|
if (config.instances && Object.hasOwn(config.instances, peer)) {
|
|
48
48
|
const workspace = resolveInstanceExecutionCwd(root, peer, config.instances, effectiveInstanceRoles(peer, config.instances, policyRoles(root), config.catalog), config.catalog);
|
|
49
49
|
if (realPath(projectRoot(cwd)) !== realPath(workspace)) return asSession();
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { PreEffectToolRefusal } from "./tool-refusal.ts";
|
|
2
|
+
|
|
3
|
+
// #1778 T2b: the conductor-role validation, moved out of conductor.ts so the Claude channel's config path (instance-config.ts) no longer reaches
|
|
4
|
+
// the task board through conductor.ts -> tasks.ts. conductor.ts re-exports `conductorPeer`, so every other importer is unchanged. No behavior change.
|
|
5
|
+
const PEER = /^[a-z][a-z0-9-]{0,31}$/;
|
|
6
|
+
export const peerId = (value: unknown, preEffect = false): string => {
|
|
7
|
+
if (typeof value !== "string" || /\s/.test(value) || !PEER.test(value) || ["user", "hub", "digest"].includes(value)) throw new (preEffect ? PreEffectToolRefusal : Error)("peer must be a valid agent peer id");
|
|
8
|
+
return value;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/** Validate before listening; missing configuration grants nobody the conductor role. */
|
|
12
|
+
export function conductorPeer(roles: unknown): string | null {
|
|
13
|
+
if (roles === undefined) return null;
|
|
14
|
+
if (!roles || typeof roles !== "object" || Array.isArray(roles)) throw new Error("roles must be an object of peer role lists");
|
|
15
|
+
let conductor: string | null = null;
|
|
16
|
+
for (const [peer, list] of Object.entries(roles)) {
|
|
17
|
+
peerId(peer);
|
|
18
|
+
if (!Array.isArray(list) || list.some((r) => typeof r !== "string")) throw new Error(`roles.${peer} must be a list of role names`);
|
|
19
|
+
if (!list.includes("conductor")) continue;
|
|
20
|
+
if (conductor !== null) throw new Error("roles may name at most one conductor peer");
|
|
21
|
+
conductor = peer;
|
|
22
|
+
}
|
|
23
|
+
return conductor;
|
|
24
|
+
}
|
package/src/hub/conductor.ts
CHANGED
|
@@ -7,6 +7,8 @@ import { CONDUCTOR_TOOL_NAMES } from "./hub-tools.ts";
|
|
|
7
7
|
import { HUB, sanitize, USER } from "./envelope.ts";
|
|
8
8
|
import { OWNERSHIP_EVENTS, type TaskAssignmentRole } from "./tasks.ts";
|
|
9
9
|
import { PreEffectToolRefusal } from "./tool-refusal.ts";
|
|
10
|
+
import { conductorPeer, peerId } from "./conductor-peer.ts";
|
|
11
|
+
export { conductorPeer };
|
|
10
12
|
import type { StartMode } from "./start-mode.ts";
|
|
11
13
|
import type { HubEvent } from "./events.ts";
|
|
12
14
|
import type { SupervisionFeed } from "./supervision.ts";
|
|
@@ -37,27 +39,6 @@ export function publicPeerBudget(status: PublicBudgetStatus, nameable: (text: st
|
|
|
37
39
|
}]));
|
|
38
40
|
}
|
|
39
41
|
|
|
40
|
-
const PEER = /^[a-z][a-z0-9-]{0,31}$/;
|
|
41
|
-
const peerId = (value: unknown, preEffect = false): string => {
|
|
42
|
-
if (typeof value !== "string" || /\s/.test(value) || !PEER.test(value) || ["user", "hub", "digest"].includes(value)) throw new (preEffect ? PreEffectToolRefusal : Error)("peer must be a valid agent peer id");
|
|
43
|
-
return value;
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
/** Validate before listening; missing configuration grants nobody the conductor role. */
|
|
47
|
-
export function conductorPeer(roles: unknown): string | null {
|
|
48
|
-
if (roles === undefined) return null;
|
|
49
|
-
if (!roles || typeof roles !== "object" || Array.isArray(roles)) throw new Error("roles must be an object of peer role lists");
|
|
50
|
-
let conductor: string | null = null;
|
|
51
|
-
for (const [peer, list] of Object.entries(roles)) {
|
|
52
|
-
peerId(peer);
|
|
53
|
-
if (!Array.isArray(list) || list.some((r) => typeof r !== "string")) throw new Error(`roles.${peer} must be a list of role names`);
|
|
54
|
-
if (!list.includes("conductor")) continue;
|
|
55
|
-
if (conductor !== null) throw new Error("roles may name at most one conductor peer");
|
|
56
|
-
conductor = peer;
|
|
57
|
-
}
|
|
58
|
-
return conductor;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
42
|
/** The role check always comes first; default-allow capabilities cannot grant a role. */
|
|
62
43
|
export function requireConductor(peer: string, roles: unknown, capabilities: Record<string, unknown> = {}, assign = false, preEffect = false): void {
|
|
63
44
|
if (conductorPeer(roles) !== peer) throw new (preEffect ? PreEffectToolRefusal : Error)("this operation requires the explicit conductor role");
|