Skip to content

Commit d4de68b

Browse files
committed
Merge PR kunchenguid#4986: cap live lanes per billing provider at spawn
2 parents 9f9b2e7 + 2c1be1f commit d4de68b

10 files changed

Lines changed: 495 additions & 2 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ Break genuine evidence ties without array-order or harness bias.
230230
`quota-axi` owns how model or product windows relate to bounding account windows and remains data-only.
231231
Load `quota-array-dispatch` before choosing among a matched profile array; that skill is the single owner of the TOON-first spendPriority selection procedure.
232232
Run `bin/fm-dispatch-resolve.sh` directly on the written brief in the same turn, with no preflight, and on `clear` pass its `profile:` line to `fm-spawn` unless you state a reason to override; `ambiguous`, `escalate`, `error`, and off all mean the intake above, unchanged (contract: `docs/configuration.md` "Typed dispatch resolution").
233+
Read current per-provider lane load with `bin/fm-provider-load.sh` before choosing a candidate, and treat a provider at its cap as a re-assignment trigger: `bin/fm-spawn.sh` refuses a dispatch that would exceed a provider's configured cap, and the model string decides which provider a candidate bills against.
233234
The generic effort fallback and its precedence are owned by `harness-adapters`: explicit captain and standing configured effort win; otherwise use low for well-understood explicit work, xhigh for ambiguous investigation or design, intermediate levels proportionally, and never max without explicit captain preference.
234235
Do not add model-specific versions of that policy.
235236

‎bin/fm-bootstrap.sh‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1132,6 +1132,18 @@ crew_dispatch_validate() {
11321132
err=$(jq -r --argjson typed "$typed_active" --argjson verified_harnesses "$verified_harnesses" --arg provider_re "$FM_QUOTA_PROVIDER_ID_RE" '
11331133
def verified($h): $verified_harnesses | index($h);
11341134
def provider_id($p): ($p | type) == "string" and ($p | test($provider_re));
1135+
# providerCaps (docs/configuration.md "Crew dispatch profiles") bounds the
1136+
# live lanes one billing provider may carry; fm-provider-lib.sh enforces it
1137+
# at spawn. An invalid declaration must fail loudly here rather than be
1138+
# silently ignored, so every value must be a whole number of at least one
1139+
# and every key a provider id or the reserved `default`.
1140+
def provider_caps_bad:
1141+
(.providerCaps // null) as $c
1142+
| $c != null and (
1143+
($c | type) != "object"
1144+
or ([$c | keys[] | select(. != "default") | select(test($provider_re) | not)] | length > 0)
1145+
or ([$c[] | select((type != "number") or (. < 1) or (. != (. | floor)))] | length > 0)
1146+
);
11351147
def effort_ok($h; $m; $e):
11361148
if $e == null then true
11371149
elif ($e | type) != "string" then false
@@ -1181,6 +1193,7 @@ crew_dispatch_validate() {
11811193
| unique;
11821194
if type != "object" then "top-level value must be an object"
11831195
elif has("rules") and (.rules | type) != "array" then "rules must be an array"
1196+
elif provider_caps_bad then "providerCaps must map each provider id (or default) to a positive integer"
11841197
elif [(.rules // [])[]? | select(type != "object")] | length > 0 then "each rule must be an object"
11851198
elif [(.rules // [])[]? | select((.when? | type) != "string" or (.when | length) == 0)] | length > 0 then "each rule needs non-empty when"
11861199
elif [(.rules // [])[]? | select((.use? | type) != "object" and (.use? | type) != "array")] | length > 0 then "each rule needs use"

‎bin/fm-provider-lib.sh‎

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
#!/usr/bin/env bash
2+
# shellcheck shell=bash
3+
# fm-provider-lib.sh - single owner of the model -> provider identity mapping and
4+
# the per-provider live-lane concurrency cap.
5+
#
6+
# Usage:
7+
# . bin/fm-provider-lib.sh
8+
#
9+
# A provider is the billing pool a dispatch draws on, NOT the harness that
10+
# launches it. The identity is taken from the resolved model string first - a
11+
# provider-qualified `<provider>/<id>` prefix, else a model-id pattern - and the
12+
# harness table is consulted only when the model carries no signal. That is what
13+
# makes `opencode-go/deepseek-v4.1-flash` and `opencode-go/deepseek-v4-pro` ONE
14+
# pool while `pi/deepseek-v4p1-flash`, billed through Fireworks, is a different
15+
# one. The harness fallback reuses the existing quota tables
16+
# (fm_quota_provider_for_harness / fm_quota_single_provider_for_harness in
17+
# bin/fm-quota-axi-lib.sh) rather than restating them; those tables are frozen
18+
# for no-key quota routing and are never edited here.
19+
#
20+
# Functions:
21+
# fm_provider_for_model <harness> <model>
22+
# Print the provider id the tuple bills against, or return 1 when the
23+
# model and harness together name no known pool.
24+
# fm_lane_provider <harness> <model>
25+
# Print fm_provider_for_model's answer, or the harness name as a
26+
# last-resort bucket, or return 1 when even that is empty.
27+
# fm_provider_cap_for <provider> [<config-dir>]
28+
# Print the operator-configured cap: `providerCaps.<provider>` from
29+
# config/crew-dispatch.json, else `providerCaps.default`, else
30+
# FM_PROVIDER_LANE_CAP_DEFAULT.
31+
# fm_provider_lane_counts <state-dir> [<config-dir>] [<exclude-id>]
32+
# Print `<provider> <used> <cap>` for every provider carrying a live lane,
33+
# sorted by provider. One line per provider, no header.
34+
# fm_provider_cap_refuse <state-dir> <config-dir> <harness> <model> [<exclude-id>]
35+
# Print an operator-facing refusal to stderr and return 1 when dispatching
36+
# this tuple would push its provider past the cap; return 0 otherwise.
37+
#
38+
# Seat accounting: a lane occupies a seat unless its recorded endpoint is
39+
# PROVABLY dead or missing (fm_backend_agent_state). A lane whose endpoint cannot
40+
# be proven gone - alive, ambiguous, unreadable, or unverified (every backend
41+
# except tmux and herdr) - keeps its seat, and a record with no endpoint target
42+
# keeps it too. The count can therefore under-admit, never over-admit; a
43+
# stranded record on an unverifiable backend is released by the stranded-record
44+
# detector that retires it, not by this counter.
45+
#
46+
# Scope: the cap is per home. A remote secondmate's own lanes live on another
47+
# host and are invisible here, so this counter governs only the lanes this
48+
# home's state directory records.
49+
set -u
50+
51+
if [ -n "${FM_PROVIDER_LIB_SOURCED:-}" ]; then
52+
return 0
53+
fi
54+
FM_PROVIDER_LIB_SOURCED=1
55+
56+
FM_PROVIDER_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
57+
# shellcheck source=bin/fm-backend.sh
58+
. "$FM_PROVIDER_LIB_DIR/fm-backend.sh"
59+
# shellcheck source=bin/fm-quota-axi-lib.sh
60+
. "$FM_PROVIDER_LIB_DIR/fm-quota-axi-lib.sh"
61+
62+
# Fallback cap when config/crew-dispatch.json is absent or declares no
63+
# providerCaps entry. The operator overrides it per provider (or for every
64+
# provider through providerCaps.default) in config/crew-dispatch.json.
65+
FM_PROVIDER_LANE_CAP_DEFAULT=4
66+
67+
# fm_provider_for_model <harness> <model>
68+
fm_provider_for_model() { # <harness> <model>
69+
local harness=${1:-} model=${2:-} segment
70+
case "$model" in
71+
'' | default | -) ;;
72+
*/*)
73+
segment=${model%%/*}
74+
case "$segment" in
75+
fireworks_ai | fireworks) printf 'fireworks\n'; return 0 ;;
76+
openai-codex | openai) printf 'codex\n'; return 0 ;;
77+
claude-bridge | anthropic) printf 'claude\n'; return 0 ;;
78+
esac
79+
# An unrecognized provider-qualified prefix is its own billing pool when
80+
# it is a well-formed provider id (the same shape docs/configuration.md
81+
# pins for the resolver's provider fields).
82+
case "$segment" in
83+
'' | -* | *- | *--* | *[!a-z0-9-]*) ;;
84+
*) printf '%s\n' "$segment"; return 0 ;;
85+
esac
86+
;;
87+
esac
88+
case "$model" in
89+
'' | default | -) ;;
90+
deepseek-v4p1*) printf 'fireworks\n'; return 0 ;;
91+
deepseek*) printf 'deepseek\n'; return 0 ;;
92+
composer* | cursor-*) printf 'cursor\n'; return 0 ;;
93+
grok-*) printf 'grok\n'; return 0 ;;
94+
claude-* | sonnet | haiku | opus | fable) printf 'claude\n'; return 0 ;;
95+
kimi-*) printf 'kimi\n'; return 0 ;;
96+
gemini-*) printf 'gemini\n'; return 0 ;;
97+
muse*) printf 'meta\n'; return 0 ;;
98+
codex* | gpt-* | o[0-9]*) printf 'codex\n'; return 0 ;;
99+
esac
100+
if fm_quota_provider_for_harness "$harness" 2>/dev/null; then
101+
return 0
102+
fi
103+
if fm_quota_single_provider_for_harness "$harness" 2>/dev/null; then
104+
return 0
105+
fi
106+
return 1
107+
}
108+
109+
# fm_lane_provider <harness> <model>
110+
# The bucket a lane is counted against: the model-derived provider when one is
111+
# known, else the harness name so unmapped lanes still count somewhere.
112+
fm_lane_provider() { # <harness> <model>
113+
local harness=${1:-}
114+
if fm_provider_for_model "$1" "${2:-}" 2>/dev/null; then
115+
return 0
116+
fi
117+
[ -n "$harness" ] || return 1
118+
printf '%s\n' "$harness"
119+
}
120+
121+
# fm_provider_cap_for <provider> [<config-dir>]
122+
fm_provider_cap_for() { # <provider> [<config-dir>]
123+
local provider=${1:-} config=${2:-} cap=''
124+
if [ -n "$config" ] && [ -r "$config/crew-dispatch.json" ] && command -v jq >/dev/null 2>&1; then
125+
cap=$(jq -r --arg p "$provider" '
126+
(.providerCaps // {}) as $c
127+
| ($c[$p] // $c.default // empty)
128+
| select(type == "number" and . >= 1 and . == floor)
129+
' "$config/crew-dispatch.json" 2>/dev/null || true)
130+
fi
131+
case "$cap" in
132+
'' | *[!0-9]*) cap=$FM_PROVIDER_LANE_CAP_DEFAULT ;;
133+
esac
134+
printf '%s\n' "$cap"
135+
}
136+
137+
# fm_provider_lane_counts <state-dir> [<config-dir>] [<exclude-id>]
138+
fm_provider_lane_counts() { # <state-dir> [<config-dir>] [<exclude-id>]
139+
local state=${1:-} config=${2:-} exclude=${3:-}
140+
local meta id harness model provider backend target endpoint_state
141+
[ -n "$state" ] || return 0
142+
for meta in "$state"/*.meta; do
143+
[ -e "$meta" ] || [ -L "$meta" ] || continue
144+
id=${meta##*/}
145+
id=${id%.meta}
146+
[ -n "$exclude" ] && [ "$id" = "$exclude" ] && continue
147+
harness=$(fm_meta_get "$meta" harness)
148+
model=$(fm_meta_get "$meta" model)
149+
provider=$(fm_lane_provider "$harness" "$model" 2>/dev/null) || continue
150+
[ -n "$provider" ] || continue
151+
backend=$(fm_backend_of_meta "$meta")
152+
target=$(fm_backend_target_of_meta "$meta")
153+
if [ -n "$target" ]; then
154+
endpoint_state=$(fm_backend_agent_state "$backend" "$target" 2>/dev/null || printf 'unreadable')
155+
case "$endpoint_state" in
156+
dead | missing) continue ;;
157+
esac
158+
fi
159+
printf '%s\n' "$provider"
160+
done | LC_ALL=C sort | uniq -c | while read -r used provider; do
161+
printf '%s %s %s\n' "$provider" "$used" "$(fm_provider_cap_for "$provider" "$config")"
162+
done
163+
}
164+
165+
# fm_provider_cap_refuse <state-dir> <config-dir> <harness> <model> [<exclude-id>]
166+
fm_provider_cap_refuse() { # <state-dir> <config-dir> <harness> <model> [<exclude-id>]
167+
local state=${1:-} config=${2:-} harness=${3:-} model=${4:-} exclude=${5:-}
168+
local provider used cap
169+
provider=$(fm_lane_provider "$harness" "$model" 2>/dev/null) || return 0
170+
[ -n "$provider" ] || return 0
171+
cap=$(fm_provider_cap_for "$provider" "$config")
172+
used=$(fm_provider_lane_counts "$state" "$config" "$exclude" | awk -v p="$provider" '$1 == p { print $2; exit }')
173+
case "$used" in
174+
'' | *[!0-9]*) used=0 ;;
175+
esac
176+
if [ "$used" -ge "$cap" ]; then
177+
printf 'error: provider lane cap: %s already carries %s live lanes (cap %s), so dispatching harness=%s model=%s would exceed it; reassign to a provider with headroom, or raise providerCaps.%s in %s/crew-dispatch.json (fallback cap %s).\n' \
178+
"$provider" "$used" "$cap" "${harness:-unknown}" "${model:-default}" \
179+
"$provider" "${config:-<config>}" "$FM_PROVIDER_LANE_CAP_DEFAULT" >&2
180+
return 1
181+
fi
182+
return 0
183+
}

‎bin/fm-provider-load.sh‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env bash
2+
# fm-provider-load.sh - live crewmate/scout/secondmate lanes per billing provider
3+
# against each provider's configured concurrency cap, for dispatch intake.
4+
#
5+
# Usage:
6+
# fm-provider-load.sh
7+
#
8+
# Read-only: it acquires no lock, mutates nothing, and never starts, stops, or
9+
# steers an agent. It reads this home's state/<id>.meta records, resolves each
10+
# lane's provider from its recorded harness and model (the model string wins;
11+
# see bin/fm-provider-lib.sh), and prints one line per provider that currently
12+
# carries a live lane:
13+
#
14+
# provider-load: <provider> <used>/<cap>
15+
#
16+
# A lane whose recorded endpoint is provably dead or missing does not count, so
17+
# a cleared seat is visible before the next dispatch. With no live lane it prints
18+
# provider-load: no live lanes
19+
# The cap is `providerCaps.<provider>` from config/crew-dispatch.json, else
20+
# `providerCaps.default`, else the fallback in bin/fm-provider-lib.sh; that tool
21+
# is the single owner of the counting and cap rules.
22+
#
23+
# Environment: FM_HOME, FM_STATE_OVERRIDE, and FM_CONFIG_OVERRIDE select the home
24+
# and its state/config directories, exactly as the other bin/ scripts do.
25+
set -u
26+
27+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
28+
FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}}"
29+
STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}"
30+
CONFIG="${FM_CONFIG_OVERRIDE:-$FM_HOME/config}"
31+
32+
# shellcheck source=bin/fm-provider-lib.sh
33+
. "$SCRIPT_DIR/fm-provider-lib.sh"
34+
35+
counts=$(fm_provider_lane_counts "$STATE" "$CONFIG")
36+
if [ -z "$counts" ]; then
37+
printf 'provider-load: no live lanes\n'
38+
exit 0
39+
fi
40+
while read -r provider used cap; do
41+
[ -n "$provider" ] || continue
42+
printf 'provider-load: %s %s/%s\n' "$provider" "$used" "$cap"
43+
done <<EOF
44+
$counts
45+
EOF

‎bin/fm-spawn.sh‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,8 @@ fm_backlog_directory_present "$STATE" "state directory" || {
512512
. "$SCRIPT_DIR/fm-remote-readiness-lib.sh"
513513
# shellcheck source=bin/fm-timeout-lib.sh
514514
. "$SCRIPT_DIR/fm-timeout-lib.sh"
515+
# shellcheck source=bin/fm-provider-lib.sh
516+
. "$SCRIPT_DIR/fm-provider-lib.sh"
515517
# Fail closed before any fleet mutation: a no-mistakes gate agent must never spawn
516518
# a direct report (see bin/fm-gate-refuse-lib.sh).
517519
fm_refuse_if_gate_agent
@@ -2105,6 +2107,22 @@ fi
21052107
if [ "$HARNESS" = agy ]; then
21062108
agy_model_validate "$AGY_BIN" "$MODEL" || exit 1
21072109
fi
2110+
# Per-provider concurrency cap: refuse a dispatch that would push a billing
2111+
# provider past its configured lane cap. The identity comes from the resolved
2112+
# model string (bin/fm-provider-lib.sh), so one pool's models count together
2113+
# even across harnesses while a different pool stays separate. A relaunch
2114+
# already owns its seat, so it is excluded from the count; a lane whose
2115+
# endpoint is provably gone no longer holds a seat. Skipped for a raw launch
2116+
# command, whose harness is unknown and therefore uncountable.
2117+
if [ -n "$HARNESS" ]; then
2118+
LANE_CAP_MODEL=$MODEL
2119+
LANE_CAP_EXCLUDE=
2120+
if [ "$RELAUNCH" -eq 1 ]; then
2121+
LANE_CAP_EXCLUDE=$ID
2122+
[ -n "$LANE_CAP_MODEL" ] || LANE_CAP_MODEL=$(fm_meta_get "$RELAUNCH_META" model)
2123+
fi
2124+
fm_provider_cap_refuse "$STATE" "$CONFIG" "$HARNESS" "$LANE_CAP_MODEL" "$LANE_CAP_EXCLUDE" || exit 1
2125+
fi
21082126

21092127
secondmate_registry_value() {
21102128
secondmate_registry_field "$DATA/secondmates.md" "$1" "$2"

‎docs/configuration.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,8 @@ This section is the single owner of the canonical schema and its per-field seman
447447
],
448448
"default": [
449449
{ "harness": "<adapter>", "model": "<optional model>", "effort": "<optional effort>" }
450-
]
450+
],
451+
"providerCaps": { "default": 4, "fireworks": 4 }
451452
}
452453
```
453454

@@ -461,6 +462,13 @@ The resolver supplies the fixed neutral Choice option `No listed rule applies to
461462
A rule `floor` names the quota-axi `provider` and `scope` whose `effectivePercentRemaining` must be at least `min_percent` for the rule's profiles to apply.
462463
A known percentage below it makes the tool resolve among `default` instead; an absent or unknown row or unmeasured provider makes the floor unverifiable and escalates without authorizing default routing.
463464
A profile `provider` optionally names the quota-axi provider family whose rows apply to that profile; when present, profile and rule-floor provider IDs must match the strict whole-string pattern `^[a-z0-9]+(-[a-z0-9]+)*\z`.
465+
`providerCaps` is optional and bounds how many live lanes one billing provider may carry.
466+
`providerCaps.<provider>` sets that one provider's cap and `providerCaps.default` sets the cap for every provider without its own entry; an absent entry, or a value below one, falls back to a cap of 4.
467+
The provider a lane is counted against comes from the lane's recorded harness and model, with the model string deciding the identity, so two models on one pool count together even across harnesses while a different pool stays separate.
468+
A lane whose recorded endpoint is provably dead or missing no longer occupies a seat, while a lane whose endpoint cannot be proven gone keeps it.
469+
`bin/fm-provider-load.sh` prints the current per-provider `used/cap` for dispatch intake, and `bin/fm-spawn.sh` refuses a crewmate, scout, or local secondmate spawn that would push a provider past its cap (`bin/fm-provider-lib.sh` is the single owner of both rules).
470+
The cap is per home: a remote secondmate's own lanes are recorded on its host and are not counted here.
471+
Bootstrap rejects a malformed `providerCaps` - a non-object, a key that is neither a provider id nor `default`, or a value that is not a whole number of at least one - with the usual `CREW_DISPATCH:` diagnostic.
464472
Bootstrap validates resolver-only `approval`, `floor`, and present `provider` values only while typed resolution is active; without the key those inert fields and the pre-existing verified-harness baseline preserve bootstrap behavior.
465473
Typed resolution additively recognizes `gemini` because AGENTS.md section 4 verifies it for crewmate and scout dispatch.
466474
The opted-in resolver has authoritative single-provider mappings for `claude`, `codex`, `grok`, `kimi`, `cursor`, `agy`, and `muse`; every other verified harness must declare `provider` explicitly, including multi-provider `pi`, `pi-signed`, `omp`, and `opencode` and unmapped `gemini` and `rovo`.

‎docs/examples/crew-dispatch.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,6 @@
2222
"default": [
2323
{ "harness": "codex", "model": "gpt-5.5", "effort": "medium" },
2424
{ "harness": "pi", "model": "anthropic/claude-sonnet-5", "effort": "medium", "provider": "claude" }
25-
]
25+
],
26+
"providerCaps": { "default": 4 }
2627
}

‎docs/scripts.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ The shared no-mistakes gate refusal for fleet lifecycle entrypoints is summarize
107107
| `fm-backlog-transition-lib.sh` | Pair task-record changes with their backlog transitions and replay interrupted closes |
108108
| `fm-quota-axi-lib.sh` | Shared `quota-axi` compatibility floor and quota snapshot schema validation |
109109
| `fm-quota-choose.sh` | Choose the first candidate with known positive quota from an ordered harness:model list |
110+
| `fm-provider-lib.sh` | Single owner of the model-to-provider identity mapping and the per-provider live-lane concurrency cap |
111+
| `fm-provider-load.sh` | Print live lanes per billing provider against each provider's configured cap, for dispatch intake |
110112
| `fm-vendor-auth-probe.sh`| Run one hard-bounded, non-destructive authentication probe of a named vendor CLI and report the fact |
111113
| `fm-wake-drain.sh` | Present and acknowledge the current actor's claimed wake rows alongside status, outcome-backstop, decision, divergence, recovery, and supervision checks |
112114
| `fm-wake-grant.sh` | Serialize Pi supervision-branch wake-row claim activation, publication, release, and deactivation |

0 commit comments

Comments
 (0)